3

I have two packages:

  • my_tools, a series tools including function f()
  • my_project which has my_tools as a dependency and which is using its f() function

My problem is that when I call f() from my_project package's code, I need f() to be able to find it's been called from the my_project package (and for instance return the package's name).

For example:

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

I've been playing around with sys and inspect but couldn't find any solution so far.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Anto
  • 6,806
  • 8
  • 43
  • 65
  • 1
    `def f(): return inspect.currentframe().f_back.f_globals.get('__package__', '?')` – falsetru Apr 06 '17 at 23:35
  • Returns `my_tools`, not `my_project` ;) – Anto Apr 06 '17 at 23:40
  • I've got `my_project`. Check [`__package__` documentation](https://docs.python.org/3/reference/import.html#__package__) – falsetru Apr 06 '17 at 23:59
  • Or see https://asciinema.org/a/atjvs4v32spu8tzt9i48piagm – falsetru Apr 07 '17 at 00:05
  • I think there's a difference in this asciinema snippet: `my_tools.py` isn't part of a `my_tools` python package installed as a dependency of `my_project`. I guess this is (part of) the reason why I don't get the same result... – Anto Apr 07 '17 at 02:19
  • I also tried that case, got `my_project`. (BTW, I used `from my_project.my_tools import f` to make it work both in Python 2/3) – falsetru Apr 07 '17 at 02:29
  • I suspect you import the `code` directly, not as submodule of `my_project`. Could you check that? – falsetru Apr 07 '17 at 05:47
  • I tried to properly explain what I'm doing here (great tool btw, thanks): https://asciinema.org/a/e8gfeu34h0n4loz3n5ut2o4q6 – Anto Apr 07 '17 at 12:53

1 Answers1

2

Use inspect.currentframe to get frame information, then check __package__ attribute of the module:

import inspect

def f():
    frame = inspect.currentframe()
    return frame.f_back.f_globals.get('__package__')
falsetru
  • 357,413
  • 63
  • 732
  • 636