0

Here is an example of what I want to do

import mainmodule
output=dir(mainmodule)
output 
 ['module1'
 'module2'
  ...
   ]
dir(module1.module2)
['class1',
'class2',
...
]

Now assume that I want to write a recursive function that will go like this:

def printstructure(mod)
  output=dir(mod)
  for i in output:
     print (i)
     printstructure(mod+'.'+i)    #trying to concatenate here to obtain module1.module2

The above is going to fail because module is an object (type(mod) is module and i is a string

The question is how do I get the child object (reference to it) when I know its name. Sorry if the question is naive I am learning OOP

MiniMe
  • 1,057
  • 4
  • 22
  • 47
  • Where is the duplication? If you are referring to the previous question I have tried that but it does not work if you go deeper with one level, or I could not figure our how to use getattribute in this case – MiniMe Oct 20 '18 at 20:31
  • 1
    Applying `getattr` to the return value of a previous `getattr` call lets you go deeper in a nested hierarchy: `getattr(getattr(mainmodule, "module2"), "class1")`. Often you'd do this in separate steps (e.g. `mm_module2 = getattr(mainmodule, "module2"); mm_m2_class2 = getattr(mm_module2, "class2")`), perhaps with a chain of recursive function calls handling the different levels. – Blckknght Oct 20 '18 at 20:39
  • yes he is correct as you are. I did not realize that getattr returns the name of a module and you can go with that no need to build the entire path needed when you do this dir(moduleA.moduleB.moduleC) – MiniMe Oct 20 '18 at 20:53

0 Answers0