Built-in functions

Fast C implementations of basic functionalities

Methods in this page



For accessing attributes

Property

Can be used as a class or a decorator to provide easy “hidden” attributes.

As a class, the constructor expects to receive functions to get, set and del the attribute along with some documentation

class myProp:
    def __init__(self, x=None):
        self._x = None
        
    def _get(self):
        return self._x*3 # just to show the difference with normal attr
    
    def _set(self, x):
        self._x = x
        
    def _del(self, x):
        self._x = None
        
    x = property(_get, _set, _del, "THE X!")
    
myp = myProp()
myp.x = 3
print(myp.__dict__)
myp.x
{'_x': 3}
9

As a decorator, can make the code more readable. First define the property getter then the = and del overloaders

class myPropDec:
    def __init__(self, x=None):
        self._x = None
        
    @property
    def x(self):
        return self._x*3 # just to show the difference with normal attr
    
    @x.setter
    def x(self, x):
        self._x = x
        
    @x.deleter
    def x(self, x):
        self._x = None
    
myp = myPropDec()
myp.x = 3
print(myp.__dict__)
myp.x
{'_x': 3}
9

Staticmethod

Can be used as a class or a decorator to provide easy static methods to classes (no implicit self argument).

As a class, the staticmethod constructor expects to receive a function.

def staticTest():
    print(42)
    
class testStatic:
    pass

testStatic.stat = staticmethod(staticTest)
testStatic().stat()
testStatic.stat()
42
42

Alternatively, if not static, the method uses the object as the first argument implicitly - self - raising an error when called by the class.

def nonstaticTest(x):
    print(x)
    
testStatic.nonstatic = nonstaticTest
testStatic().nonstatic()
try:
    testStatic.nonstatic()
except TypeError as e:
    print(f"TypeError: {e}")
<__main__.testStatic object>
TypeError: nonstaticTest() missing 1 required positional argument: 'x'

or an error when called by an instance, if it expects no arguments

def nonstaticTest():
    print(42)
    
testStatic.nonstatic = nonstaticTest
testStatic.nonstatic()
try:
    testStatic().nonstatic()
except TypeError as e:
    print(f"TypeError: {e}")
42
TypeError: nonstaticTest() takes 0 positional arguments but 1 was given

As a decorator, makes the code cleaner.

class staticTestClass:
    
    @staticmethod
    def stat():    # does not need self
        print(42)
        
staticTestClass().stat()
staticTestClass.stat()
42
42

Classmethod

Wrapper to define that the method receives the class as an implicit argument, not the instance calling.

class classmethodTestClass:
    """Documentation for classmethodTestClass"""
    
    @classmethod
    def test(self):
        print(self.__doc__)
        
    def testInst(self):
        print(self.__doc__)
        
testObj = classmethodTestClass()
testObj.test()
testObj.testInst()
Documentation for classmethodTestClass
Documentation for classmethodTestClass

If we modify the documentation for the instance object we can see how the self in @classmethod refers to the class.

testObj.__doc__ = """Documentation for an instance of classmethodTestClass"""
testObj.test()
testObj.testInst()
Documentation for classmethodTestClass
Documentation for an instance of classmethodTestClass

If we modify the method test for a regular function, the argument will be the implicit self.

classmethodTestClass.test = lambda self: print(self.__doc__)
testObj.test()
Documentation for an instance of classmethodTestClass

For this reason, to run an instance method within the class, an argument mas be passed.

classmethodTestClass.test(classmethodTestClass)
classmethodTestClass.testInst(classmethodTestClass)
Documentation for classmethodTestClass
Documentation for classmethodTestClass

Super

super(type, object_or_type=None)

Accessing inherited class attributes. Gets object_or_type.__mro__ starting from type on.

class A:
    def method(self):
        print("A")
        
class B(A):
    def method(self):
        print("B")
        super().method()
        
class C(B):
    def method(self):
        print("C")
        super(B,self).method()

test = C()
test.method()
C
A

You can control the sequence in the resolution order by changing the classes __mro__ (Method Resolution Order), but for that a “hack” using metaclasses is necessary. Simply trying to set it does not cut it.

See pydoc.

class D(C):
    __mro__ = (B, A, C, object)
    
    def method(self):
        print("D")
        super().method()

testMRO = D()
testMRO.method()
D
C
A

Get Attribute and Has Attribute

gettattr(object, name) and hasattr(object, name)

getattr() works like dict.get, only when not found and with no default, raises AttributeError.

class attrHolder:
    ...
    
test1 =  attrHolder()
test1.text = '42'
getattr(test1,'text')
'42'

In case of non existing attribute:

try:
    getattr(test1,'42')
except AttributeError:
    print("What is 6x9?")
What is 6x9?

hasattr(obj,name) works by calling getattr(obj,name) and capturing the AttributeError to return False

hasattr(test1,'text')
True

Set Attribute

settattr(obj, name, value)

Set an attribute in object.

class setTest:
    pass

setattr(setTest,'x','1')
setTest.x
'1'

Dir

dir(object=None)

Lists attributes for using __dir__() and __dict__. See __dir__ and for details pydocs.

Callable

callable(object)

Weather an object is callable: callable(x): return hasattr(x,'__call__'). See _call_().

callable(42), callable(int)
(False, True)
import random
print(f"current score:\n{dir()[-12:]}\n")
print(f"random module:\n{dir(random)[-12:]}\n")
print(f"mock class:\n{dir(attrHolder)[-12:]}\n")
current score:
['myp', 'nonstaticTest', 'quit', 'random', 'setTest', 'staticTest', 'staticTestClass', 'test', 'test1', 'testMRO', 'testObj', 'testStatic']

random module:
['paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

mock class:
['__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

back to top

Default attributes

Defaults and Keyword Defaults

__defaults__
__kwdefaults__

A way to get the function’s default arguments and keyword-only default arguments

def aFunc(a=2,*b,c=10):
    pass

print(aFunc.__defaults__, "\t", aFunc.__kwdefaults__)
(2,)     {'c': 10}

Name and Code

__name__
__code__

Name of function/method and related code object, which can be eval()

def pFunc():
    print('42')
    
print(f"func: {pFunc.__name__} has code:\n{pFunc.__code__}")

exec(pFunc.__code__)
func: pFunc has code:
<code object pFunc at 0x000001F57E64C870, file "C:\Users\Aang\AppData\Local\Temp\ipykernel_11404\2946981887.py", line 1>
42
class test:
    ...
    
test.__name__
'test'

back to top

Access to iterables/iterators

Enumerate

enumerate(iter, start=0)

enumerate(x) returns an iterator of pairs (index, item), where item is next(x._iter__()).

  • Optional argument for start index.
for x in enumerate("abcdef", start=42): print(x)
(42, 'a')
(43, 'b')
(44, 'c')
(45, 'd')
(46, 'e')
(47, 'f')

Filter

filter(f, iter)

Equivalent to (x for x in iter if f(x))

def myF(x):
    return x[0]%2

(*filter(myF, enumerate("abcdef", start=42)),)
((43, 'b'), (45, 'd'), (47, 'f'))

Map

map(f, iter, \*iters)

Equivalent to (f(x) for x in zip(iter,*iters))

list(map(max, (1,2,3,4,5), (9,3,1,7), (10,1,2,5)))
[10, 3, 3, 7]

Reversed

reversed(seq)

seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).” [extract from pydoc].

back to top

Conversion

Binary conversion

bin(int) -> str

bin(x) first calls x.__index__() to get integer then converts to binary representation string.

print(bin_var := bin(int("42")), type(bin_var)) #no str.__index__
int(bin_var, base=2)

Character coding

ord(str) -> int
chr(int) -> str

converting unicode char -> int and int -> unicode char

len(str) == 1
0 < i < int('0x10FFFF', base=16)
print("".join([chr(x) for x in range(65,69)]))
ord((*"A",)[0]) # str has to be len 1
ABCD
65

Got error with NBDEV using greek letters

Hexadecimal

hex(int) -> str

converting a number to hexadecimal representation string

hex(18)
'0x12'

back to top

Math Operations

Power

pow(base, exp, mod=None)

Calculates (base**exp)%mod in a more efficient way, allegedly. Details on modulus operations here

898 ns ± 34.1 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
1.78 µs ± 106 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

back to top