Low Orbit Flux Logo 2 F

Python - Modules

name variable with name of current module

Define a module like this:

crunchy.py
def crusty(x): x = x += 1 for i in range(10): result += x * i return result def crab(x): # return Fibonacci series up to n x = x += 2 for i in range(50): result += x * i return result

Use the module like this:



import crunchy

crunchy.crusty(1000)
crunchy.crab(100)
crunchy.__name__

crusty = crunchy.crusty
crusty(45)

Import names directly into importing module’s name space:



from crunchy import crusty, crab
crab(500)

You can import anything that doesn’t start with _. This could result in name conflict and is frowned upon. Here is how you do it:



from crunchy import *
crab(500)

import module with different name:



import crunchy as cr
cr.crab(500)

Import fuction with different name:




from crunchy import crab as snipper
snipper(500)

If you want to reload a module that has been changed without restarting the interpreter:



import importlib;
importlib.reload(crunchy)

Run python module as a script:



python crunchy.py

Instructions to be run only when executed as a script ( great for testing ):



if __name__ == "__main__":
    x = sys.argv[1]
    crab(int(x))

Module Search Path

First search built-in modules:



sys.builtin_module_names

Then search in the directories listed here ( can be overwritten ):



sys.path

sys.path is initialized by:

The current script dir is prioritized.



import sys
sys.path.append('/home/user1/my_libs')

Compiled Python files

Compiled version of each module is stored here:



__pycache__/module.version.pyc

Compiled only distribution:

For optimized compiled files:

-O remove aserts
-OO remove aserts and doc strings

dir() Function

Show names ( variables, functions, modules, etc. ) defined by a module as sorted list of strings:



import crunchy, sys
dir(crunchy)
dir(sys)
dir()      # names currently defined

The dir() function does not list built-in names, use the following to show these:



import builtins
dir(builtins)