Consider the following dataclass. I would like to prevent objects from being created using the __init__
method direclty.
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class C:
a: int
@classmethod
def create_from_f1(cls, a: int) -> C:
# do something
return cls(a)
@classmethod
def create_from_f2(cls, a: int, b: int) -> C:
# do something
return cls(a+b)
# more constructors follow
c0 = C.create_from_f1(1) # ok
c1 = C() # should raise an exception
c2 = C(1) # should raise an exception
For instance, I would like to force the usage of the the additional constructors I define and raise an exception or a warning if an object is directly created as c = C(..)
.
What I've tried so far is as follows.
@dataclass
class C:
a : int = field(init=False)
@classmethod
def create_from(cls, a: int) -> C:
# do something
c = cls()
c.a = a
return c
with init=False
in field
I prevent a
from being a parameter to the generated __init__
, so this partially solves the problem as c = C(1)
raises an exception.
Also, I don't like it as a solution.
Is there a direct way to disable the init method from being called from outside the class?