Take a look at the documentation:
Enter the Python interpreter and import this module with the following command:
import fibo
This does not enter the names of the functions defined in fibo
directly in the current symbol table; it only enters the module name fibo
there.
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname
.
This may seem very complicated, but what it says is basically, when you import a module, all of its contents remain in a separate namespace in order to prevent collisions (i.e. two variables in two modules with the exact same name).
Lets take your example. For your code to work you have two options.
Option A
Explicitly tell python that the variable you're looking for is defined in the constants
module.
import constants
def hello_world():
print(constants.BUCKET_NAME)
Option B
Again, from the documentation:
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table.
This variant is the following:
from module import x
What this does is it imports everything one by one from the constants
module. From then on, python treats that data as if it was defined in your current module.
Using this approach, you can do the following:
from constants import *
def hello_world():
print(BUCKET_NAME)
The *
here tells python to import everything from that module. This is convenient in a lot of cases, however be advised, this may cause performance issues when dealing with large modules. Also, keep in mind:
This does not introduce the module name from which the imports are taken in the local symbol table
What this means is that if you opt to only import BUCKET_NAME
from constants (from constants import BUCKET_NAME
instead of import *
), constants
won't be defined. You will not be able to access other variables defined in that module without also writing import constants
.
For a more detailed explanation regarding the performance of the latter approach, take a look at this excellent post by Roberto Liffredo, as well as this by resident python master Martijn Pieters.