Pages

Saturday, December 27, 2014

Python: del or assign None?








>>> x=1
>>> print x
1
>>> del x
>>> print x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined
>>> x=1
>>> print x
1
>>> x=None
>>> print x
None

see also




Tuesday, December 23, 2014

synchronized method in python








Java code

class AClass {
    private int count =0;

    public synchronized inc(){
        count++;
    }

    public synchronized dec(){
        count--;
    }
}

Python code

import threading

class AClass(object):
    def __init__(self):
        self.__count = 0;
        self.__lock = threading.RLock()

    def inc(self):
        with self.__lock:
            self.__count += 1

    def dec(self):
        with self.__lock:
            self.__count -= 1


see also




synchronized static method in python








Java code

class AClass {
    private static int _count = 0;

    public static synchronized inc(){
        _count ++;
    }
    
    public static synchronized dec(){
        _count --;
    }
}

Python code

import threading

class AClass(object):
    __count = 0
    __lock = threading.RLock()

    @classmethod
    def inc(cls):
        with cls.__lock:
            cls.__count += 1

    @classmethod
    def dec(cls):
        with cls.__lock:
            cls.__count -= 1



Tuesday, October 21, 2014

Python: check if file or directory exists








  • os.path.exists to check if file or directory exists.
    import os
    os.path.exists('/tmp/1.txt')
    os.path.exists('/tmp')
    
  • os.path.isfile to check if file exists.
    import os
    os.path.isfile('/tmp/1.txt')
    



Python: Get file absolute path








Use os.path.abspath function:
import os
os.path.abspath('abc/abc.txt')



Python: get the index of a char in a string








find and index method are available. The difference is that find returns -1 when what you're looking for isn't found, index throws an exception.
s='abc'
print(s.index('b')) # 1
print(s.find('b'))  # 1
print(s.find('d'))  # -1
print(s.index('d')) # exception



Python: string types in 2.x and 3.x








  • In Python 2.x, basestring is the base class for both str and unicode, while types.StringType is str. If you want to check if something is a string, use basestring. If you want to check if something is a ascii (bytestring), use str and forget about types.
  • Since Python 3.x, types not longer has StringType; str is always unicode. basestring no longer exists.