Just Modules
Modules we would like to import
colours.py
def rainbow():
return "red orange yellow green blue indigo violet".split()
def dull():
return "beige brown taupe".split()
messages.py
def message_one():
return "I came from one"
def message_two():
return "A bird in the hand is worth two in the bush (apparently)"
Our main program
main.py
import colours
import messages
print(colours.dull())
print(messages.message_two())
print(colours.rainbow())
and this runs fine:
python main.py
['beige', 'brown', 'taupe']
A bird in the hand is worth two in the bush (apparently)
['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
Can we import individual functions?
yep, that's fine:
What about importing *?
This does work but it's not recommended. (Ruff complains about it in VsCode)
yep, that's fine:
What about relative imports
This doesn't appear to work:
python main.py
Traceback (most recent call last):
File "C:\Users\Craig\python_projects\import_test\ex01_just_modules\main.py", line 1, in <module>
from . import colours
ImportError: attempted relative import with no known parent package
and similarly, the following is not valid:
python main.py
Traceback (most recent call last):
File "C:\Users\Craig\python_projects\import_test\ex01_just_modules\main.py", line 1, in <module>
from .colours import dull
ImportError: attempted relative import with no known parent package
You can actually import this way, but it involves a discussion about packages. See packages