Updated the coding example with comments, added a new python package manager called "pipenv". Lastly added a code example on the order of imports with comments. (#23897)

This commit is contained in:
Max Ong Zong Bao
2018-12-31 16:50:01 +08:00
committed by Kristofer Koishigawa
parent 406091303f
commit 65d2d13cd7

View File

@ -1,68 +1,76 @@
--- ---
title: Python Import Statements title: Python Import Statements
--- ---
While learning programming and reading some resources you'd have come across this word 'abstraction' which simply means to reduce and reuse the code as much as possible. While learning programming and reading some resources you undoubtedly came across the word _abstraction_, which simply means to reduce and reuse code as much as possible.
Functions and Modules facilitate abstraction. You create functions when you want to do something repeatedly within a file. Functions and modules facilitate abstraction. You create functions when you want to do something repeatedly within a file.
Modules come into picture when you want to reuse a group of functions in different source files. Modules are also useful in structuring the program well. Modules come into the picture when you want to reuse a group of functions in different source files. Modules are also useful in structuring the program well.
* Using Standard Libraries and other third party modules:
* Structuring the program
## Using Standard Libraries ## Using Standard Libraries
Example: You can read about the methods/functions of all the standard libraries in the official Python Docs in detail. Example: You can read about the methods/functions of all the standard libraries in the official Python Docs in detail.
import time ```python
for i in range(100): import time
for i in range(100):
time.sleep(1) # Waits for 1 second and then executes the next command time.sleep(1) # Waits for 1 second and then executes the next command
print(str(i) + ' seconds have passed') # prints the number of seconds passed after the program was started print(str(i) + ' seconds have passed') # prints the number of seconds passed after the program was started
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C' target='_blank' rel='nofollow'>Run Code</a> ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C' target='_blank' rel='nofollow'>Run Code</a>
# To calculate the execution time of a part of program ```python
import time # To calculate the execution time of a part of program
start = time.time() import time
# code here start = time.time() # Returns the number of seconds that have elapsed since the epoch
end = time.time() # code here
print('Execution time:' , end-start) end = time.time()
print('Execution time:' , end-start)
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C/1' target='_blank' rel='nofollow'>Run Code</a> ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C/1' target='_blank' rel='nofollow'>Run Code</a>
# Using math Module ```python
import math # Using math Module
print(math.sqrt(100)) # prints 10 import math
print(math.sqrt(100)) # prints 10
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C/2' target='_blank' rel='nofollow'>Run Code</a> ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/CS6C/2' target='_blank' rel='nofollow'>Run Code</a>
## Using third party Modules ## Using third party Modules
Third party modules don't come bundled with python , but we have to install it externally using package managers like <a href='https://bootstrap.pypa.io/get-pip.py' target='_blank' rel='nofollow'>`pip`</a> and <a href='https://bootstrap.pypa.io/ez_setup.py' target='_blank' rel='nofollow'>`easy install`</a> Sometimes third party modules do not come bundled with Python, but need to be installed using package managers like [pip](https://bootstrap.pypa.io/get-pip.py), [easy install](https://bootstrap.pypa.io/ez_setup.py), and [pipenv](https://github.com/pypa/pipenv).
# To make http requests ```python
import requests # To make http requests
rq = requests.get(target_url) import requests
print(rq.status_code) rq = requests.get(target_url)
print(rq.status_code)
```
Find out more about python-requests module <a href='http://docs.python-requests.org/en/master/' target='_blank' rel='nofollow'>here</a> Find out more about python-requests module <a href='http://docs.python-requests.org/en/master/' target='_blank' rel='nofollow'>here</a>
## Local imports ## Local imports
Files/Modules in the same project can be imported just by their name. import also supports relative references to files/modules as shown below: Files/Modules in the same project can be imported just by their name. `import` also supports relative references to files/modules as shown below:
# to relatively import a file in adjacent module ```python
import '../adjacent_module/file_to_import' # To import a file within a project from "adjacent module"
import '../adjacent_module/file_to_import'
```
However, as a good practice, it is recommended not to use relative paths in imports. However, as a good practice, it is recommended not to use relative paths in imports.
## To structure programs ## To structure programs
We want to make a program that has various functions regarding prime numbers. So lets start. We will define all the functions in `prime_functions.py` We want to make a program that has various functions regarding prime numbers. So lets start. We will define all the functions in `prime_functions.py`:
# prime_functions.py ```python
from math import ceil, sqrt # prime_functions.py
def isPrime(a): from math import ceil, sqrt
def isPrime(a):
if a == 2: if a == 2:
return True return True
elif a % 2 == 0: elif a % 2 == 0:
@ -73,7 +81,7 @@ We want to make a program that has various functions regarding prime numbers. So
return False return False
return True return True
def print_n_primes(a): def print_n_primes(a):
i = 0 i = 0
m = 2 m = 2
while True: while True:
@ -83,17 +91,27 @@ We want to make a program that has various functions regarding prime numbers. So
m += 1 m += 1
if i == a: if i == a:
break break
```
Now we want to use the functions that we just created in `prime_functions.py` so we create a new file `playground.py` to use those functions. Now we want to use the functions that we just created in `prime_functions.py`, so we create a new file called `playground.py` to use those functions.
> _Please note that this program is far too simple to make two separate files, it is just to demonstrate. But when there are large complex programs, making different files is really useful._ > _Please note that this example is far too simple to need two separate files -- it is just to demonstrate. But when there are large, complex programs, splitting the code into different files is really useful._
# playground.py ```python
import prime_functions # playground.py
print(prime_functions.isPrime(29)) # returns True import prime_functions
print(prime_functions.isPrime(29)) # returns True
```
## Sorting Imports ## Sorting Imports
Good practice is to sort `import` modules in three groups - standard library imports, related third-party imports, and local imports. Within each group it is sensible to sort alphabetically by module name. You can find [more information in PEP8](https://www.python.org/dev/peps/pep-0008/?#imports). A good practice is to sort `import` modules into three groups - standard library imports, related third-party imports, and local imports. Within each group it is sensible to sort alphabetically by module name. You can find [more information in PEP8](https://www.python.org/dev/peps/pep-0008/?#imports).
One of the most important thing for Python language is legibility, and alphabetically sorting modules are quicker to read and search. Also it is easier to verify that something is imported, and avoid duplicated imports. ```python
# Order of importing modules
import time # Standard library modules
from package import calculate_duration # Related third-party modules
from package.sibling import example # Local modules within the project
```
One of the most important things to keep in mind when writing Python is legibility, and alphabetically sorting modules makes them faster to read and search through. Also, it is easier to verify that something is imported, and avoid duplicated imports.