## Metaclasses
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` `metaclass` exists to allow library code works nicely
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
+ y --> __add__
x repr(s) --> __repr__
--> __call__ x()
# Meet the `__builtins__` library
import builtins
__build_class__
class Nok:
pass
# This is possible because class is a Python keyword
Nok()
# You can actually construct a class with a function.
"Nok") builtins.__build_class__(
TypeError: __build_class__: not enough arguments
Generator
- Eager vs Lazy
- Process when data comes - memory efficient and no wait.
yield
control - 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