Created
February 7, 2017 03:19
-
-
Save lucsmall/c4acdf3f804c666ef82a0cd6cf0dafd1 to your computer and use it in GitHub Desktop.
An example of using modules and packages in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### BASIC SETUP | |
# set pleasant tab stops | |
cat <<EOF >~/.nanorc | |
set tabsize 4 | |
set tabstospaces | |
EOF | |
# dir for all python command line programs | |
mkdir ~/programs | |
cd ~/programs | |
### CREATE A PYTHON MODULE | |
# create a file mymaths.py | |
def fib(n): | |
if n==0: | |
return 0 | |
elif n==1: | |
return 1 | |
else: | |
return fib(n-1) + fib(n-2) | |
def main(): | |
for i in range(0, 20): | |
print(fib(i)) | |
if __name__ == "__main__": | |
main() | |
# note it will run standalone | |
python mymaths.py | |
### USING THE MODULE | |
# create a file main.py | |
import mymaths | |
for i in range(0, 20): | |
print(mymaths.fib(i)) | |
# run main.py | |
python main.py | |
### CONVERT TO A PACKAGE | |
mkdir myutils | |
mv mymaths.py myutils | |
cd myutils | |
touch __init__.py | |
cd .. | |
# edit main.py to reference package | |
import myutils.mymaths | |
for i in range(0, 20): | |
print(myutils.mymaths.fib(i)) | |
## create a file myutils/myconv.py | |
def inches_to_mm(length): | |
return length * 25.4 | |
## edit main.py to reference package | |
import myutils.mymaths | |
import myutils.myconv | |
for i in range(0, 20): | |
print(myutils.mymaths.fib(i)) | |
print("12 inches in mm:") | |
print(myutils.myconv.inches_to_mm(12)) | |
python main.py |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment