A function that knows the name of the package from which it was called

I have two packages:

  • my_tools

    . series instruments including function f()

  • my_project

    which has my_tools

    as a dependency and which uses its functionf()

My problem is that when I call f()

from my_project

the package code, I need f()

to find it called from the package my_project

(and, for example, return the package name).

For example:

# my_project/code.py
from my_tools import f
print f()  # prints 'my_project'

      

I have played with sys

and inspect

but haven't found any solution yet.

+3


source to share


1 answer


Use inspect.currentframe

to get information about a frame, then check the __package__

module attribute :



import inspect

def f():
    frame = inspect.currentframe()
    return frame.f_back.f_globals.get('__package__')

      

+2


source







All Articles