0

I have a module in python, and based on the script that has called a function in it, I want to take a decision inside that module.

So if we have 2 file file1.py and file2.py, both import the module testmod and call a function in it. Inside the module testmod, I want to know which script has called it ? file1.py or file2.py.

I want to write a code like below in testmod if then do this else if then do that else do something else !

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
attaboyabhipro
  • 1,450
  • 1
  • 17
  • 33
  • 3
    What is your use case? Why can't `file1` and `file2` call your function with an extra parameter that toggles the switch? `function myfunc(arg1, arg2, dosomething=False)` or similar. – Martijn Pieters Oct 17 '12 at 09:14
  • 4
    You will be defeating the purpose of modularity if your module needs to know who called it. You should just add parameters to the function you are using to do this – Ranjith Ramachandra Oct 17 '12 at 09:16

3 Answers3

1

I published a wrapper for inspect with simple stackframe addressing covering the stack frame by a single parameter spos, these do what the name promisses:

  • PySourceInfo.getCallerModuleFilePathName
  • PySourceInfo.getCallerModuleName

See:

acue
  • 381
  • 3
  • 6
0

Traceback

See if there is anything in the docs on traceback that gives you ideas.

John Mee
  • 50,179
  • 34
  • 152
  • 186
0

As already stated in the comments you can avoid this (since it is bad design and complicates things a lot) adding a parameter to that function. Or you could write two versions of this function if the code inside is much different from time to time.

Anyway, if you want to know from where your function got called you need the inspect module. I'm not an expert at it, but I don't think it's too hard to obtain the stack frame that called the function and from there understand which script called it.

Update:

If you really want to use inspect and do the ugly thing, here's a minimal working example:

#file a.py

import inspect
def my_func():
    dad_name = inspect.stack()[1][1]
    if inspect.getmodulename(dad_name) == 'b':   #or whatever check on the filename
         print 'You are module b!'
    elif inspect.getmodulename(dad_name) == 'c':
         print 'You are module c!'
    else:
         print 'You are not b nor c!'

#file b.py
import a

a.my_func()

#file c.py

import a
a.my_func()

#file d.py
import a
a.my_func()

Output:

$ python b.py
You are module b!
$ python c.py
You are module c!
$ python d.py
You are not b nor c!

If you want to add a parameter to the function:

#file a.py
def my_func(whichmod=None):
    if whichmod == 'b':
         print 'You are module b!'
    elif whichmod == 'c':
         print 'You are module c!'
    else:
         print 'You are not B nor C!'

#files b.py/c.py
import a
a.my_func(whichmod='b')   # or 'c' in module c

#file d.py
import a
a.my_func()

The output is the same.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231