#compsci #python A **module** is a Python program that can be used in other programs. # Use of Modules ## Running stuff ^c29627 In simple terms, every file of Python source code whose name ends in a .py extension is a module. This module-based services model turns out to be **the core idea behind program architecture in Python**. Larger programs usually take the form of multiple module files, which import tools from other modules. One of the modules is designated as the main or **top-level** file, and this is the one launched to start the entire program. Imports can be used to launch scripts, as in here: ![[this (Python)#^98817e]] ^52352a However, imports work like that **only once per session**. If you want to use it again, then you must use the **reload()** function from the [[imp module]]: ^93961e ```python from imp import reload reload(this) ``` ^3814ba You can also use the built-in [[exec function]]: ```python >>> exec(open('script.py').read()) ``` Though it must be noted that it runs without isolated namespaces, and may overwrite your variables. ## Libraries Modules are mofe often libraries of tools, mostly just a package of variable names, known as a [[Namespace|namespace]]. The names within that package are called *attributes* - simply a variable name that is attached to a specific object (like a module). For example, upon the execution of the following module: ```python title = "Traps are not gay" ``` an attribute named `title` is created. You can also access that attribute using the `object.attribute` expression. However, when you access it like that, you copy the module's variables, whereas in "import %name%" you get a module with attributes. You can use the built-in **dir()** function to fetch a list of the names available inside a module: ```python >>> dir(example) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a'. 'b', 'test'] ``` Names with double underscores are predefined by Python.