typing
frequenz.core.typing ¤
Type hints and utility functions for type checking and types.
This module provides a decorator to disable the __init__ constructor of a class, to
force the use of a factory method to create instances. See
@disable_init for more information.
It also provides a metaclass used by the decorator to disable the __init__:
NoInitConstructibleMeta. This is
useful mostly for disabling __init__ while having to use another metaclass too (like
abc.ABCMeta).
Finally, it provides FloatInt, an honest type alias
for float | int, to annotate floating point values that can also be an int at
runtime.
Attributes¤
frequenz.core.typing.FloatInt
module-attribute
¤
A floating point value that can also be an int at runtime.
PEP 484's numeric tower makes
int assignable to any float-annotated parameter, attribute or variable, so a plain
float annotation is a lie: type checkers (even mypy --strict) happily accept int
values, but isinstance(1, float) is False at runtime. This breaks match … case
float(): arms (an int value falls through to
assert_never()), calls to float-only methods like
hex(), and any other code dispatching on the concrete runtime type.
Annotating with this alias instead makes the heterogeneity explicit, so type checkers
push the code reading these values to handle both branches, typically by matching with
case float() | int():.
The full analysis, including the alternatives that were rejected, is recorded in issue #250.
Danger
bool is a subclass of int, so True and False also satisfy this alias. This
is inherent to Python's type system and is not guarded against.
Example
from typing import assert_never
from frequenz.core.typing import FloatInt
def describe(value: FloatInt | None) -> str:
match value:
case float() | int():
return f"number {value}"
case None:
return "nothing"
case unexpected:
assert_never(unexpected)
assert describe(1) == "number 1"
assert describe(1.5) == "number 1.5"
assert describe(None) == "nothing"
frequenz.core.typing.TypeT
module-attribute
¤
A type variable that is bound to a type.
Classes¤
frequenz.core.typing.NoInitConstructibleMeta ¤
Bases: type
A metaclass that disables the __init__ constructor.
This metaclass can be used to disable the __init__ constructor of a class. It is
intended to be used with classes that don't provide a default constructor and
require the use of a factory method to create instances.
When marking a class using this metaclass, the class cannot be even declared with a
__init__ method, as it will raise a TypeError when the class is created, as soon
as the class is parsed by the Python interpreter. It will also raise a TypeError
when the __init__ method is called.
To create an instance you must provide a factory method, using __new__.
Warning
It is also recommended to apply this metaclass only to classes inheriting from
object directly (i.e. not explicitly inheriting from any other classes), as
things can also get tricky when applying the constructor to a sub-class for the
first time.
Basic example defining a class with a factory method
To be able to type hint the class correctly, you can declare the instance attributes in the class body, and then use a factory method to create instances.
from typing import Self
class MyClass(metaclass=NoInitConstructibleMeta):
value: int
@classmethod
def new(cls, value: int = 1) -> Self:
self = cls.__new__(cls)
self.value = value
return self
instance = MyClass.new()
# Calling the default constructor (__init__) will raise a TypeError
try:
instance = MyClass()
except TypeError as e:
print(e)
Hint:
The @disable_init decorator is a more
convenient way to use this metaclass.
Example combining with other metaclass
A typical case where you might want this is to combine with
abc.ABCMeta to create an abstract class that doesn't provide a
default constructor.
from abc import ABCMeta, abstractmethod
from typing import Self
class NoInitConstructibleABCMeta(ABCMeta, NoInitConstructibleMeta):
pass
class MyAbstractClass(metaclass=NoInitConstructibleABCMeta):
@abstractmethod
def do_something(self) -> None:
...
class MyClass(MyAbstractClass):
value: int
@classmethod
def new(cls, value: int = 1) -> Self:
self = cls.__new__(cls)
self.value = value
return self
def do_something(self) -> None:
print("Doing something")
instance = MyClass.new()
instance.do_something()
# Calling the default constructor (__init__) will raise a TypeError
try:
instance = MyClass()
except TypeError as e:
print(e)
Source code in src/frequenz/core/typing.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
Methods:¤
__call__ ¤
Raise an error when the init constructor is called.
| PARAMETER | DESCRIPTION |
|---|---|
*args
|
ignored positional arguments.
TYPE:
|
**kwargs
|
ignored keyword arguments.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
Always. |
Source code in src/frequenz/core/typing.py
__init__ ¤
Initialize the new class.
Source code in src/frequenz/core/typing.py
__new__ ¤
__new__(
mcs,
name: str,
bases: tuple[type, ...],
namespace: dict[str, Any],
**kwargs: Any
) -> type
Create a new class with a disabled init constructor.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The name of the new class.
TYPE:
|
bases
|
The base classes of the new class. |
namespace
|
The namespace of the new class. |
**kwargs
|
Additional keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
type
|
The new class with a disabled init constructor. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the class provides a default constructor. |
Source code in src/frequenz/core/typing.py
Functions:¤
frequenz.core.typing.disable_init ¤
disable_init(
cls: TypeT | None = None,
*,
error: Exception | None = None
) -> TypeT | Callable[[TypeT], TypeT]
Disable the __init__ constructor of a class.
This decorator can be used to disable the __init__ constructor of a class. It is
intended to be used with classes that don't provide a default constructor and
require the use of a factory method to create instances.
When marking a class with this decorator, the class cannot be even declared with a
__init__ method, as it will raise a TypeError when the class is created, as soon
as the class is parsed by the Python interpreter. It will also raise a TypeError
when the __init__ method is called.
To create an instance you must provide a factory method, using __new__.
Warning
This decorator will use a custom metaclass to disable the __init__ constructor
of the class, so if your class already uses a custom metaclass, you should be
aware of potential conflicts. See
NoInitConstructibleMeta for an
example on how to use more than one metaclass.
It is also recommended to apply this decorator only to classes inheriting from
object directly (i.e. not explicitly inheriting from any other classes), as
things can also get tricky when applying the constructor to a sub-class for the
first time.
Basic example defining a class with a factory method
To be able to type hint the class correctly, you can declare the instance attributes in the class body, and then use a factory method to create instances.
from typing import Self
@disable_init
class MyClass:
value: int
@classmethod
def new(cls, value: int = 1) -> Self:
self = cls.__new__(cls)
self.value = value
return self
instance = MyClass.new()
# Calling the default constructor (__init__) will raise a TypeError
try:
instance = MyClass()
except TypeError as e:
print(e)
Class wrongly providing an __init__ constructor
Using a custom error message when the default constructor is called
from typing import Self
class NoInitError(TypeError):
def __init__(self) -> None:
super().__init__("Please create instances of MyClass using MyClass.new()")
@disable_init(error=NoInitError())
class MyClass:
@classmethod
def new(cls) -> Self:
return cls.__new__(cls)
try:
instance = MyClass()
except NoInitError as e:
assert str(e) == "Please create instances of MyClass using MyClass.new()"
print(e)
| PARAMETER | DESCRIPTION |
|---|---|
cls
|
The class to be decorated.
TYPE:
|
error
|
The error to raise if init is called, if
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TypeT | Callable[[TypeT], TypeT]
|
A decorator that disables the |
Source code in src/frequenz/core/typing.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |