What is import statement in python

Python Import Statements Explained

Python Import Statements Explained

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.

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.

Using Standard Libraries

Example: You can read about the methods/functions of all the standard libraries in the official Python Docs in detail.

import time for i in range(100): 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
# To calculate the execution time of a part of program import time start = time.time() # code here end = time.time() print('Execution time:' , end-start)
# Using math Module import math print(math.sqrt(100)) # prints 10

Using third party Modules

Third party modules don’t come bundled with python , but we have to install it externally using package managers like pip and easy install

# To make http requests import requests rq = requests.get(target_url) print(rq.status_code)

Find out more about python-requests module here

Читайте также:  Html menus and submenus

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

# prime_functions.py from math import ceil, sqrt def isPrime(a): if a == 2: return True elif a % 2 == 0: return False else: for i in range(3,ceil(sqrt(a)) + 1,2): if a % i == 0: return False return True def print_n_primes(a): i = 0 m = 2 while True: if isPrime(m) ==True: print(m) i += 1 m += 1 if i == a: 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.

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.

# playground.py import prime_functions print(prime_functions.isPrime(29)) # returns True

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.

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.

From X import Y: an example

>>> from math import ceil, sqrt >>> # here it would be >>> sqrt(36) 

Or we could use this one instead:

>>> import math >>> # here it would be >>> math.sqrt(36) 

Then our code would look like math.sqrt(x) instead of sqrt(x) . This happens because when we use import x , a namespace x is itself created to avoid name conflicts. You have to access every single object of the module as x. .

But when we use from x import y we agree to add y to the main global namespace. So while using this we have to make sure that we don’t have an object with same name in our program.

Never use from x import y if an object named y already exists

For example, in os module there’s a method open . But we even have a built-in function called open . So, here we should avoid using from os import open .

We can even use form x import * , this would import all the methods, classes of that module to the global namespace of the program. This is a bad programming practice. Please avoid it.

In general you should avoid from x import y simply because of the problems it may cause in large scale programs. For example, you never know if a fellow programmer might want to make a new function that happens to be the name of one of the existing functions. You also do not know whether Python will change the library that you are importing functions from. While these problems won’t exist as often for solo projects, as stated before, it is bad programming practice and should be avoided.

Источник

Understanding Python Import Statements: What does a ‘.’ Mean?

What Does A DOT( ) In An Import Statement In Python Mean

The import statement in Python allows us to access in built functions present in other files. Instead of writing one program over and over again for using it in various different functions, Python’s flexibility achieve this feat with just one statement.

There are two major types of imports in Python: absolute imports and relative imports. Most of the time we use absolute imports but sometimes it is effective to use relative imports.

A dot or a period (.) in an import statement is the directory of a module for relative imports in Python. It is how relative imports are done in Python. Import statements can be used to use all the functions inside a particular module or libraries only with one line. When performing relative imports we are going to use the “dot” in the import statement.

What are Python Import Statements? An Explanation

Importing in Python brings in existing code from other files, eliminating the need for repetitive coding. In programming, especially in Python, imports allow us to use existing code from other files into our own code without having to write them all over again.

Import statements can be used to use all the functions inside a particular module or libraries only with one line.

The Benefits of Using Import Statements in Python

There are many advantages of using import statements in your code. Such as:

  • It makes your code more effective.
  • It makes your code look nice and clean
  • You avoid writing extra lines of code over and over again.
  • You can use variables from various other modules into your code and not have to worry about assigning variables that you might need at runtime.
  • You can import data files as well into your program.

Best Practices and Rules for Importing in Python

There are some rules to importing modules and files in Python. They are:

  • One should always write all of the import statements at the very top of the code block. All of the required modules or libraries should be imported at the very beginning.
  • There is a hierarchy that one should follow when importing various files. All of the required in built modules should be imported at the very beginning. Modules that have been installed along with the python installation comes under this type.
  • This is followed by imports of all of the third-party packages that weren’t installed via the official installer.
  • The files on your local machine that you might need in your current code is imported as the final successor of the above two statements.

Import statements are very easy to use. You just need to use the import statement before a module’s or a package’s name to import it. For example,

If you want to assign the package’s content into a variable you can use the “as” keyword followed by the variable name as well.

To know more about how to import files in your Python program, click here!

Absolute vs Relative Imports: A Deeper Dive

Absolute imports provide the full path of a module, while relative imports only indicate the directory relative to the current file.

There used to be two kinds of relative imports in the previous versions of Python that is before Python3. Those were implicit relative imports and explicit relative imports.

Implicit relative imports are were in general very messy, hence they were not supported anymore in Python 3. This is why only explicit relative imports exist nowadays because they are easy to use and clean.

Let’s consider a directory containing a Python modules which further contains sub modules or programs in them as follows:

Module Paths And Hierarchies

Using Absolute Imports

  • First Scenario: Suppose we have a Python module, let’s call it “third_module“, inside a directory or library named “second_library“.
  • Absolute Import: To import a function, say “function1“, from this “third_module” using an absolute import, our statement would look like this: from second_library.third_module import function1 . This provides the full path of the function within the module hierarchy.
#using absolute import method to import function1 from the third_module from second_library.third_module import function1

There are some disadvantages to using absolute imports. When the paths are long and there are numerous sub packages in a single directory when importing multiple functions, this method becomes very wordy and inaccurate.

Using Relative Imports

  • Second Scenario: Now, let’s consider we are inside the same “second_library” and want to import “function2” from the “third_module”.
  • Relative Import: We can use a single dot (.) representing the current directory in our import statement, like this: from .third_module import function2 . This way, we only specify the location of “third_module” relative to the current file.
  • Third Scenario: Suppose we have another library named “first_library” at the same level as “second_library”, and we want to import “module1” from “first_library”.
  • Relative Import: We can use two dots (..) representing the directory above the current directory in our import statement, like this: from ..first_library import module1 .
  • Fourth Scenario: For importing “second_library” from a grandparent directory named “Our_Directory”, we can use three dots (…) in our import statement.
  • Relative Import: Our import statement would look like this: from . Our_Directory import second_library
#examples of relative imports from .third_module import function2 from .. first_library import module1 from . our_directory import second_library

There are disadvantages to using relative imports as well. When directory structures change from one system to another, it becomes difficult to keep track of them. The locations become difficult to pinpoint.

To know more in depth about absolute and relative imports, check out this article!

Python Import Statements: Final Thoughts and Considerations

It is very important to know how to use import statements in Python. They are efficient and make your code look clean and nice and legible. There are two ways of using imports, they are the absolute import statements and the relative import statements. Both have their pros and cons. Do you think relative imports are easier than absolute imports or the opposite?

Источник

Оцените статью