-
Python: Protocols
Python interpreter recognizes special methods like __method__() and invokes them in hard-wired situations. A group of related such “dunder” or “double underscore” methods are called a protocol. An object that implements a protocol, can be used in idiomatic ways. Object Protocol About object creation, initialization, destruction, and representation. x = SomeClass(args) is translated into: It…
-
Python: Objects
All data in a Python program are objects. An object has: identity, type, and value. Type is also object. Data and methods are an object’s attributes. Even an operator like a + 10 is mapped to a method a.__add__(10) and thus is an attribute. Assigning object creates reference. Shallow copy of a container object creates…
-
Python: GIL
GIL or Global Interpreter Lock is an implementation details of CPython. Reference counting is how CPython implements automatic garbage collection. With multiple threads, synchronization is required for correct reference counting. CPython takes a process-wide lock and that is GIL. Consequently, with CPython, for a single process, only one Python byte-code (by a thread) can execute…
-
Python: Synchornization
All synchronization primitives are available from threading and multiprocessing modules. A primitive from threading module synchronizes between threads from the same process. A primitive from multiprocessing module synchronizes between threads across multiples processes and is heavier. Primitives:
-
Python: Assertions
Execution of assert‘s is controlled by __debug__ variable. In optimized mode (-o or -oo), __debug__ is False, so assert‘s are no-op. Best practice:
-
Python: Exceptions
Exception is a standard way of propagating errors. Exceptions: Best practice: Context Manager helps with resources that need closing even on exceptions. contextlib module has useful functions:
-
Exponentiation
is a shorthand for repeated multiplication. For example, . In other words, to compute the value of we multiply three ‘s. . We can generalize: . Since , we can generalize: . . However, . Since is undefined, is also undefined. . Thus is the reciprocal of . Obviously, is undefined. What about ? We…
-
Division by zero
For two real numbers and if we can find a unique real number such that then we say and that is the definition of division. A division between real numbers is undefined if we fail to find any or there are more than one choices for . These may happen when . For example, would…
-
Sign of product
Sign of a product of two numbers comes down to: , , , and . For example, . Since is the multiplicative identity, by definition: . So, , , and . What should be? By definition: . More generally, . Since is the multiplicative identity, . Assuming negative numbers abide by associative law of multiplication:…