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
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
if e in list: list.remove(e)
while e in list: list.remove(e)
try: list.remove(e) except ValueError: # not in the list pass
while True: try: list.remove(e) except ValueError: break
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.
>>> 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
class AClass { private int count =0; public synchronized inc(){ count++; } public synchronized dec(){ count--; } }
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
class AClass { private static int _count = 0; public static synchronized inc(){ _count ++; } public static synchronized dec(){ _count --; } }
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
import os os.path.exists('/tmp/1.txt') os.path.exists('/tmp')
import os os.path.isfile('/tmp/1.txt')
import os os.path.abspath('abc/abc.txt')
s='abc' print(s.index('b')) # 1 print(s.find('b')) # 1 print(s.find('d')) # -1 print(s.index('d')) # exception
with open('myfile.txt') as f: return [line for line in f if len(line)>80]
class Iterator(object): def next(self): pass class Iterable(object): def __iter__(self): return Iterator()
class AClass(object): def __init__(self): self._list = [1,2,3] def __len__(self): return len(self._list) a=AClass() print(a.__len__()) # 3 print(len(a)) # 3
class AClass(object): def __init__(self): pass @staticmethod def a(): AClass.b() @staticmethod def b(): pass
import zlib import sys import urllib2 def __zlib_csum(url, func): if isinstance(url, basestring if sys.version_info[0] < 3 else str): url = urllib2.Request(url) f = urllib2.urlopen(url) csum = None try: chunk = f.read(1024) if len(chunk)>0: csum = func(chunk) while True: chunk = f.read(1024) if len(chunk)>0: csum = func(chunk, csum) else: break finally: f.close() if csum is not None: csum = csum & 0xffffffff return csum def crc32(url): return __zlib_csum(url, zlib.crc32) def adler32(url): return __zlib_csum(url, zlib.adler32) if __name__ == '__main__': print(hex(crc32('file:/tmp/111.zip'))) print(hex(adler32('file:/tmp/111.zip')))
def copy(if_path, of_path): with open(if_path, 'rb') as in_file, open(of_path, 'wb') as out_file: while True: chunk = in_file.read(1024) if chunk: out_file.write(chunk) out_file.flush() else: break
import struct buffer = bytearray(8) buffer[0]=1 buffer[1]=1 struct.pack_into('>ih', buffer, 2, 100, 200) # to convert the array to str print(bytes(buffer))
import struct def int_to_bytes(value, size, big_endian=False): bs = [] for i in range(size): offset = i * 8 b = chr((value & (0xff << offset)) >> offset) if big_endian: bs.insert(0, b) else: bs.append(b) return b''.join(bs) def int32_to_bytes(value, big_endian=False): return int_to_bytes(value, 4, big_endian) def int64_to_bytes(value, big_endian=False): return int_to_bytes(value, 8, big_endian) if __name__ == '__main__': # the two commands below do the same print(repr(int64_to_bytes(65536, big_endian=True))) print(repr(struct.pack('>Q', 65536)))
':'.join(x.encode('hex') for x in 'Hello World!')
>>> ':'.join(x.encode('hex') for x in 'Hello World!') '48:65:6c:6c:6f:20:57:6f:72:6c:64:21'
b''.join(['abc', '\x01\x02\x03', 'efg'])
>>> b''.join(['abc', '\x01\x02\x03', 'efg']) 'abc\x01\x02\x03efg'
class Animal: DOG = 1 CAT = 2 x = Animal.DOGor
class Animal: DOG, CAT = range(2) x = Animal.DOG
class Animal(Enum): DOG = 1 CAT = 2 x = Animal.DOGor equivalently:
from enum import Enum Animal = Enum('Animal', 'DOG CAT') x = Animal.DOG
def parse_bool(s): return s.lower() in ("yes", "true", "T", "1")
bool('foo') # True bool('') # FalseYou can not use the above function to parse boolean from string.
if isinstance(var, int): print("It is integer")On python 2:
if is instance(var, (int, long)): print("It is integer")
import sys if isinstance(var, basestring if sys.version_info[0]<3 else str): print("it is string") # var is string
x = true_value if condition else false_value
if isinstance(s, basestring if sys.version_info[0]<3 else str): print('It is a str.')
dict = { 'a':1, 'b':2 } dict = { k: str(dict[k]) for k in dict.keys() } print(dict)
class A: def __init__(self): pass def main(): print("Hello World") if __name__ == '__main__': main()
class MyClass: def method(self): ':rtype unittest.TestCase'
class MyClass: def method(self, a): ':type a: TestCase' #Note that just the class name is accepted, but in this case, #it'll search for a TestCase class in the whole workspace
class MyClass: def method(self, a): ':param TestCase a:'
class MyClass: def method(self, lst): #Can be on the same line for a in lst: #: :type a: GUITest a.;
class MyClass: def method(self, lst): #Or on the line before #: :type a: GUITest for a in lst: a.;
class MyClass: def method(self, lst): #If commented as a docstring must be on the #line after for a in lst: ': :type a: GUITest' a.;
class MyClass: def method(self): '@rtype unittest.TestCase'
class MyClass: def method(self, a): '@type a: TestCase' #Note that just the class name is accepted, but in this case, #it'll search for a TestCase class in the whole workspace
[str(elem) for elem in list]..
import xml.etree.ElementTree as ET ... ...When executing the file, it raises the following error:
ImportError: No module named etree.ElementTreeAccording the stackoverflow post, it was caused by the moudle file name xml.py, rename the xml.py to something else resolved the issue.
import xml.etree.ElementTree as ET # element is an xml.etree.ElementTree.Element object xmlstr = ET.tostring(element, encoding='utf8', method='xml')
import xml.etree.ElementTree as ET tree = ET.parse('/home/wilson/my.xml') root = tree.getroot()
import xml.etree.ElementTree as ET root = ET.fromstring('1')
class A: def object_m(self,x): print "executing object_m(%s,%s)"%(self,x) @classmethod def class_m(cls,x): print "executing class_m(%s,%s)"%(cls,x) @staticmethod def static_m(x): print "executing static_m(%s)"%xAccording to stackoverflow:
def f(arg): if isinstance(arg, ClassA): print('A') elif isintance(arg, ClassB): print('B') elif issubclass(arg, ClassC): print('subclass of C') else: print("D")
def f(arg): if type(arg) is str: print "str" elif type(arg) is int: print "int" elif type(arg) is dict: print "dict" else: print "unsupported"
all_descendants = list(element.iter())
children = list(element)
for name in dict.keys(): print(name) print(dict[name])
values = [ dict[name] for name in dict.keys() ]
list2 = [ unicode(e.strip()) for e in list1 ]
list2 = [ unicode(e.strip()) if e is not None else '' for e in list1 ]