Sub topic 5
Alternative constructors with @classmethod
This chapter assumes you can write a class with __init__ and instance methods, that you know @name decorator syntax, and that you have read the earlier chapter on what @classmethod is and how cls works. Here the focus is one use of class methods: building instances from inputs that __init__ does not accept directly.
The problem: one `__init__`, many input shapes
A class has exactly one __init__. Python has no constructor overloading, so you cannot define two __init__ methods with different parameter lists. The second definition replaces the first.
Data rarely arrives in the one shape your __init__ expects. A date might come as a string, a tuple, a timestamp, or a dictionary parsed from JSON. There are three common ways to handle this:
- Make
__init__accept every shape and branch on the argument types. - Make the caller convert the data before calling the class.
- Add named class methods that each accept one shape, convert it, and call the normal constructor.
The third option is the alternative constructor pattern. It keeps __init__ simple, gives each input shape a descriptive name, and keeps the conversion logic next to the class it belongs to.
The basic pattern
An alternative constructor is a class method that does some preparation and then returns cls(...).
class Date:
def __init__(self, year, month, day):
if not 1 <= month <= 12:
raise ValueError(f"month must be 1-12, got {month}")
if not 1 <= day <= 31:
raise ValueError(f"day must be 1-31, got {day}")
self.year = year
self.month = month
self.day = day
def __repr__(self):
return f"Date({self.year}, {self.month}, {self.day})"
@classmethod
def from_string(cls, text):
try:
year, month, day = map(int, text.split("-"))
except ValueError:
raise ValueError(f"expected YYYY-MM-DD, got {text!r}") from None
return cls(year, month, day)
d = Date.from_string("2026-11-26")
print(d) # Date(2026, 11, 26)
try:
Date.from_string("2026/11/26")
except ValueError as error:
print(error) # expected YYYY-MM-DD, got '2026/11/26'Three things happen in from_string:
- It parses the input.
text.split("-")produces a list of strings, andmap(int, ...)converts each one. - It translates parsing failures into one clear error message. Both a failed
int()conversion and a wrong number of parts raiseValueError, so a singleexceptclause covers them. - It hands the clean values to
cls(...), so__init__still performs its range checks. The alternative constructor never duplicates validation that__init__already does.
The last point is the main design rule. An alternative constructor should reduce its input to the arguments __init__ expects and then call cls. Validation then lives in one place.
Several constructors on one class
A class can have as many alternative constructors as it has meaningful input shapes. Each one has its own name, which documents what it accepts.
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
@classmethod
def from_polar(cls, radius, angle):
return cls(radius * math.cos(angle), radius * math.sin(angle))
@classmethod
def from_tuple(cls, pair):
x, y = pair
return cls(x, y)
@classmethod
def origin(cls):
return cls(0, 0)
print(Point(3, 4)) # Point(3, 4)
print(Point.from_polar(2, 0)) # Point(2.0, 0.0)
print(Point.from_tuple((5, 6))) # Point(5, 6)
print(Point.origin()) # Point(0, 0)from_polar takes different parameters from __init__: a radius and an angle instead of x and y. from_tuple takes a single argument. origin takes no arguments at all. It is a named shortcut for a commonly needed instance. Because the call site reads Point.origin(), no reader has to wonder what Point(0, 0) was meant to represent.
Naming conventions
Python's standard library and most third-party code follow a few naming habits. Following them makes your constructors predictable.
| Name pattern | Meaning | Example |
|---|---|---|
| `from_<source>` | Build from data in a given format or type | `int.from_bytes`, `Date.from_string` |
| `<source>`-style without `from` | Common in the standard library for short names | `dict.fromkeys`, `date.fromisoformat` |
| `of`, `create`, `new` | Generic factory when the input is the ordinary one | `Shape.create()` |
| A noun naming the value | A well-known preset instance | `Point.origin()`, `Money.zero()` |
Choose the name that tells the reader what the input is. Date.from_string is better than Date.parse2, and much better than a boolean flag on __init__.
Alternative constructors you already use
The standard library uses this pattern widely. You have probably called some of these without noticing that they are class methods.
import datetime
print(dict.fromkeys(["a", "b"], 0)) # {'a': 0, 'b': 0}
print(int.from_bytes(b"\x01\x00", "big")) # 256
print(datetime.date.fromisoformat("2026-11-26")) # 2026-11-26
print(type(datetime.date.today()).__name__) # dateEach of these is called on the class, not on an instance, and each returns a new instance of that class. That is the whole contract of the pattern.
Layering constructors
Alternative constructors can call each other. When one input shape is a simple transformation of another, build the outer constructor on top of the inner one.
import json
class Config:
def __init__(self, host, port=8080):
self.host = host
self.port = port
def __repr__(self):
return f"Config(host={self.host!r}, port={self.port!r})"
@classmethod
def from_dict(cls, data):
return cls(data["host"], data.get("port", 8080))
@classmethod
def from_json(cls, text):
return cls.from_dict(json.loads(text))
@classmethod
def from_file(cls, path):
with open(path, encoding="utf-8") as handle:
return cls.from_json(handle.read())
print(Config.from_json('{"host": "example.org"}'))
# Config(host='example.org', port=8080)
print(Config.from_json('{"host": "example.org", "port": 9000}'))
# Config(host='example.org', port=9000)from_file reads text and passes it to from_json. from_json decodes text and passes a dictionary to from_dict. from_dict is the only one that touches __init__, so any change to how dictionary keys map to parameters happens in one method.
Notice that each inner call uses cls.from_dict(...) and cls.from_json(...), not Config.from_dict(...). Inside a class method, cls is the class the method was called on. Calling through cls keeps the whole chain tied to that class, which matters as soon as a subclass is involved.
Why `cls(...)` and not the class name
You could write return Date(year, month, day) inside from_string. It works for Date itself, but it ignores subclasses. This is the main reason alternative constructors are class methods and not static methods.
class Date:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
@staticmethod
def hardcoded_from_string(text):
year, month, day = map(int, text.split("-"))
return Date(year, month, day)
class LoggedDate(Date):
pass
print(type(LoggedDate.from_string("2026-11-26")).__name__) # LoggedDate
print(type(LoggedDate.hardcoded_from_string("2026-11-26")).__name__) # DateCalling LoggedDate.from_string(...) passes LoggedDate as cls, so the result is a LoggedDate. The static version has the name Date written into its body, so a subclass can never change what it builds. The next chapter covers inheritance in more detail. For now, the rule is: inside an alternative constructor, build the result with cls(...).
When a subclass changes `__init__`
Using cls(...) has a cost. An alternative constructor assumes that cls.__init__ accepts the arguments it passes. If a subclass changes the __init__ signature, inherited constructors can break.
class Pair:
def __init__(self, first, second):
self.first = first
self.second = second
@classmethod
def from_string(cls, text):
first, second = text.split(",")
return cls(first, second)
class Triple(Pair):
def __init__(self, first, second, third):
super().__init__(first, second)
self.third = third
try:
Triple.from_string("a,b")
except TypeError as error:
print(type(error).__name__) # TypeErrorTriple.from_string calls Triple("a", "b"), but Triple.__init__ requires three arguments, so Python raises TypeError. You have two reasonable fixes:
- Override
from_stringin the subclass so it supplies the extra argument. - Keep subclass
__init__signatures compatible with the parent, for example by giving new parameters default values.
Neither fix is always right. If subclasses are meant to change the constructor signature, document that they must also override the alternative constructors.
Constructors that skip `__init__`
Sometimes an alternative constructor must create an instance without running __init__. Typical reasons are that the data is already validated, or that running __init__ would repeat expensive work. You can allocate the object with cls.__new__(cls) and set the attributes yourself.
class Account:
def __init__(self, owner, balance=0):
if balance < 0:
raise ValueError("balance cannot be negative")
self.owner = owner
self.balance = balance
@classmethod
def _from_trusted(cls, owner, balance):
instance = cls.__new__(cls)
instance.owner = owner
instance.balance = balance
return instance
account = Account._from_trusted("Ada", -5)
print(account.balance) # -5The output shows the cost. The instance has a negative balance because __init__ never checked it. A subclass that adds setup work to __init__ also loses that work. Use this technique only when you control all the callers, and mark the method private with a leading underscore as above.
Constructors that return existing instances
__init__ always initializes a new object. A class method has no such restriction, so an alternative constructor can return a cached or shared instance.
class Color:
_cache = {}
def __init__(self, name):
self.name = name
@classmethod
def named(cls, name):
if name not in cls._cache:
cls._cache[name] = cls(name)
return cls._cache[name]
print(Color.named("red") is Color.named("red")) # True
print(Color("red") is Color("red")) # FalseHere _cache is a class attribute, which a class method can read and update through cls. One caveat: because _cache is defined on Color, a subclass shares the same dictionary unless it defines its own. A Color.named("red") call and a Shade.named("red") call would then return the same cached object, even though the second one should be a Shade. If you cache per class, key the cache on (cls, name).
Comparing the three approaches
| Approach | Strength | Weakness |
|---|---|---|
| One `__init__` that branches on argument types | One entry point | Grows into a long chain of `isinstance` checks. Call sites do not say what they pass. |
| Conversion code in the caller | No change to the class | Every caller repeats the conversion. Parsing rules drift apart. |
| Alternative constructors with `@classmethod` | Named, discoverable, one `__init__` | Subclasses with a different `__init__` signature must override them. |
For most classes with two or more input shapes, the third approach is the best default.
A design checklist
When you add an alternative constructor, check these points:
- The method is decorated with
@classmethodand its first parameter iscls. - It ends by building the instance with
cls(...), not with a hard-coded class name. - It raises a clear error for bad input, and it lets
__init__perform validation of the converted values. - Its name says what the input is, such as
from_stringorfrom_dict. - Its docstring states the expected format, because the signature alone does not.
- It works if called on a subclass, or the subclass is documented to override it.
Exercises
Exercise
Write a class Duration whose _init takes a number of seconds. Add a class method fromhms that takes a string such as "1:30:15" (hours, minutes, seconds) and returns a Duration. What value of seconds does Duration.from_hms("1:30:15") produce, and which expression should the method end with?
Show answer
It produces 5415 seconds, because 1 3600 + 30 60 + 15 = 5415. Split the text on ":" and convert each part with int, so hours, minutes, seconds = map(int, text.split(":")). The method should end with return cls(hours 3600 + minutes 60 + seconds). It must use cls and not Duration so that subclasses of Duration get instances of their own type.
Exercise
A class Base has _init(self, a) and a class method fromtext(cls, text) that returns cls(text.strip()). A subclass Child defines _init(self, a, b) and sets self.b = b. What happens when you call Child.fromtext(" x ")? Give two ways to fix it.
Show answer
fromtext calls cls(...) with cls set to Child, so Python calls Child("x") with one argument, and the missing b raises a TypeError. One fix is to give b a default value in Child.init, for example b=None. The other is to override fromtext in Child so that it passes both arguments, for example by returning cls(text.strip(), some_value).