Python - herougo/SoftwareEngineerKnowledgeRepository GitHub Wiki
Asyncio
- mixing asyncio with decorators: https://stackoverflow.com/questions/42043226/using-a-coroutine-as-decorator
def foo(f):
async def wrapper(*args, **kwargs):
return await f(*args, **kwargs)
return wrapper
@foo
async def boo(*args, **kwargs):
pass
-
- Personal notes: CPU context switching: CPU saves the thread state and does something else.
SQLAlchemy
- there are 2 options for having your code interact with databases:
- Gateway classes which act as the interface code and SQL queries (results in lots of code)
- Object-Relational Mapping (ORM) use an OO paradigm for DB data manipulation (e.g. SQLAlchemy)
- this works
class Parent(Base): # Booking
__tablename__ = "parent"
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey("child.id"), nullable=True)
class Child(Base): # BookingPatchEvent
__tablename__ = "child"
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey("parent.id"))
parent = relationship(Parent, uselist=False, foreign_keys=[parent_id])
- questions:
- When you define a relationship, what happens behind the scenes when you access that attribute?
- What if you overwrite the attribute with something else?
Metaclasses
Source: (optional) https://www.youtube.com/watch?v=NAQEj-c2CI8
- type of a class is "type" (e.g. type(MyClass))
- "type" is the metaclass
- this creates a class
MyClass = type('MyClass', (BaseClass,), {'attr1': 0, 'method1': my_method})
- this ...
class Meta(type):
def __new__(cls, class_name, bases, attrs):
# called when the class itself is created (not instances of the class)
print(attrs)
result = super().__new__(cls, class_name, bases, attrs)
return result
class Dog(metaclass=Meta):
x = 5
def hello(self):
print('hi')
# attributes (x and hello) are printed without needing to create a Dog object
Code Quirks
Code Quirk 1
- this works
class A:
a = 'hello'
b = a
assert A().b == 'hello'