0

This questions is related global-scope of python.

There are have two files below.

fileA.py

import pprint
pprint.pprint(globals())

fileB.py

import fileA

def global_funcB():
    return "global_funcB"

When I run python fileB.py. The globals() of fileA.py only contains fileA's content.

Is that possible to get address of global_funcB in fileB.py from fileA.py? So far, I only can do this from fileB.py.

Note: for my purpose, there is no way to import fileB from fileA.py


[Edit]

Let me describe my purpose clearly.

loader.py

class loader(object):
    def __init__(self, module):
        print(dir(module))

builder.py + class function

import loader

class someobj(object):
   def somefunc(self):
       pass

loader.loader(someobj)

If I passing some module/class from fileB to build fileA, then it's possible to fetch function of fileB.

However, if the function in builder.py is globally.

builder.py + global function

import loader

def someglobalfunc(self):
   pass

loader.loader(???)

I have no idea how to pass globals() as a module/class to another file.

Kir Chou
  • 2,980
  • 1
  • 36
  • 48

1 Answers1

0

If you want to get the globals of file B inside file A after importing it in B and use the globals in B it's completely redundant, as you can simple get the globals within B and use them.

If you want to get those globals and use them with A it's not possible because at the time you are running the file A there is not B in it's name space which is completely obvious.

Based on your edit:

If you are going to pass multiple global function to loader you can find all functions within your global namespace and pass them to loader. For example you can look for objects that have a __call__ attribute (if your classes and other objects are not callable). Or as a more general way use types.FunctionType.

from typing import FunctionType
functions = [obj for obj in globals().values() if isinstance(obj, FunctionType)]

The loader class:

class loader:
    def __init__(self, *modules):
        for module in modules:
            print(dir(module))

Your executable file:

import loader
from typing import FunctionType

def someglobalfunc1(self):
   pass
def someglobalfunc2(self):
   pass

functions = [obj for obj in globals().values() if isinstance(obj, FunctionType)]
loader.loader(*functions)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • @KirChou I don't see any differences between two cases, you can still pass your function object to `loader`. Note that almost every thing in python is an object. – Mazdak Nov 06 '16 at 10:18
  • Yep, I know I can pass function to loader.py, but consider there are multiple global functions. How to pass them **in one object**? What I knew is globals(), but I found that I can not share globals as a module. – Kir Chou Nov 06 '16 at 10:25
  • Thanks. tbh, the solution is not over my expectation, but it seems like no other way to achieve this. – Kir Chou Nov 07 '16 at 04:16