Modules

Modules

modules are .py files that contain variables and functions for use in other files.

Consider a simple file that lives in this directory.

!type localscript.py
def test_fn():
    print("Sup")

Importing it gives you access to the underlying functions using the '.' operator

import localscript

localscript.test_fn()
Sup

You can see what’s available to you by using the dir command

dir(localscript)
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'test_fn']

module object

The import statement is actually a Python expression.

It uses the given name in "import _____" to find the appropriate file, then assigns whatever it finds to the name, locally, as a module object.

whos
Variable      Type      Data/Info
---------------------------------
localscript   module    <module 'localscript' fro<...>ackages\\localscript.py'>

But like any Python object we can overwrite it, deliberately or otherwise.

import localscript # again
whos
Variable      Type      Data/Info
---------------------------------
localscript   module    <module 'localscript' fro<...>ackages\\localscript.py'>
localscript = 'whoops'
whos
Variable      Type    Data/Info
-------------------------------
localscript   str     whoops

Or straight-up delete it.

import localscript

del localscript
whos
Interactive namespace is empty.