Classes and Modules

Classes wrap around a dictionary

Classes are a way to couple data and functionality.

You might think of classes as powerful tools that are quite different from functions and data structures, but classes are pretty much just a way to tightly couple a dictionary to some functions.

Methods are just functions that live on a class

Methods are functions that are attached to a class.

>>> class AwesomeThing:
...     def __init__(self, my_life=42):
...         self.my_life = my_life
...     def some_method(self):
...         print("You just called an awesome method!")
...
>>> my_thing = AwesomeThing()
>>> my_thing.some_method()
You just called an awesome method!

A method is really just a function that accepts an instance of a class as its first argument. We call that first argument self by convention, but it could be named anything at all.

When you call a method on an object, Python looks up the type of that object (the words “type” and “class” are synonyms in Python) and it calls the function of the same name on that object, passing in the actual instance as the first argument (called self by convention) automatically.

So these two lines of code do the same thing:

>>> my_thing.some_method()
You just called an awesome method!
>>> AwesomeThing.some_method(my_thing)
You just called an awesome method!

This is true of every method, even on classes that are built-in to Python. So these two lines are equivalent:

>>> numbers = [2, 1, 3, 5, 8]
>>> numbers.reverse()
>>> numbers
[8, 5, 3, 1, 2]
>>> list.reverse(numbers)
>>> numbers
[2, 1, 3, 5, 8]

And so are these:

>>> greetings = "Hello there!"
>>> greetings.upper()
'HELLO THERE!'
>>> str.upper(greetings)
'HELLO THERE!'

Note that you shouldn’t usually call a function on a class and pass in the instance as the first argument because that looks a bit weird. But you can. That’s what Python does under the hood every time we call a method on an object.

Note

Technically there’s a bit more to how methods work. Every function in Python is actually a descriptor, which means functions have a __get__ method that Python automatically calls whenever that attribute is looked up on a class instance.

Python’s descriptor protocol is very advanced and you don’t really need to know about it… though I’ll mention it again when we see properties.

Attributes live in a dictionary

Python’s classes bundle state and functionality.

The functionality is handled by methods, which (as we saw) are functions attached to a class.

The state is handled by attributes. How do attributes work?

Well, attributes are actually just keys in a dictionary. Every class instance has a __dict__ dictionary that it uses to store a key-value pair of all its attributes:

>>> my_thing.__dict__
{'my_life': 42}

We can add a new attribute to a class instance or update the value for an attribute at any time and when we do, it’ll update that dictionary:

>>> my_thing.pugs = 1
>>> my_thing.my_life = "Busy!"
>>> my_thing.__dict__
{'my_life': 'Busy!', 'pugs': 1}

We could even modify the dictionary directly to update a class instance’s attributes:

>>> my_thing.__dict__['pugs'] = 2
>>> my_thing.__dict__
{'my_life': 'Busy!', 'pugs': 2}

Though you typically wouldn’t want to do that. If you do need to dynamically work with attributes on a class instance based on strings that represent attribute names, you should use Python’s built-in hasattr, getattr, setattr, and delattr functions instead.

>>> hasattr(my_thing, 'color')
False
>>> setattr(my_thing, 'color', 'purple')
>>> my_thing.__dict__
{'my_life': 'Busy!', 'pugs': 2, 'color': 'purple'}
>>>
>>> if hasattr(my_thing, 'color'):
...     my_color = getattr(my_thing, 'color')
...
>>> my_color
'purple'
>>> delattr(my_thing, 'color')
>>> my_thing.__dict__
{'my_life': 'Busy!', 'pugs': 2}

Attribute lookups aren’t quite as simple as looking in an object’s __dict__ dictionary, since Python also looks on the object’s class, its parent classes, and so on. Using the built-in getattr function and friends will use the same lookup mechanisms that Python usually uses to lookup attributes.

Note

Note that this __dict__ dictionary isn’t always used. Some classes store their attributes in a slightly more restrictive but more memory efficient way, using __slots__.

Most classes you’ll encounter in Python use the default __dict__ dictionary though.

Classes also have a __dict__ dictionary that stores their attributes:

>>> AwesomeThing.__dict__
mappingproxy({'__module__': '__main__', '__init__': <function AwesomeThing.__init__ at 0x10e5996c0>, 'some_method': <function AwesomeThing.some_method at 0x10e7c80e0>, '__dict__': <attribute '__dict__' of 'AwesomeThing' objects>, '__weakref__': <attribute '__weakref__' of 'AwesomeThing' objects>, '__doc__': None})

And so do modules:

>>> import math
>>> math.__dict__.keys()  
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log1p', 'log10', 'log2', 'modf', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'sumprod', 'trunc', 'prod', 'perm', 'comb', 'nextafter', 'ulp', '__file__', 'pi', 'e', 'tau', 'inf', 'nan'])

The __dict__ attribute on a module is the dictionary that stores the global namespace for that module.

Properties

Attribute lookups on an object don’t just check __dict__ on an instance or a class.

Python also has properties, which are kind of like a virtual attribute:

>>> import math
>>>
>>> class Circle:
...     """Class to create Circle objects"""
...     def __init__(self, radius=1):
...         """Circle initializer"""
...         self.radius = radius
...     @property
...     def area(self):
...         """Calculate and return the area of the Circle"""
...         return math.pi * self.radius**2
...
>>> circle = Circle(radius=2.5)
>>> circle.area
19.634954084936208

A property is essentially an attribute that runs a function each time it’s accessed. You can even use properties to control attribute assignment:

>>> class Circle:
...     """Class to create Circle objects"""
...     def __init__(self, radius=1):
...         """Circle initializer"""
...         self.radius = radius
...     @property
...     def area(self):
...         """Calculate and return the area of the Circle"""
...         return math.pi * self.radius ** 2
...     @property
...     def diameter(self):
...         """Calculate and return the diameter of the Circle"""
...         return self.radius * 2
...     @diameter.setter
...     def diameter(self, diameter):
...         """Set the diameter"""
...         self.radius = diameter / 2
...
>>>
>>> circle = Circle()
>>> circle.diameter
2
>>> circle.diameter = 3
>>> circle.radius
1.5
>>> circle.__dict__
{'radius': 1.5}

Properties are powered by Python’s descriptor protocol, which also powers the automatic binding of self to a method (a function that’s defined in a class). Descriptors are a whole advanced topic on their own.

Even if you never define a property yourself, note that attribute lookups and assignments in Python don’t necessarily rely on a simple lookup of a key in a __dict__ dictionary. Sometimes advanced dynamic behavior can be triggered by a simple attribute lookup or assignment.

Metaclasses

What’s the class of a class?

>>> type(Circle)
<class 'type'>
>>> type(list)
<class 'type'>

A class’s class is its metaclass.

Some classes have a custom metaclass.

>>> import collections
>>> type(collections.abc.Sequence)
<class 'abc.ABCMeta'>

Just as an object’s class can customize how an object behaves, a metaclass can customize how a class behaves.

Metaclasses are called whenever a new class is created.

You can actually call a metaclass yourself to dynamically construct a new class:

>>> SillyDictionary = type('SillyDictionary', (dict,), {'name': "Trey"})
>>> colors = SillyDictionary({"purple": 2})
>>> colors.name
'Trey'
>>> colors["purple"]
2

When calling a metaclass, you need to specify the class name to create, the base classes of the new class, and a dictionary of that class’s attributes (remember that methods are just functions that live as an attribute on a class).

You probably won’t ever want to dynamically create a class, but in the rare case that you do, you may want to use the dataclasses.make_dataclass function instead of manually calling a metaclass:

>>> import dataclasses
>>>
>>> Thing = dataclasses.make_dataclass(
...     "Thing",
...     [('start', str),
...     'another',
...     ('last', int, dataclasses.field(default=1))],
... )
>>>
>>> thing = Thing(start='first', another=3.5)
>>> thing
Thing(start='first', another=3.5, last=1)

Also note that class decorators are often more preferable for customizing a class than creating a metaclass. For example the dataclasses.dataclass decorator can create a very user-friendly class from just some type annotations:

>>> import dataclasses
>>> import typing
>>>
>>> @dataclasses.dataclass
... class Thing:
...     start: str
...     another: 'typing.Any'
...     last: int = 1
...
>>> thing = Thing(start='first', another=3.5)
>>> thing
Thing(start='first', another=3.5, last=1)

A function decorator is a function that accepts a function and returns a new function. A class decorator is a function that accepts a class object and returns the same class object

def class_counter(cls):
    original_init = cls.__init__
    cls.instances = 0
    def new_init(self, *args, **kwargs):
        cls.instances += 1
        original_init(self, *args, **kwargs)
    cls.__init__ = new_init
    return cls
>>> @class_counter
... class Thing:
...     def __init__(self, name):
...         self.name = name
...
>>> duck = Thing("rubber duck")
>>> duck.instances
1

A class decorator could return a new class instead of modifying the existing one, but that’s usually a bad idea because it often breaks the ability to use super().

Modules

Importing a module in Python automatically creates a namespace:

>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> sqrt(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

Because modules make namespaces automatically, we prefer short variable names in Python.

We also have an additional import syntax for times when you’d prefer not to type out the module name every time you use a specific object from a different module:

>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951

Also note that modules in Python are cached after we import them. Meaning, if we import the same module twice, we’ll get the exact same module object back.

Because modules are cached, we don’t usually make things like “singleton classes”. Instead we just make a variable within a module and point an object to that variable.

For example, the sys.path list is occasionally modified within a Python program to add an additional directory to the list of directories that Python searches when importing a module:

>>> from pathlib import Path
>>> vendor_dir = Path.cwd() / "vendor"
>>> import sys
>>> sys.path  
['', '/home/trey/.pyenv/versions/3.12.0/lib/python312.zip', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12/lib-dynload', '/home/trey/.virtualenvs/programmers/lib/python3.12/site-packages']
>>> sys.path.append(str(vendor_dir))
>>> sys.path  
['', '/home/trey/.pyenv/versions/3.12.0/lib/python312.zip', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12/lib-dynload', '/home/trey/.virtualenvs/programmers/lib/python3.12/site-packages', '/home/trey/vendor']

If the sys module was imported again anywhere within the same Python process, the same sys module object will be returned and the same path list will be shown:

>>> import sys
>>> sys.path  
['', '/home/trey/.pyenv/versions/3.12.0/lib/python312.zip', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12', '/home/trey/.pyenv/versions/3.12.0/lib/python3.12/lib-dynload', '/home/trey/.virtualenvs/programmers/lib/python3.12/site-packages', '/home/trey/vendor']

So Python has just one version of every module in each Python process.

Scripts

A Python script is just a module that’s meant to be run from the command-line.

Unlike some programming languages, Python doesn’t have any notion of a main function. If we define a main function, it won’t be run automatically, when run run a Python script:

import random

salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"]


def main():
    """Print a salutation."""
    print(random.choice(salutations))

Instead of a main function, we ask the question “is our current module being run from the command-line?” We do this using a strange looking incantation involving the __name__ variable:

import random

salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"]


def main():
    """Print a salutation."""
    print(random.choice(salutations))


if __name__ == "__main__":
    main()

Each module knows its own name, except for the entry point module to a Python process. That module always gets the name __main__.

Why don’t we just put the code we’d like to run at the top level of our module?

import random

salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"]

print(random.choice(salutations))

Well, when you import a module in Python all the code in that module will be run. So if we want our script to also be used as a regular module, we’d have a problem:

>>> import greetings
Howdy

That __name__ check is for making modules that can also be used as scripts.

If you never plan to use your script as a module, you can just stick the code at the top level of your module. You don’t need any functions at all in that case!

Class Exercises

These exercises are all in the classes.py file in the exercises directory. Edit the file to refactor the class or fix the error(s) in the class. To run the test: from the exercises folder, type python test.py <class_name>, like this:

$ python test.py Row

Row

Make a Row class that accepts any keyword arguments given to it and stores these arguments as attributes.

Hint

Note that ** can be used to capture all keyword arguments given to a function or method into a dictionary.

It should work like this:

>>> from classes import Row
>>> row = Row(a=1, b=2)
>>> row.a
1
>>> row.b
2

Make Class

For this exercise, make a friendly class factory function. This make_class function should accept a class name and a list of argument names and should return a class with an initializer and a nice string representation:

>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> p = Point(1, 2)
>>> p.x
1
>>> p
Point(x=1, y=2)

The arguments can be accepted positionally (as above) or as keyword arguments:

>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> q = Point(x=3, y=4)
>>> q
Point(x=3, y=4)
>>> q.y
4

A TypeError should be raised if any arguments are missing:

>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> Point(1)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'y'

A TypeError should also be raised if any extra/unknown arguments are given:

>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> Point(1, 2, 3)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: __init__() takes 3 positional arguments but 4 were given

The argument names given to make_class must be valid Python variable names. A ValueError should be raised otherwise:

>>> from classes import make_class
>>> make_class('Person', ['name', '1st_place'])
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: Invalid arguments: 1st_place

Arguments should also be accepted if given as a single string of valid argument names:

>>> from classes import make_class
>>> Person = make_class('Person', 'name favorite_color')
>>> Person("Trey", "purple")
Person(name='Trey', favorite_color='purple')

And if this class is inherited from, the string representation of child classes should show their class name instead:

>>> class ColorfulPoint(Point):
...     def __init__(self, x, y, color):
...         self.color = color
...         super().__init__(x, y)
...
>>> p = ColorfulPoint(1, 2, 'purple')
>>> p.color
'purple'
>>> p
ColorfulPoint(x=1, y=2)

You might notice that this class creation helper is very similar to collections.namedtuple.

Easy Class

Make an easyclass decorator which makes a dataclass that is frozen and also iterable.

It should work like this:

>>> from classes import easyclass
>>> @easyclass
... class Vector:
...     x: float
...     y: float
...     z: float
...     color: str = "black"
...
>>> v = Vector(1, 2, 3, "purple")
>>> u = Vector(4, 5, 6)
>>> w = Vector(4, 5, 6)
>>> v
Vector(x=1, y=2, z=3, color='purple')
>>> w == u
True

Auto Repr

Make a class decorator auto_repr which accepts args and kwargs arguments and adds an appropriate __repr__ method to the decorated class.

>>> from classes import auto_repr
>>> @auto_repr(args=['x', 'y'], kwargs=['color'])
... class Point:
...     def __init__(self, x, y, color='purple'):
...         self.x, self.y = x, y
...         self.color = color
...
>>> Point(1, 2)
Point(1, 2, color='purple')
>>> Point(x=3, y=4, color='green')
Point(3, 4, color='green')

There is a helper function for you to use, make_repr, which accepts args and kwargs attributes and will return an appropriate __repr__ method for the class to which it is attached. The helper function format_arguments is another helper that is used by make_repr.

def format_arguments(*args, **kwargs):
    arg_strings = (
        repr(a)
        for a in args
    )
    kwarg_strings = (
        f"{name}={value!r}"
        for name, value in kwargs.items()
    )
    return ", ".join([*arg_strings, *kwarg_strings])

def make_repr(args=(), kwargs=()):
    """Make a repr method for the class."""
    def __repr__(self):
        arg_values = [self.__dict__[a] for a in args]
        kwarg_values = {a: self.__dict__[a] for a in kwargs}
        arg_string = format_arguments(*arg_values, **kwarg_values)
        return f"{type(self).__name__}({arg_string})"
    return __repr__

It works like this:

>>> from classes import make_repr
>>> class Point:
...     def __init__(self, x, y, color='purple'):
...         self.x, self.y = x, y
...         self.color = color
...     __repr__ = make_repr(args=['x', 'y'], kwargs=['color'])
...
>>> Point(1, 2)
Point(1, 2, color='purple')
>>> Point(x=3, y=4, color='green')
Point(3, 4, color='green')