Search code examples
pythonimportpython-importsubclass

How can you a access a superclass from inside a subclass in different a file?


I'm trying to create an instance of a subclass in a script called main.py. The subclass and its associated superclass each live in separate files in a subdirectory. The file structure is as follows:

  • main.py
  • protocols
    • protocol.py (inside is a superclass named protocol)
    • MovingBar.py (inside is a subclass named MovingBar)

In main.py I can load the protocol superclass using from protocols.protocol import protocol Using this approach I can generate an instance of the superclass without issue.

However, when I next try to load the MovingBar subclass using from protocols.MovingBar import MovingBar I get the following error

NameError: name 'protocol' is not defined

Presumably, this is because I have a reference to protocol in the class def of MovingBar as follows:

class MovingBar(protocol):
    def __init__(self):
        super().__init__()

I'm not sure why python recognizes a reference to protocol in the main.py file, but not when it's in the MovingBar file. Is there a way to import protocol such that it can be seen when I'm subsequently importing MovingBar?


Solution

  • You need from protocol import protocol in your MovingBar.py. Modules do not inherit the global environment of their callers.