0

I would like to get a class from another module by its name as string, with the following structure:

> foldera
  > folderb1
    > folderc
      - __init__.py
      - folderc.py (parent)
      - folderc_childa.py (child)
      - ....py (more child implementations)
  > folderb2
      - __init__.py
      - converter.py
      - ....py

And would like to getattr of module folderc to list all classes of its files (e.g. a list containing classes named FolderC, FolderCChildA, and so on)

Currently getattr(foldera.folderb1.folderc, 'FolderCChildA') displays that it was not found. Because in the debugger foldera.folderb1.folderc contains no more classes as attributes than folderc.py

I tried things like this How to get class object from class name string in the same module? but it still is not working. Has anyone any advice where my mistake was made?

Solved: solution import classes into init.py of the module

Taka Incur
  • 35
  • 1
  • 6
  • are you able to import these classes normally using `import`? – fshabashev Jun 12 '22 at 10:42
  • Yes, I can import and use classes FolderCChildA, FolderCChildB, ... in my converter.py – Taka Incur Jun 12 '22 at 10:48
  • 1
    use `__all__` in `__init__.py` and add all classes to it. ie `__all__ = ['class1', 'class2']` – sahasrara62 Jun 12 '22 at 11:23
  • Thank you for the advice, but is there a way without manually adding the classes to a list, to get them by name? – Taka Incur Jun 12 '22 at 11:35
  • When you manually import the classs, where do you import `FolderCChildA` from? Do you import it in `foldera.folderb1.folderc.__init__.py` so that you can import it from `foldera.folderb1.folderc` or do you import it from `foldera.folderb1.folderc.folderc_childa`? – Iain Shelvington Jun 12 '22 at 20:32

0 Answers0