Variables in Python Modules

All kinds of variables can be stored in a module, including arrays and dictionaries. Functions can also be stored in a module.

For Example,

Open the newmodule.py file and write this code in it and save the file:

def welcome (name):
print ("Hello, " + name +" to 30 Days of Python")

person1 = {
  "name": "Tobby",
  "age": 19,
  "country": "Nigeria"
}

Now let us import the module again and try to access the person1 dictionary:

import newmodule
newmodule.welcome ("Tobby")

a = newmodule.person1 ["age"]
b = newmodule.person1 ["name"]
c = newmodule.person1 ["country"]
print (c)

Output:

Hello, Tobby to 30 Days of Python

Nigeria

How to rename a Python Module?

We can name the module file whatever we want, but we must keep in mind that the file extension must be “.py.”

To change the name of a module, we can make a nickname when we import a module with the as keyword.

For Example, let us create a new name for our newmodule module and call it mymodule:

import newmodule as mymodule
mymodule.welcome ("Tobby")

a = mymodule.person1 ["age"]
b = mymodule.person1 ["name"]
c = mymodule.person1 ["country"]
print (c)

Output:

Hello, Tobby to 30 Days of Python

Nigeria

How does Import from Modules work?

Using the from keyword, we may selectively import data from one module while leaving out data from another.

For Example,

Now, we have a module named newmodule that has one function and one dictionary:

def welcome (name):
print ("Hello, " + name +" to 30 Days of Python")

person1 = {
  "name": "Tobby",
  "age": 19,
  "country": "Nigeria"
}

Now, Let’s import only the person1 dictionary from the module named newmodule:

from newmodule import person1
print (person1 ["age"])

Output: 19

NOTE: Here, we need to keep in mind that when we use the from keyword to try to import something, we should not use the module name when talking about things in the module.

For Example, we type the code as:

person1[“age”],

not

newmodule.person1[“age”]

Advantages of Modules

There are a lot of benefits to working with modules in Python, like this one:

Reusability

Working with modules means that the code can be reused.

Simplicity

The module only looks at a small part of the problem, not the whole thing.

Scoping

In a module, there’s a separate namespace that doesn’t have the same name as other identifiers.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials