0% found this document useful (0 votes)
22 views

Lecture 09

Each Python file is considered a module that contains definitions and statements within a namespace; modules allow code reuse and organization of large projects into multiple files; the import statement is used to access objects defined in other modules and make them available in the current namespace.

Uploaded by

ج 90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lecture 09

Each Python file is considered a module that contains definitions and statements within a namespace; modules allow code reuse and organization of large projects into multiple files; the import statement is used to access objects defined in other modules and make them available in the current namespace.

Uploaded by

ج 90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Module

• Each file in Python is considered a module.


Everything within the file is encapsulated within a
namespace (which is the name of the file)
• Why Modules?
• Reuse code
• Manage large projects
• Professional projects can be hundreds of thousands of
lines long
• Would be nearly impossible to maintain in one file
1
Creating a Module

• A module is a file containing Python definitions and


statements.
• The file name is the module name with the
suffix .py appended.
• Within a module, the module’s name (as a string) is
available as the value of the global variable
__name__.
• For Example: use your text editor to create a file
called mymath.py in the current directory with the
following contents (in the next slide):
2
Creating a Module
Any Python source file is a module
# mymath.py
pi = 3.14

def add(x,y):
return x + y

def sub(x,y):
return x - y

Several objects are defined in mymath.py file:

• pi : Float

• add : Function

• sub : Function

3
How to use the Module?
• You can use any Python source file as a module by
executing an import statement in another Python
source file.
• import has the following syntax:
import modulename

• To use the module mymath, we just type:


import mymath

4
Module Execution
• When a module is imported, all of the statements in
the module execute one after another until the end of
the file is reached
• If there are scripting statements that carry out tasks in
the global scope (printing, creating files, etc.), you will
see them run on import
main.py mymath.py

import mymath # mymath.py


x = 1 pi = 3.14
Y = 13
def add(x,y):
return x + y

7 def sub(x,y):
The output return x – y
of main.py add(2,5) 5
Access to the imported objects
• Objects (variables, Functions, Classes,… etc.) in any
module can be accessed using the module’s name,
a dot (.) and the object name.
main.py
import mymath mymath.py
m = 1
# mymath.py
n = 13
pi = 3.14
mymath.add(m,n)
mymath.sub(m,n) def add(x,y):
print(mymath.pi) return x + y

14 def sub(x,y):
-12 return x – y
3.14
The output of main.py 6
Import by alias
• For longer module names, it's not convenient to use
the full module name each time you access some
element.
• For this reason, you can use the "import ... as ..."
pattern to create a shorter alias for the namespace.
• Example: mymath.py
# mymath.py
import mymath as m
pi = 3.14
m = 1
n = 13
def add(x,y):
m.add(m,n) return x + y

def sub(x,y):
return x – y 7
The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace.

• Allows parts of a module to be used without having


to type the module prefix

• The from...import has the following syntax −


from modulename import name1[name2 ..]

8
The from...import Statement Cont’d
Example
main.py mymath.py
from mymath import add
# mymath.py
m = 1
n = 13
pi = 3.14

add(m,n) def add(x,y):


return x + y

def sub(x,y):
return x – y

• This statement does not import the entire module mymath


into the current namespace; it just introduces the item add.
• You cannot use the function sub in the main program

9
The from...import *  Statement
• It is also possible to import all names from a
module into the current namespace by using the
following import statement

from modulename import *

• Takes all symbols from a module and places them


into local scope

10
The from...import *  Statement
• Example
main.py mymath.py
from mymath import * # mymath.py
m = 1 pi = 3.14
n = 13
def add(x,y):
add(m,n)
return x + y
sub(m,n)
print (pi)
def sub(x,y):
return x – y

This provides an easy way to import all the items from a


module into the current namespace; however, this
Usually considered bad style (try to avoid)
11
Commentary
• Variations on import do not change the way that
modules work
• import mymath as m
• from mymath import add, sub
• from mymath import *
• ...
• import always executes the entire file
• Modules are still isolated environments
• These variations are just manipulating names

12
Module Names

• File names have to follow the rules

• avoid non-ASCII characters

13
Naming Conventions
• It is standard practice for package and module
names to be concise and lowercase
person.py Not ThePersonModule.py
• Use a leading underscore for modules that are
meant to be private or internal
_person.py
• Don't use names that match common standard
library modules (confusing)
math.py os.py

14
The dir() Function
• The built-in function dir() returns a list of defined
names in a namespace. Without arguments, it
produces an alphabetically sorted list of names in
the current local symbol table:
mymath.py
main.py
import mymath # mymath.py
print(dir(mymath)) pi = 3.14

def add(x,y):
['__builtins__', '__cached__', '__doc__', return x + y
'__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'pi', 'sub'] def sub(x,y):
return x – y

15
__main__ check
• Python module can test if the module is being used
as the main program by checking if global variable
__name__ has the value '__main__' .

• If a file might run as a main program, do this


...
if __name__ == '__main__':
# Running as the main program
...

• Such code would not run on library import


__main__ check
Cont’d
mymath.py
• Example pi = 3.14

def add(x,y):
main.py return x + y

import mymath def sub(x,y):


pass return x - y

Run in the imported if __name__ == '__main__':


print('Run in mymath')

if __name__ != '__main__':
print('Run in the imported')

Run in mymath 17
How Imports Work?

1. Find the module’s file.

2. Compile it to byte code (if needed).

3. Run the module’s code

18
How Imports Work?

1. Find the module’s file.

2. Compile it to byte code (if needed).

3. Run the module’s code

19
1- Find the module’s file
• When you import a module, the Python interpreter
searches for the module in the following sequences
1) The current directory.
2) If the module isn't found, Python then searches each
directory in the shell variable PYTHONPATH.
3) Standard library directories

• The module search path is stored in the system module


sys as the sys.path variable. The sys.path variable
contains the current directory, PYTHONPATH, and the
installation-dependent default.
20
The sys.path List
• The resulting search path is accessible in the
Python variable sys.path, which is obtained from a
module named sys:
import sys
print(sys.path)
['C:\\Users\\User\\PycharmProjects\\test2\\venv\\Scripts\\python37.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\
Users\\User\\PycharmProjects\\test2\\venv', 'C:\\Users\\User\\
PycharmProjects\\test2\\venv\\lib\\site-packages',

Note: The exact contents of sys.path are installation-dependent. The above will
almost certainly look slightly different on your computer.
21
Modify sys.path
• One additional option that you can create a module
file in any directory and then modify sys.path at
run-time by adding the new directory.

• The sys.path will contain the new directory.

• For example, if you create mymath.py module in


directory C:\Users\myproject and then use the
following statements:

import sys
sys.path.append(“C:\Users\myproject")
import mymath
22
Determine the Location
• Once a module has been imported, you can determine the
location where it was found with the module’s __file__
attribute:
import mymath

print(mymath.__file__)

C:\Users\User\.PyCharmCE2018.2\config\scratches\mymath.py

• Or by using module’s name:


print(mymath)

<module 'mymath' from 'C:\\Users\\User\\.PyCharmCE2018.2\\config\\


scratches\\mymath.py'>
23
How Imports Work?

1. Find the module’s file.

2. Compile it to byte code (if needed).

3. Run the module’s code

24
2- Compile it to byte code (if
needed)
• After finding a source code file that matches an import
statement, Python next chooses an action as follows:
 Compile :
• if it has not compiled before. Then python will store
the byte code of your programs in files that end with a
.pyc extension (“.pyc” means compiled “.py” source).
• If the byte code file is older than the source file (i.e., if
you’ve changed the source), Then will be compiled
again.
• byte code files are stored in a __pycache__
subdirectory

25
2- Compile it to byte code (if
needed)
 Don’t compile:
• Python finds a .pyc byte code file that is not
older than the corresponding .py source file and
was created by the same Python version, it skips
the source-to-byte-code compile step.

• If Python finds only a byte code file on the


search path and no source, it simply loads the
byte code directly.

26
How Imports Work?

1. Find the module’s file.

2. Compile it to byte code (if needed).

3. Run the module’s code

27
3- Run the module’s code
• The final step of an import operation executes the
byte code of the module.

• if any top-level code in a module file does real


work, you will see its results at import time.

• For example, top-level print statements in a module


show output when the file is imported. Function
def statements simply define objects for later use.

28
Reloading Modules
• Python loads a module only the first time you
import the module during a program run.
• However, If a module has changed, you can reload
the new definition of the module using the
imp.reload function.
• reloading looks like this:
import module # Initial import
...use module.attributes...
... # Now, go change the module file
...
from imp import reload # Get reload itself
reload(module) # Get updated
...use module.attributes...
29

You might also like