Get _Name_ of Calling Function's Module in Python

Get __name__ of calling function's module in Python

Check out the inspect module:

inspect.stack() will return the stack information.

Inside a function, inspect.stack()[1] will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.

See the docs for details:

http://docs.python.org/library/inspect.html

Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:

http://pymotw.com/2/inspect/index.html#module-inspect

EDIT: Here's some code which does what you want, I think:

import inspect 

def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)

What does if __name__ == __main__: do?

Short Answer

It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:

  • If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and using the second script's command line arguments. This is almost always a mistake.

  • If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.

Long Answer

To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then

  • it executes all of the code found in the file.

Let's see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
print("Function A")

print("before function_b")
def function_b():
print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
function_a()
function_b()
print("after __name__ guard")

Special Variables

When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:

# Suppose this is in some other main program.
import foo

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Executing the Module's Code

After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.

Always

  1. It prints the string "before import" (without quotes).

  2. It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")

  1. It prints the string "before function_a".

  2. It executes the def block, creating a function object, then assigning that function object to a variable called function_a.

  3. It prints the string "before function_b".

  4. It executes the second def block, creating another function object, then assigning it to a variable called function_b.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program


  1. If your module is the main program, then it will see that __name__ was indeed set to "__main__" and it calls the two functions, printing the strings "Function A" and "Function B 10.0".

Only When Your Module Is Imported by Another


  1. (instead) If your module is not the main program but was imported by another one, then __name__ will be "foo", not "__main__", and it'll skip the body of the if statement.

Always


  1. It will print the string "after __name__ guard" in both situations.

Summary

In summary, here's what'd be printed in the two cases:

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

Why Does It Work This Way?

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.

Food for Thought

  • Question: Can I have multiple __name__ checking blocks? Answer: it's strange to do so, but the language won't stop you.

  • Suppose the following is in foo2.py. What happens if you say python foo2.py on the command-line? Why?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
print("a1")
from foo2 import function_b
print("a2")
function_b()
print("a3")

def function_b():
print("b")

print("t1")
if __name__ == "__main__":
print("m1")
function_a()
print("m2")
print("t2")

  • Now, figure out what will happen if you remove the __name__ check in foo3.py:
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
print("a1")
from foo3 import function_b
print("a2")
function_b()
print("a3")

def function_b():
print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
  • What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
print("bar")

print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard")

Python custom module attribute error _name_

You need to use double underscores:

print(tm.__name__)

What does `if name == __main__` mean in Python?

This allows you to use the same file both as a library (by importing it) or as the starting point for an application.

For example, consider the following file:

# hello.py
def hello(to=__name__):
return "hello, %s" % to

if __name__ == "__main__":
print hello("world")

You can use that code in two ways. For one, you can write a program that imports it. If you import the library, __name__ will be the name of the library and thus the check will fail, and the code will not execute (which is the desired behavior):

#program.py
from hello import hello # this won't cause anything to print
print hello("world")

If you don't want to write this second file, you can directly run your code from the command line with something like:

$ python hello.py
hello, __main__

This behavior all depends on the special variable __name__ which python will set based on whether the library is imported or run directly by the interpreter. If run directly it will be set to __main__. If imported it will be set to the library name (in this case, hello).

Often this construct is used to add unit tests to your code. This way, when you write a library you can embed the testing code right in the file without worrying that it will get executed when the library is used in the normal way. When you want to test the library, you don't need any framework because you can just run the library as if it were a program.

See also __main__ in the python documentation (though it's remarkably sparse)

How to get a function's name as string?

greeting.capitalize is a function object, and that object has a .__name__ attribute that you can access. But greeting.capitalize() calls the function object and returns the capitalized version of the greeting string, and that string object doesn't have a .__name__ attribute. (But even if it did have a .__name__, it'd be the name of the string, not the name of the function used to create the string). And you can't do str.capitalize() because when you call the "raw" str.capitalize function you need to pass it a string argument that it can capitalize.

So you need to do

print str.capitalize.__name__

or

print greeting.capitalize.__name__

Calling if __name__ == '__main__': in one module from a function in another module

The if __name__ == '__main__' is mainly used to make a single python script executable. For instance, you define a function that does something, you use it by importing it and running it, but you also want that function to be executed when you run your python script with python module1.py.

For the question you asked, the best I could come up with is that you wanted a function defined in "module1.py" to run when you invoke "module2.py". That would be something like this:

### module1.py:
def main():
# does something
...

if __name__ == '__main__':
main()

### module2.py:
from module1 import main as main_from_module_one

if __name__ == '__main__':
main_from_module_one() # calling function main defined in module1

Purpose of 'if __name__ == __main__:'

Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!

With the if __name__ == "__main__", this doesn't happen. Your module only "does its thing" if it's run as the main module. Otherwise it behaves like a library. It encourages code reuse by making it easier.

(As Sheng mentions, you may want to import the module into another script yourself for testing purposes.)

if __name__ == '__main__' in IPython

When working from within Emacs (which I assume is close to what you get with %edit), I usually use this trick:

if __name__ == '__main__' and '__file__' in globals():
# do what you need

For obvious reasons, __file__ is defined only for import'ed modules, and not for interactive shell.



Related Topics



Leave a reply



Submit