Skip to content

Python Custom Classes

Decorators

@classmethod

  • the first param is the class
  • instead of self (which is the instance)
    • which accesses the instance values
    • or class values if it hasn't been overridden
class Test(TestCase):
    @classmethod
    def setUpTestData(cls):
        pass

Creating unique values

Unique sentinel values, identity checks, and when to use object() instead of None

[[spot-the-bug#The problem with None in Python]]

object()

kinda Like JS Symbol

No two symbols are the same

Useful for creating unique values

>>> x = object()
>>> y = object()
>>> x == y
False

Every class in Python has a base class of object

When to use object?

  1. Unique initial values: a starting value that should be distinguished from values seen later (default and initial in our min function)
  2. Unique stop values: a value whose presence tells us to stop looping/processing (a true sentinel value, as in strict_zip)
  3. Unique skip values: a value whose presence should be treated as an empty value to be skipped over (we didn’t see this, but it comes up with utilities like itertools.zip_longest sometimes)

Enum

Python Enum Docs

Enums are unique values

Regular enum

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

>>> Color.RED
<Color.RED: 1>

>>> Color.RED.name
'RED'

>>> Color.RED.value
1

string enum

from enum import Enum

class Color(str, Enum):
    GREEN: '#00ff00'

Color.GREEN == '#00ff00'

Last update: 2022-11-04