Python common build-in functions

LORY
4 min readDec 28, 2020

--

any and all

any([any_one, is_true])all([all, must, true])

chr and ord

convertion between char and ascii

>>> chr(123)
'{'
>>> ord('a')
97

getattr, hasattr, setattr and delattr

>>> class x:
... a='1'
... b='2'
...
>>> hasattr(x,'a')
True
>>> hasattr(x,'c')
False
>>> getattr(x,'a')
'1'
>>> getattr(x,'b')
'2'
>>> setattr(x,'c','3')
>>> getattr(x,'c')
'3'
>>> delattr(x,'b')
>>> hasattr(x,'b')
False
>>> getattr(x,'b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'x' has no attribute 'b'

callable

check if the specified object is callable

if the specified object is callable
>>> callable(123)
False
>>> class x :
... pass
...
>>> callable(x)
True
>>> def y():
... pass
...
>>> callable(y)
True

sorted

Return a sorted list of objects

>>> sorted([{'a':1,'b':1.5},{'a':3,'b':1},{'a':2,'b':3}], key = lambda x:x['a'])
[{'a': 1, 'b': 1.5}, {'a': 2, 'b': 3}, {'a': 3, 'b': 1}]
>>> sorted([{'a':1,'b':1.5},{'a':3,'b':1},{'a':2,'b':3}], key = lambda x:x['b'])
[{'a': 3, 'b': 1}, {'a': 1, 'b': 1.5}, {'a': 2, 'b': 3}]
>>> sorted([{'a':1,'b':1.5},{'a':3,'b':1},{'a':2,'b':3}], key = lambda x:x['b'],reverse=True)
[{'a': 2, 'b': 3}, {'a': 1, 'b': 1.5}, {'a': 3, 'b': 1}]

hash

return hash value of objects (class implementation may override __hash__)

>>> hash((1,2,3))
-2022708474
>>> hash('a')
550789989
>>> hash(123)
123
class x :
def __init__(self, x1, y1):
self.x1 = x1
self.y1 = y1
def __hash__(self):
return hash(self.x1) * hash(self.y1)
>>> hash(x(1,2))
2
>>> hash(1)
1
>>> hash(2)
2

bin, bytes, bytearray

convert integer to binary

>>> bin(15)
'0b1111'

Convert number or string to bytes

>>> bytes(5)
b'\x00\x00\x00\x00\x00'
>>> bytes('5','utf-8')
b'5'
>>> bytearray(5)
bytearray(b'\x00\x00\x00\x00\x00')
>>> bytearray('5','utf-8')
bytearray(b'5')

Difference: bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.

dir, vars

dir : Returns a list of the specified object’s properties and methods

x=[1,2,3,4]
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> x

vars : Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

>>> class x:
... pass
...
>>> vars(x)
mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'x' objects>, '__weakref__': <attribute '__weakref__' of 'x' objects>, '__doc__': None})

Enumerate, range

create enumerable list and loop

>>> x=[1,2,3,4]
>>> for id, value in enumerate(x):
... print(id, value)
...
0 1
1 2
2 3
3 4
>>> for i in range(0,5):
... print(i)
...
0
1
2
3
4

eval and exec

dynamic execute string as code

>>> x = 'print(55)'
>>> eval(x)
55
>>> x = 'name = "John"\nprint(name)'
>>> exec(x)
John

filter and map

x=[1,2,3,4]
>>> list(filter(lambda x1:x1%2==0,x))
[2, 4]
>>> list(map(lambda x1:x1*2, x))
[2, 4, 6, 8]

reduce is not included in build-in function . can import functools and use it . the usage is similar to filter and map .

>>> import functools
>>>
>>> lis = [ 1 , 3, 5, 6, 2, ]
>>> print (functools.reduce(lambda a,b : a+b,lis))
17

hex

return hex represent of number .

>>> hex(123)
'0x7b'

id

id of variable grantee unique through its lifecycle

>>> id(1)
1357162416
>>> id('a')
20207552
>>> class x:
... pass
...
>>> id(x)
51577344
>>> id(x())
20248560

isinstance , issubclass, type

helper function to check object is instance of class or sub class and type

>>> x=(1,2)
>>> isinstance(x,int)
False
>>> isinstance(x,tuple)
True
>>> class x :
... pass
...
>>> issubclass(x, object)
True
>>> isinstance(x, object)
True
>>> type(1)
<class 'int'>
>>> type('a')
<class 'str'>
>>> class x:
... pass
...
>>> type(x())
<class '__main__.x'>

list, dict , len

create a list and dict

>>> list('abc')
['a', 'b', 'c']
>>> list(range(0,5))
[0, 1, 2, 3, 4]
>>> dict(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> d1={'1':1,'2':2}
>>> dict(**d1)
{'1': 1, '2': 2}
get len of object
>>> len('1234')
4
>>> len([1,2,3,4])
4
>>> len((1,2,3))
3
>>> class x :
... def __len__(self):
... return 5
...
>>> len(x())
5

iter, reversed

iter : return object iterator 
>>> x = iter([1,2,3])
>>> print(next(x))
1
>>> print(next(x))
2
>>> print(next(x))
3
>>> print(next(x))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
reversed : return reversed iterator
>>> x = reversed([1,2,3])
>>> print(next(x))
3
>>> print(next(x))
2
>>> print(next(x))
1

Locals, globals

Returns an updated dictionary of the current local/global symbol table

>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 1, 'y': <class '__main__.y'>}
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

divmod, abs, min, max, sum, pow, round

math helper functions

zip

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> for z in zipped:
... print(z)
...
(1, 4)
(2, 5)
(3, 6)

str and repr, format

define str ,format and repr for class

>>> str(123)
'123'
>>> repr(123)
'123'
>>> import time
>>> time.time()
1609084728.8249786
>>> str(time.time())
'1609084733.521007'
>>> class x :
... def __str__(self):
... return 'x string '
...
... def __repr__(self):
... return 'x'

... def __format__(self, f):
... return 'x123'
...
>>> x()
x
>>> str(x())
'x string '
>>> format(x())
'x123'

--

--

LORY
LORY

Written by LORY

A channel which focusing on developer growth and self improvement

No responses yet