Skip to content

Carlos Iriarte

Learning Python | Modules

python, learning3 min read

When we build programs sometimes they get big. The same way we split little pieces of logic with Methods, Functions and Classes we might want to start segregating our code in multiple files, for many reasons, the most common one is to reuse a piece of code that we already wrote. Let's see how all that works.

When we writing the first few programs in earlier posts, we created a file named like cat.py and then keep appending more code at the end of the file.

Let's try to use our file in another program!

Create a new file by opening a terminal and type:

Note: Whenever you see $ at the beginning of commands it means it should be typed in your terminal.

Now let's add the following content to our file:

Now let's run our new script:

What we're seeing is the output of cat.py. Why is that? When we use other imports we usually don't get this kind of output!

When Python reads our file it starts "interpreting" our statements from top to bottom, line by line. Therefore adding the following line:

Acts as a copying and pasting cat.py in our main.py at the top of the file.

Rad. Except when it's not. Most of the time, what we want to do when reusing code this way is to import the definitions. In our example above we want to get just the Cat definition, but we don't want to execute all those meows.

To do that, we need to go back to the original cat.py and make a few adjustments:

class Cat:
def __init__(self,
oos_when_hungry,
oos_when_playful,
oos_when_open_door):
self.oos_when_hungry = oos_when_hungry
self.oos_when_playful = oos_when_playful
self.oos_when_open_door = oos_when_open_door
@staticmethod
def meow(number_of_os):
print("ฅ^•ﻌ•^ฅ Me" + "o" * number_of_os + "w")
def open_the_door(self):
Cat.meow(self.oos_when_open_door)
def hungry(self):
Cat.meow(self.oos_when_hungry)
def i_wanna_play(self):
Cat.meow(self.oos_when_playful)
def equals(self, other_cat):
if self.oos_when_hungry == other_cat.oos_when_hungry and \
self.oos_when_playful == other_cat.oos_when_playful and \
self.oos_when_open_door == other_cat.oos_when_open_door:
return True
else:
return False
def __equals__(self, other_cat):
return self.equals(other_cat)
# Let me tell you about my girly kitty's morning
a = Cat(1, 4, 8)
a.open_the_door()
a.hungry()
a.i_wanna_play()
print() # Let's add some space for readability. This line has nothing to do with the cats.
# Let me tell you about my big macho kitty
b = Cat(2, 10, 5)
b.open_the_door()
b.hungry()
b.i_wanna_play()
print() # Let's add some space for readability. This line has nothing to do with the cats.
if a.equals(b):
print("a == b Same Cat")
else:
print("a == b Not the same Cat!")
print() # Let's add some space for readability. This line has nothing to do with the cats.
if a.equals(a):
print("a == a Same Cat")
else:
print("a == a Not the same Cat!")
print() # Let's add some space for readability. This line has nothing to do with the cats.
if b.equals(b):
print("b == b Same Cat")
else:
print("b == b Not the same Cat!")
print() # Let's add some space for readability. This line has nothing to do with the cats.
if a == b:
print("a == b It's the same cat!")
else:
print("a == b It's not the same cat!")
print() # Let's add some space for readability. This line has nothing to do with the cats.
if a == a:
print("a == a It's the same cat!")
else:
print("a == a It's not the same cat!")
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.
print() # Let's add some space for readability. This line has nothing to do with the cats.

First, let's review what we mean by "definitions":

A definition is every time we describe the behavior of a class, a method or a function.

Later on, we use these definitions when we instantiate/create objects of the class or when we invoke those methods and functions.

We can reuse those definitions by "importing" them in our main.py from our cat.py module.

But what about those extra meows we got when we imported the cat module the first time? Let's go back to cat.py for a moment.

You can prevent executing those statements by checking if the file cat.py was invoked as a module or as a script by checking its name.

You achieve that by checking the special variable __name__ and compare it to the string "__main__". Don't forget to indent the code that instantiates and tests the code to match the if statement in your condition.

Let's take a look at a module we didn't write: jira. Let's install that module first:

Note: make sure you run the steps in setting up your development environment

from jira import JIRA
options = {"server": "https://jira.atlassian.com"}
jira = JIRA(options)
# Get all projects viewable by anonymous users.
projects = jira.projects()
print(projects)
options = {"server": "https://jira.atlassian.com"}
options = {"server": "https://jira.atlassian.com"}
options = {"server": "https://jira.atlassian.com"}
options = {"server": "https://jira.atlassian.com"}
options = {"server": "https://jira.atlassian.com"}
options = {"server": "https://jira.atlassian.com"}

Let's analyze the following code line by line:

From the jira module, get the JIRA class definition.

Construct a dictionary (a dict object) with key server and value https://jira.atlassian.com, and assign the value to the options variable.

With those options, instantiate a jira object from the JIRA class.

Invoke the projects function from my new jira object and assign the results to the projects variable.

Print the object projects.

But... how does python know where to find the jira module. What does it mean "to install it"?

If you compare the jira example from above to our cat module example. One important difference is that cat.py was located in the same directory as our main.py file.

Like most programming languages, Python cares where you place your files, and it follows a series of rules to find modules. You can read more about those rules here.

I'll try to simplify what that page says here:

Note: you can modify this behavior but that's a bit out of scope for this tutorial.

  1. It looks for built-in functions.
  2. It looks for modules in your current working directory (this is how it found cat.py!)
  3. It looks at the python installation folder (your site-packages).

i.e. installing the jira module means to get the files from some location on the internet and placing them in the right location in your computer.

Now that we know that, the really cool fact is that the JIRA class we're using in our code is not that special. Someone else wrote it, published it in pypi.org and made it available for everyone.

When we ran:

the command pipenv just helped us to place all those bits we downloaded in the right place.

You can even learn how jira was implemented (which is just a fancy word to say "coded" or "written")

You can read how the JIRA class has an __init__ method. Or the projects function.