Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent instantiation of abstract base classes #82

Open
goerz opened this issue Aug 16, 2018 · 1 comment
Open

Prevent instantiation of abstract base classes #82

goerz opened this issue Aug 16, 2018 · 1 comment

Comments

@goerz
Copy link
Member

goerz commented Aug 16, 2018

Python prevents instantiation of abstract base classes, but only if they have abstract methods. Thus, for example, the following works:

>>> QuantumSymbol('a', hs=1)

despite QuantumSymbol being an abstract class:

class QuantumSymbol(QuantumExpression, metaclass=ABCMeta)

This can cause problems, as abstract classes may not define all the necessary class attributes for algebraic operations to work (and there's no way in Python to declare abstract class attributes, which Python could catch similar to abstract methods)

We should figure out some general way in Expression.__init__ to raise an exception if any class whose type is a direct subclass of ABCMeta is being instantiated. So far, I haven't found a way to perform this check.

@goerz
Copy link
Member Author

goerz commented Aug 18, 2018

An alternative is to implement "abstract class attributes", using a custom meta-class, as described in

https://stackoverflow.com/questions/23831510/abstract-attribute-not-property/23833055

Specifically:

  • define a singleton AbstractClassAttributes
  • subclass ABCMeta into QnetABCMeta
  • In the abstract class, set class attributes that subclasses must overwrites to AbstractClassAttributes
  • In QnetABCMeta, check that no class attributes are AbstractClassAttributes, otherwise raise a TypeError: Can't instantiate abstract class with abstract class attribute

QnetABCMeta might also implement some mechanism to categorically forbid instantiating classes that directly have the QnetABCMeta class, but this would be in addition to providing abstract class attributes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant