-1

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?

Enoch
  • 344
  • 2
  • 6
  • Where are the files located? – 12944qwerty May 13 '21 at 14:08
  • 2
    that's now how imports work, you can only import top level defined objects, not nested ones – gold_cy May 13 '21 at 14:11
  • Does this answer your question? [python import nested class](https://stackoverflow.com/questions/36514851/python-import-nested-class) – gold_cy May 13 '21 at 14:14
  • @12944qwerty they are located in the same directory – Enoch May 13 '21 at 14:20
  • @gold_cy Yes, but is that the only way how you can do it? Because in my original Project, I have more and deeper nested classes that need to be accessed. – Enoch May 13 '21 at 14:27
  • Why do you even have the need to nest class definitions? – Matthias May 13 '21 at 15:10
  • @Matthias I am building an app automation framework with uiautomator2 and with nested classes it is easier to keep track of where the elements are located in the app – Enoch May 13 '21 at 17:17

1 Answers1

3

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.

alumarcu
  • 133
  • 6