i

Python Programming

The PYTHON PATH-Variable

PYTHONPATH is environment variable, consisting of a list of the directories. Syntax of PYTHONPATH is same as that of the shell variable PATH.

Below is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python37\lib

Here is a typical PYTHONPATH from UNIX system:

set PYTHONPATH => /usr/local/lib/python

Namespaces / Scoping

The Variables are names (identifiers) that map to the objects. The namespace is a dictionary of the variable names (keys) and their corresponding objects (values).

Python statement can access the variables in a local name-space and global name-space. If a local and a global-variable have the same name, the local-variable shadows the global-variable.

Each function has its local-namespace. Class methods follow the same scoping-rule as ordinary functions.

The statement global-VarName shows Python that VarName is the global variable. Python stops searching local name-space for variable.

If understand by example, we define variable money in the global namespace. Within  function money, we assign money a value, hence python assumes money as a local variable. However, we accessed the value of local variable money before setting it, so  UnboundLocalError is the result. Un-commenting global statement fixes problem.

dir( ) Function

dir() built-in-function returns the sorted list of the strings containing the names defined by the module.

List contains the names of all modules, variables and functions are defined in a module. Please check below example:

Live Demo

Output:

'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e',

'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'log',

'log10', 'modf', 'pi', 'pow', 'sin', 'sinh',

'sqrt', 'tanh']

The special string variable __name__ is the module name, and __file__ is the filename from which module was loaded.

The globals() / locals() Functions

The globals() / locals() functions can be used to return names in global and local namespaces depending on location from where they called.

If locals() is called from within the function, it will return all names that can be accessed locally from that function.

If globals() is called from within the function, it will return all names that can be accessed globally from that function.

The return type of the both these functions is dictionary. Hencenames can be extracted using  keys() function.

The reload()-Function

When the module is imported into the script, the code in top-level portion of the module is executed only once.

Hence if you want to re-execute the top-level code in a module, you can use reload() function. The reload() function imports previously imported module again. The syntax of reload() function is this:

The reload(module_name)

In module_name is name of the module you want to reload and not string containing the module name. For example, to reload the helloo module, do the following:

reload(helloo)