What Are Modules?
Each .py
file is a module within a program.
import
is how you can input functions into a file.
Say you have a file that defines functions but doesn’t call them. You call this file the utility.py
To access these functions, you can simply say import utility
at the very top of your code.
__pycache__
will generate itself within the program. To cache the access to the data in case there are no changes.
Say you have a folder called shopping
and in it is a file called cart.py
. You could call it into your program by going: import shopping.cart
.
Packages
Folders within a Python program that have individual __init__
files. And contain other Python modules
Different ways of importing
Like before, you can import in ways like import shopping.cart
. But perhaps you have a lot of layers in your program and only need a specific function.
You can call it by going from shopping import cart
and you can reference specific functions within the file you are calling. Seperated by commas of course from math import divide, multiply, add, subtract
Or you can go from shopping.cart import new_cust_discount
There are various ways to access specific functions and methods through modules.
__name__
if __name__ == __main__:
this is an if statement asking if the name
dundar is equal to the main
dundar file. This is apparently a common line to see in Python code.
__main__
is a determination given to a specific file in the program. Doesn’t have to be named main.py
though it seems traditionally it is.
The above if statement is useful to only run certain code from the main file.
Some bits to remember
Give a module an alias if you want to avoid collisions import random as bingo
You can also single out a specific function within a module if that’s all you need from random import shuffle