Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic ways of traversing imported constants

Tags:

python

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.

like image 904
PepperoniPizza Avatar asked Jun 11 '26 01:06

PepperoniPizza


1 Answers

You cannot list 'all imported constants', no. They are just more globals in your current module.

Your options are to:

  1. 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.

  2. declare the list as part of your constants module, and import that instead.

  3. 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)
    
like image 85
Martijn Pieters Avatar answered Jun 12 '26 15:06

Martijn Pieters