You've defined a couple of yummy ingredients in your ingredients.py module:
# ingredients.py
def prepare(ingredient):
return f"cooked {ingredient}"
carrot = "carrot"
salt = "salt"
potato = "potato"
print(prepare(potato))
Because you spent some time writing your code and you were also checking its functionality, you kept a print() at the bottom of your file:
print(prepare(potato))
So far, that all seems fine, and if you execute ingredients.py, it all seems to work normally.
Side Effects From Importing
You head over to soup.py and import just your carrot once again:
# soup.py
from ingredients import carrot
However, now you're getting some unexpected output in your console:
# OUTPUT:
cooked potato
Huh?! Where did the potato come from, and why is it already cooked? You've explicitly imported only the carrot so far. Does that mean you can access the potato variable in soup.py:
# soup.py
from ingredients import carrot
print(carrot)
print(potato)
The output of running this doesn't make the mystery less mysterious:
# OUTPUT:
cooked potato
carrot
Traceback (most recent call last):
File "/Users/martin/codingnomads/cook.py", line 9, in <module>
print(potato)
NameError: name 'potato' is not defined
Your CLI clearly prints the cooked potato, but Python doesn't know anything about the potato variable and throws its digital hands in the air with a sigh of NameError. What's going on here?
Info: When you import code from a module, you execute the whole script. If there's any code execution written in the script, it'll run and potentially produce some unexpected output.
Python runs the call to your print() function inside of ingredients.py when you're importing even just the carrot variable in a different script. But that's not what you want! You just want access to the carrot, and leave the potato uncooked and in storage over in ingredients.py.
In a future lesson, you'll learn how you can avoid running into this.
Summary: Python, Error Handling
- When you import code from a module, Python executes the whole script. Any leftover function calls will also execute, and they might produce unexpected results.