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
).
Attributes¤
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(metaclas=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 frequenz/core/typing.py
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 197 198 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 |
|
Functions¤
__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 frequenz/core/typing.py
__init__ ¤
Initialize the new class.
Source code in 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 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 frequenz/core/typing.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 |
|