How to forbid direct object creation in Python 3?
class A:
def create(self):
return B()
class B:
pass
b = B() # FORBIDDEN
a = A()
a.create() # ALLOWED
How to forbid direct object creation in Python 3?
class A:
def create(self):
return B()
class B:
pass
b = B() # FORBIDDEN
a = A()
a.create() # ALLOWED
I am certain that whatever issue you are facing could be solved using an alternative approach that is more straigh forward and readable. However you can achieve what your ask by using the inspect
module and force __init__
to throw an exception if it wasn't called from a specific classmethod
.
for example:
import inspect
class A:
def __init__(self):
stack = inspect.stack()
classvar, klas = list(stack[1].frame.f_locals.items())[0]
if stack[1].function != 'create' and klas != type(self):
raise Exception
def __str__(self):
return "Success"
@classmethod
def create(cls):
result = cls()
return result
a1 = A.create() # Returns instance of A
print(a1) # prints "Success"
a2 = A() # Throws Exception
I want to reiterate that this is likely not the best means of solving whatever your issue is.