Skip to content
Advertisement

Abstract dataclass without abstract methods in Python: prohibit instantiation

Even if a class is inherited from ABC, it can still be instantiated unless it contains abstract methods.

Having the code below, what is the best way to prevent an Identifier object from being created: Identifier(['get', 'Name'])?

JavaScript

Advertisement

Answer

You can create a AbstractDataclass class which guarantees this behaviour, and you can use this every time you have a situation like the one you described.

JavaScript

So, if Identifier inherits from AbstractDataclass instead of from ABC directly, modifying the __post_init__ will not be needed.

JavaScript

Instantiating Identifier will raise TypeError but not instantiating SimpleIdentifier or CompountIdentifier. And the AbstractDataclass can be re-used in other parts of the code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement