Pages

Wednesday, December 31, 2014

Python: test if a dictionary contains a specific key









def contains(dict, key):
    return key in dict

dict={}
dict['a']=1
dict['b']=2
dict['c']=3

print(contains(dict, 'a')) # True
print(contains(dict, 'd')) # False



Sunday, December 28, 2014

Python: delete a item from a list








  • remove the first matching element:
    if e in list:
        list.remove(e)
  • remove all occurrences:
    while e in list:
        list.remove(e)
  • EAFP style: remove the first occurrence:
    try:
        list.remove(e)
    except ValueError:
        # not in the list
        pass
    
  • EAFP style: remove all occurrences:
    while True:
        try:
            list.remove(e)
        except ValueError:
            break
    

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.




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