How to import things
Imports can be confusing in Python, especially when you have a mixture of modules and packages. If in doubt, use the autocompleter to help you get it right!
Just type “from .”, then see the suggestions.
Importing from the same Package
Imagine you have a Package with two Modules inside it:
This is how you import the Modules from the Package:
# In MyPackage
from . import Foo
from . import BarThis is how you import the Modules from each other:
# In the Module named Bar
from . import FooImporting variables from the Package is similar:
# In the Module named Bar,
# To import a variable from MyPackage
from . import my_variableTo import the Package itself, you must use an extra dot:
# In the Module named Bar
from .. import MyPackageImporting from a nested Package
Imagine you have a Package containing a Module and a Package, which in turn contains a Module:
This is how you import the Module that’s in the child Package:
# In Foo.py
from .MyChildPackage import Bar
# or, to import a variable from inside the Module:
from .MyChildPackage.Bar import my_functionThis is how you import the Module that’s in the parent Package:
# In Bar.py
from .. import Foo
# or, to import a variable from inside the Module:
from ..Foo import my_functionIf you move a Form, Module or Package, be sure to rewrite its imports and the imports of things that refer to it - the all-app search function can help you here.
Importing Forms
You will often see Forms imported like this:
# From the Package called Form1, import the class called Form1
from ..Form1 import Form1This works because of the way Forms are represented in code: Form1 is a Package named Form1 that contains a class
named Form1. You can use this to create instances of the Form:
from ..Form1 import Form1
my_form_instance = Form1()
alert(my_form_instance)You should not use this approach when importing Modules:
# This is not the correct way to import a Module
from ..Module1 import Module1This will cause an ImportError (unless Module1 happens to contain a variable named Module1).
This is how to import a Module:
from .. import Module1Do you still have questions?
Our Community Forum is full of helpful information and Anvil experts.