PRACTICAL PYTHON
DESIGN PATTERNS
Ramanathan R
Zentropy Technologies
Slide 2
Slide 2 text
About me
■ Co-Founder/Director of Zentropy Technologies – We do end to end implementations
of Fin Tech and Data science projects
■ Before finding Zentropy, had a working experience of 10 years in a leading Hedge
fund
■ Part of the organizing team of PyCon India, 2018
Slide 3
Slide 3 text
Disclaimer J
■ This presentation is based on Python 3 and later
■ Almost all of this works in Python 2 as well – However, not really tested by Presenter
■ Tit-bits gained over a period by working in Python.
Slide 4
Slide 4 text
What are classes in Python?
Slide 5
Slide 5 text
Classes in Python
■ First class supported entities
■ Technically class is an instance of type
■ Sugar over the native ‘type’ in Python
Slide 6
Slide 6 text
What is type in Python?
Slide 7
Slide 7 text
type.__doc__
Init signature: type(self, /, *args, **kwargs)
Docstring:
type(object_or_name, bases, dict)
Usages:
1. type(object) -> the object's type
2. type(name, bases, dict) -> a new type Type: type
Slide 8
Slide 8 text
Create a class using a type
type(name, bases, dict)
■ name – Name of the Class
■ bases – Base classes of the class
■ dict – The initial set of attributes and methods
Slide 9
Slide 9 text
Lifecycle of a class magic methods
Instance
requested
__new__()
call
__init__()
call
Instance
returned
Slide 10
Slide 10 text
Quick Recap
■ Class is an instance of ’type’ – the holy grail
■ Type can be used to create dynamic classes
■ Life cycle of a class creation
– It applies for the Class creation (instance of type).
Slide 11
Slide 11 text
What can I do with ‘type’?
Slide 12
Slide 12 text
Meta Classes
■ A subclass of ‘type’
■ Change the way the class behaves
■ Commonly called ‘Black magic’ in Python – Use it only when actually needed
Slide 13
Slide 13 text
The gory details of syntax
■ Creating a Meta class
class MyMetaClass(type):
pass
■ Using a Meta class
class MyClass(metaclass=MyMetaClass):
pass
Slide 14
Slide 14 text
The big picture
type class
Meta class
(child of type)
instance
Slide 15
Slide 15 text
Lifecycle of Meta class based class
__new__()
__init__()
__call__()
Meta class
__new__()
__init__()
__call__()
Actual class
__new__()
__init__()
Actual class creation
__call__()
__new__()
__init__()
Class instance creation
Slide 16
Slide 16 text
The broad idea
■ Class Behavior changes –
– Use __new__() and __init__() of meta class
■ Change Behavior of instance of the class (typical object)
– Use __call__() of meta class
References
■ Python 3 Meta Programming by David Beazley -
https://www.youtube.com/watch?v=sPiWg5jSoZI
■ Practical Metaclasses and Descriptors by Sim Zacks - -
https://www.youtube.com/watch?v=Nay7lRPwnC4
■ Stack Overflow
Slide 28
Slide 28 text
Questions?
Slide 29
Slide 29 text
PyCon India, 2018
■ October 5-9, 2018 @ Hyderabad, India
■ Tenth Anniversary
■ CFP and Tickets open
■ Keynote speakers
– Carol Willing
– Travis Oliphant
– Armin Ronacher
■ More details @ in.pycon.org