## Metaclasses
`metaclass` exists to allow library code works nicely with user code. For example, how can a library author ensure that its user will follow its protocol and not using it wrongly? Again you can dive into `__new__` for ensuring that. In practice, the code is already written for `abc` and people use `@abstractmethod` `abc.ABCMeta`This presentation introduce three concepts, decorator, generator and contextmanager. The presenter explains that Python is a Protocol oriented langauge brilliantly and put these three concepts together to illustrate a story. Ultimately, being a Python expert doesn’t mean that you write advance syntax, but using these pattern wisely with simple code. These three concepts both serves its own puprose and are orthogonal to each other, yet working nicely when they are composed together.
Meet the Python Data Model
With python, there are almost always a lower level __ method corresponds to a higher-level function/syntax. It’s useful to change these behavior and understand how the Python Data Model work. You can find all the dunder __ method here. https://docs.python.org/3/reference/datamodel.html
x + y --> __add__
repr(s) --> __repr__
x() --> __call__# Meet the `__builtins__` library
import builtins
__build_class__
class Nok:
pass
Nok() # This is possible because class is a Python keyword
# You can actually construct a class with a function.
builtins.__build_class__("Nok")TypeError: __build_class__: not enough arguments
Generator
- Eager vs Lazy
- Process when data comes - memory efficient and no wait.
yieldcontrol - interleaving. Idea of executing some code, then passing the output back to user, do something and continue.
def temptable(cur):
print("Create Table")
yield
print("Drop Table")
class T:
def __enter__(self):
self.gen = temptable("123")
next(self.gen)
return self
def __exit__(self, *args):
return next(self.gen, None)
with T():
print("Finish")
Create Table
Finish
Drop Table