Tutorial #6: Python Modules and Packages Rapt Kickstart

Python Modules and Packages

Python Modules and Packages Successful and Helpful!

Complete Python Bootcamp From Zero to Hero in Python (Basic Modules and Packages)

Contents

1. Creating Modules and Packages

2. Using __name__ and __main__

Create ‘modules_and_packages’ directory:

inside ‘modules_and_packages’ create ‘module.py’ then add this:

def hello(name):

print(‘Hello’, name)

inside ‘modules_and_packages’ create ‘program.py’ then add this:

from basic_codes import hello

hello(‘Your Name’)

Then run program.py to see sample:

# output: Hello Your Name

—————————————————————–

inside ‘modules_and_packages’ create ‘package’ directory

under ‘package’ directory create ‘__init__.py’

under ‘package’ directory create ‘main.py’

inside ‘main.py’ add this code:

def report_main():

print(“Im report_main function inside package > main.py”)

—————————————————————–

under ‘package’ directory create ‘subpackage’ directory

under ‘subpackage’ directory create ‘__init__.py’

under ‘subpackage’ directory create ‘submain.py’

inside ‘submain.py’ add this code:

def report_submain():

print(“Im report_submain function inside subpackage > submain.py”)

—————————————————————–

Back to ‘programs.py’ and add this inside then run:

from package.main import report_main

from package.subpackage.submain import report_submain

report_main()

report_submain()

# output:

Hey Im report_main function inside package > main.py

Hey Im report_submain function inside subpackage > submain.py

—————————————————————–

You can check the files here

Python Modules and Packages Effective Harmoniously!

—————————————————————–

2. Using __name__ and __main__

Create ‘name_and_main’ directory:

Inside ‘name_and_main’ directory create ‘one.py’ then add this:

def one_func():

print(“one_func() function ran in one.py”)

print(“top-level print inside of one.py”)

if __name__ == “__main__”:

print(“one.py is being run directly”)

else:

print(“one.py is being imported into another module”)

# output:

top-level print inside of one.py

one.py is being run directly

—————————————————————–

Python Modules and Packages – Brilliant Hard-working!

Inside ‘name_and_main’ directory create ‘two.py’ then add this:

import one

print(“top-level in two.py”)

one.one_func()

if __name__ == “__main__”:

print(“two.py is being run directly”)

else:

print(“two.py is being imported into another module”)

#output:

top-level print inside of one.py

one.py is being imported into another module

top-level in two.py

one_func() function ran in one.py

two.py is being run directly

Python Modules and Packages
Tagged : / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x