1

What is the python way of defining abstract class constants?

For example, if I have this abstract class:

class MyBaseClass(SomeOtherClass, metaclass=ABCMeta):
    CONS_A: str
    CONS_B: str

So, the type checker/"compiler" (at least Pycharm's one) doesn't complain about the above. But if I inherit it to another class and don't implement CONS_A and CONS_B, it doesn't complain either:

class MyChildClass(MyBaseClass):
    pass

What is the python way of enforcing (the much we can with a duck-type language) implementation of MyBaseClass to actually implement CONS_A and CONS_B?

Bonus question: once I can enforce, how can I only enforce for non-abstract classes? I suppose it should be the same answer as the main question. But, I might be wrong. So, for example:

# "compiler" should not complain
class MyChildAbstractClass(MyBaseClass):
    pass

# here it must complain if I don't implement `CONS_A` and `CONS_B`
class MyChildImplementationClass(MyChildAbstractClass):
    pass

Obs: I am aware of @abstractmethod, but I didn't find a solution for abstract class constants.

Thank you.

YFl
  • 845
  • 7
  • 22
  • Does this answer your question? [Abstract attributes in Python](https://stackoverflow.com/questions/2736255/abstract-attributes-in-python) Specifically [this](https://stackoverflow.com/a/53417582/12479639) answer. – Axe319 Dec 08 '22 at 17:25
  • Python doesn't really have a concept of constants other than a naming convention. – Axe319 Dec 08 '22 at 17:26
  • Thanks, @Axe319. I'll check the answers. What do you mean by "Python doesn't really have a concept of constants other than a naming convention"? Can you elaborate a bit? – YFl Dec 08 '22 at 17:38
  • Sure. The naming convention for constants is all capital letters, such as you have with `CONS_A`. However, Python doesn't enforce this in any way or treat it differently than any other class variables. I only mention this because if you come across a solution for abstract class attributes, they would be functionally identical. – Axe319 Dec 08 '22 at 17:45

0 Answers0