2

Question: Is there a way to use globals() or locals() but from a different (imported) module rather than "__main__", without having to then grind through the results to find, for example, just the function objects?

What I've tried so far: (showing different shades of ignorance and confusion!)

module2.globals module2.globals() "module2".globals "module2".globals() globals(module2) globals().module2 globals().module2() __name__.globals __name__.globals() "__main__".globals() "__main__".globals

My best prospects were module2.__dict__ and module2.__dict__.keys() - but I couldn't see how I'd filter the results without great deviousness...

Background: (and why I'm not looking for a sys.modules() answer, thanks)

My original goal was to "farm" a list of function objects from any new module I created and after some filtering, use that list to procedurally generate a menu or GUI. I came up with the following approach using sys.modules as a first step in "function farming" so I have a solution, just not a full understanding - hence my long-winded question.

# module1

import sys

def get_functions_A(module = "__main__"):
    values1 = sys.modules[module].__dict__.values()
    print([x for x in values1 if str(type(x))=="<class 'function'>"])

I got identical results using globals() and values() below, which looked promising at first:

# module1    
...
def get_functions_B(module = "__main__"):
    values2 = list(globals().values())   
    print([x for x in values2 if str(type(x))=="<class 'function'>"])

I prefer this 2nd approach because it reads much less like an arcane incantation to me as a newcomer to Python.

However, when I tried putting this globals()-based function into a different module (my personal "go-to" library of tools and tricks) and importing it from there, I noticed it was only farming functions from its own module, module2:

# module2

def get_functions_B2(module="__main__"):
    values2=list(globals().values())   
    print([x for x in values2 if str(type(x))=="<class 'function'>"])

and then:

# module1

from module2 import get_functions_B2

def get_functions_B1(module = "__main__"):
    values1 = list(globals().values())   
    print([x for x in values1 if str(type(x))=="<class 'function'>"])

Correct output as desired from module1 and get_functions_B1:

[<function get_functions_B2 at 0x000002059594DBF8>, <function get_functions_B1 at 0x0000020593593E18>]

Incorrect (partial) output from module1 and import of get_functions_B2:

[<function get_functions_B2 at 0x000002494CC7DBF8>]

I now understand why this is happening ("global" actually means "module-wide"), and replied to a related Question here but would still like to know if I'm missing an elegant or obvious way of using globals() instead of sys.modules() please.

This is my first question on StackOverflow so thanks for your patience & help...

Peter F
  • 793
  • 8
  • 10

0 Answers0