I'm importing some constants from my file constants.py like this:
from constants import (SOME_CONST, OTHER_CONST, ANOTHER_ONE)
This constants are filenames and I'm reading data out of them, what I want to achieve is this:
for filename in [SOME_CONST, OTHER_CONST, ANOTHER_ONE]:
# process file
constants.py
SOME_CONST = "filename.txt"
OTHER_CONST = "myfile.xml"
ANOTHER_ONE = "file.csv"
But I want to know if there is a way to avoid declaring the list in the for, like traverse or build a list of imported constants, because there can be many constants not just 3 like the example and it is error prone, since I would need to import the constant and add it to the list, I just want to import it and work with whatever is imported.
You cannot list 'all imported constants', no. They are just more globals in your current module.
Your options are to:
list all names on the constants module:
import constants
for name in dir(constants):
const = getattr(constants, name)
You can filter those names if they follow a pattern:
for name in dir(constants):
if name.startswith('FOO_'):
The filter can be a simple as checking that the name is all uppercase.
declare the list as part of your constants module, and import that instead.
declare a list of names in your current module, and use that to 'import' your constants:
import constants
const_names = ['SOME_CONST', 'OTHER_CONST', 'ANOTHER_ONE']
for const_name in const_names:
const = getattr(constants, const_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With