Creating a module

suggest change

A module is an importable file containing definitions and statements.

A module can be created by creating a .py file.

# hello.py
def say_hello():
    print("Hello!")

Functions in a module can be used by importing the module.

For modules that you have made, they will need to be in the same directory as the file that you are importing them into. (However, you can also put them into the Python lib directory with the pre-included modules, but should be avoided if possible.)

$ python
>>> import hello
>>> hello.say_hello()
=> "Hello!"

Modules can be imported by other modules.

# greet.py
import hello
hello.say_hello()

Specific functions of a module can be imported.

# greet.py
from hello import say_hello
say_hello()

Modules can be aliased.

# greet.py
import hello as ai
ai.say_hello()

A module can be stand-alone runnable script.

# run_hello.py
if __name__ == '__main__':
    from hello import say_hello
    say_hello()

Run it!

$ python run_hello.py
=> "Hello!"

If the module is inside a directory and needs to be detected by python, the directory should contain a file named __init__.py.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Getting Started:
* Creating a module

Table Of Contents
0 Getting Started
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve