Speaker
Nina Zaharenko (@nnja)
Material
Note
Magic methods: __func__
- Custom iterator
__iter__
: Make classesiterable
- returns an iterator
__next__
: Make classiterator
- raises
StopIteration
when there is no more items to return
- raises
- Use a generator when your iterator doesn't need to maintain a lot of state
- Method magic
getattr(object, name, default)
- call function by
name
string - use case
- cli tool with dynamic commands
- call function by
functool.partial(func, *args, **kwargs)
Context manager
- perform an action before and/or after an operation
- use case
- close a resource (e.g., file, network, database)
- perform clean up before/after function call
- feature flags: turn feature of your application on and off easily
- A/B Testing
- Rolling Releases
from contextlib import contextmanager
Decorators
- Wrap a function in another function to do something
- before the call
- after the call
- with provided arguments
- Problem: lost context using a decorator
- Solution:
from contextlib import wraps
- Solution:
- Use case
- logging
- timing
- validation
- rate limiting
- mocking/patching
ConextDecorator
- By use it, you can write classes that can be used both as decorator and context managers
- It's included if implemented through
from contextlib import contextmanger
.
- It's included if implemented through