#module nametest

def showName():
   print("__name__ is: " + str(__name__))

If I import nametest into another module or into the shell interpreter and call nametest.showName() I find that name = "nametest", in other words name gets the module name it is a built-in member of?

The only exception I know of is if I define showName directly in the shell without importing it in a module, then name shows "main". Is there any other way to get the function "showName()" to print a value other than "nametest".

Here is one

import nametest
nametest.__name__ = "foobar"
nametest.showName()

Thanks Gribouillis So (sorry if this is obvious question) would it be correct to say the main purpose of name is to verify what module the particular function/class was defined in? (As opposed to where it is called from). Other than passing self or something similar as an argument to a function, is there any dynamic builtin variable a function can use to print out where it was called from, not knowing ahead of time how it might be used. (Other than toggling the debugger).

By the way, does nametest.name = .... reset the original variable or create a new one?

You can tell where the function was called from using module inspect

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function

__doc__ = """ sandbox.funccall -

    show how to print where a function was called from
"""

import inspect
import os

def calling_line(level):
    level = max(int(level), 0)
    frame = inspect.currentframe().f_back
    try:
        for i in xrange(level):
            frame = frame.f_back
        lineno, filename = frame.f_lineno, frame.f_code.co_filename
    finally:
        del frame
    return lineno, filename


def thefunc(*args):
    lineno, filename = calling_line(1)
    print("thefunc() was called from {0} at line {1}".format(
        os.path.basename(filename), lineno))
    return 3.14

def foo():
    x = thefunc() ** 2

if __name__ == "__main__":
    foo()

""" my output -->

thefunc() was called from funccall.py at line 32
"""

Otherwise, yes, nametest.__name__ = ... resets the original variable. __name__ is an ordinary global variable which is automatically inserted in the module's namespace. Another interesting variable which exists only for imported modules is__file__.

Excellent! Thank you Gribouillis...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.