0

I need to declare an abstract instance variable in an abstract base class. After looking at Python: abstract instance variable?, it seems the one way to do that is with type annotations, e.g.,,

class base(ABC):
  var : str

If var here can take on multiple types, e.g., str or int, how would that work?

I tried

class base(ABC):
  var : str | int

but that gives the error

    val : int | str
TypeError: unsupported operand type(s) for |: 'type' and 'type'

Also, I'm not tied to annotations, so if there's a better way to accomplish what I need, I'm definitely open to switching.

24n8
  • 1,898
  • 1
  • 12
  • 25
  • what is your python version? – cards Feb 09 '23 at 17:06
  • @cards I was using `Python 3.7.4` when I generated the above error – 24n8 Feb 09 '23 at 17:07
  • not sure but it could require >= 10, [see](https://docs.python.org/3/library/typing.html#typing.Union): _Changed in version 3.10: Unions can now be written as X | Y_ – cards Feb 09 '23 at 17:09
  • "it seems the one way to do that is with type annotations" not really. what do you think this abstract base class does? It doesn't enforce the creation of `var` at runtime. What is your goal here? – juanpa.arrivillaga Feb 09 '23 at 17:16
  • @juanpa.arrivillaga I come from a C++ background, and usually for base classes, I can declare attributes that will be inherited by subclasses, so that's what I'm trying to achieve, basically declaring the variable without initializing it. Is there a better way to do this in Python? – 24n8 Feb 09 '23 at 17:33
  • Python doesn't really have variable declarations. But you really haven't answered my question. You are inheriting from `ABC`, so it seems like you want to use the facilities of the `abc` module. This will prevent you from instantiating classes without the abstract methods implemented in a base class. But you cannot really do that with attributes, only with methods. That is actually what the answer you linked to explains. – juanpa.arrivillaga Feb 09 '23 at 17:37
  • @juanpa.arrivillaga Yes, I would like to use the facilities in `abc`. I think one thing I would like to accomplish here is to make sure `var` is set in the inherited class or an error is thrown, like there would be if an abstract method isn't defined in the base class – 24n8 Feb 09 '23 at 17:45
  • Anyway, the proximal cause of your error is that you are using a python version that doesn't support that syntax – juanpa.arrivillaga Feb 09 '23 at 17:45
  • Well, in that case, you are out of luck, because you cannot do that with the`abc` module. – juanpa.arrivillaga Feb 09 '23 at 17:45
  • @juanpa.arrivillaga oh let me clarify. I need to inherit from `ABC` (it's in an existing codebase and I don't think I can change that part of the design). I don't need to use `abc` facilities to accomplish what I want to do, so I can use other approaches – 24n8 Feb 09 '23 at 18:10

0 Answers0