leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Getting Started with Python Modules Tutorial

Estimated reading: 3 minutes 54 views

We have previously learned some basic concepts used in Python programming. From now on, we will try to write a Graphical User Interface (GUI) program. The Python standard library contains modules that support graphics drawing, and we use these modules to draw graphics.

First, we need to understand what a module is.

Getting to know Python modules

A module in Python is a Python file that ends with .py and contains Python object definitions and Python statements. Modules organize Python code segments more logically. Distributing related code into a module makes the code easier to use and easier to understand. Modules can be used to define functions, classes, and variables, and modules can also contain executable code.

When Python is installed, many modules are also installed on the local computer, and we can use these modules for free. These modules that are installed by default when Python is installed are collectively referred to as the “standard library”.

We can use the import statement to import modules. When the interpreter encounters an import statement, it will be imported if the module following the import statement is in the current search path. No matter how many import statements you execute, a module will only be imported once, which prevents importing a module from being executed over and over again.

Python import module

There are two common ways to import modules in Python, let’s look at the first one first.

import module_name

If we use this import method, when we refer to the method in the module, we need to prefix the method name with “module_name.”. Let’s look at a simple example.

import turtle

In these two lines of code, the first sentence is to import the module, and the second sentence is to call the forward() method in the module.

Let’s look at the second method of importing modules.

from module_name import *

Using this method, you can import all the methods and variables in the module_name module. When you need to call a method, you can directly write the method name without adding the “module_name.” prefix.

Let’s rewrite the previous example.

from turtle import *

So, when should I use the first method and when should I use the second method? The first method should be used if you want to selectively import certain properties and methods and not others. If a module contains properties and methods with the same name as one of your own modules, you must use the first method to avoid name collisions.

If you want to access the properties and methods of a module frequently, and don’t want to type the module name over and over, and you won’t have properties and methods with the same name in multiple imported modules, then you can use the second method.

Leave a Comment