Search code examples
pythonpython-importpython-class

Python import class from another class


This is an example to better understand my problem:

fileno1.py

class MyClass:
    class MySecondClass:
         value = {"some": "dictionary"}

What I tried:
fileno2.py

from fileno1.MyClass import MysecondClass
print(MySecondClass.value)

but that gave me:
ModuleNotFoundError: No module named 'fileno1.MyClass'; "fileno1" is not a package

Now my question:
Is it somehow possible to import MySecondClass to another file in the same directory so that the variable value is accessible there?


Solution

  • I believe the correct syntax is to import the top-level class, then call the nested class through the top level class.

    from fileno1 import MyClass
    
    print(MyClass.MySecondClass.value)
    

    There's a guide on nested classes here that you might find useful.