Python Forum

Full Version: Seeking understanding with the python import function.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a beginner Python programmer, and I am now learning about the import sys. My primary influence is a program that I have been working on for a bit now, which I feel like needs to be broken down into several different modules.

I started reading this article online which was an intro to using the import sys, and I ran some code examples to confirm my understanding of the topic. I created the following module, from a file I called Testy.py:

>>> a=11
>>> b=3
>>> def add(a,b):
"""This program adds two numbers and return the result."""
result=a+b
return result

The function ran fine from it's own module. Later I tried importing and running all the statements from Testy in a different module, which i will refer to as "Scripty".

It didn't work how I assumed it would work. I initially added a line to Scripty which imported Testy. I then tried to call the function add(a,b) from within Scripty, I kept getting errors saying "a is not defined", and "b is not defined".

After trial and error, moving this line around and that line, I connected the dots and realized that by me simply stating "import Testy" I wasn't getting everything I needed.

I then added lines to scripty stating:

>>>from Testy import a
>>>from Testy import b

Everything worked perfectly after that, I got the rest of the code I needed.

My question for the community is, what exactly does a simple import statement do? Why did I have to specify on different lines to import certain objects/statements. Do I have to do this, is there a simpler way to get all the statements from a module?
You could do a dissertation on import, but shy of that, what better way to expose yourself than
a video by the guy that rewrote import for python 3, Brett Cannon: https://www.youtube.com/results?search_q...ett+Cannon
It is quite complicated (but also quite interesting), so put your seat-belt on.
To fix it so it make sense.
There should be no >>> in code that's imported.
# foo.py
def add(a, b):
    """This program adds two numbers and return the result."""
    result = a + b
    return result
So now i want to use add function in an other script.
# bar.py
from foo import add

a = 11
b = 3
print(add(a, b))
Output:
14
You can look at my tutorial here,it's a little heavy as it cover a lot Module, Package, Wheel, setup.py, and sharing on PyPi.