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 !
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
inspectand do the ugly thing, here’s a minimal working example:Output:
If you want to add a parameter to the function:
The output is the same.