The Magic of Python

30-minute Talk - date TBD at time TBD in room TBD

Python has many built in magic functions that are used internally by classes for certain actions. For example, adding two numbers calls the __add__ method and iterating over a list calls the __iter__ method. I will expand on this Duck Typing principle and enumerate over a range of magic methods that you can add to your classes to have a cleaner codebase.

Introduction [4-5 minutes]

I will introduce myself, and continue to give an overview of what magic methods are. I will then expand on this Duck Typing principle. Then, I will be transitioning into introducing the classes of magic methods along with examples for each class.

Basic magic methods [4-5 minutes]

We will start off by looking at magic methods that offer basic customization. You might already be aware of methods like __init__ and __new__, but we will also go over methods that let you print out a readable version of your objects, methods that allow you to compare objects and a method to make your objects hashable amongst others.

Numerical magic methods [4-5 minutes]

Next, we will go over emulating numeric types and how you can write classes for objects that allow for arithmetic operations (Examples: +, -, *, @, /, //, %).

Magic methods to emulate sequences [5-6 minutes]

We will then go over how you can emulate container types of sequences (like lists) or mappings (like dictionaries). You will see the methods you can implement to index, slice, or iterate over your object.

Writing a context manager [3-4 minutes]

We then look at the __enter__ and __exit__ magic methods and how they help implement context managers.

Extending functionality using abc module and conclusion [5 minutes]

We conclude by looking at some Abstract Base Classes in the abc module that will allow for you to get free functionality if you provide the implementation for certain magic methods on your class.

Presented by: