Home > database >  Python: Pythonic way to import all variables with a specific identifier?
Python: Pythonic way to import all variables with a specific identifier?

Time:01-03

I want to neatly import all variables in a file that have '_COLUMN' in their name. I do this because there are 20 variables and the normal import statement would be huge. I also want the variables to be directly accessible e.g. TIME_COLUMN and not earthquakes.tools.TIME_COLUMN

The following code works:

import earthquakes.tools    
for item in dir(earthquakes.tools):
    if '_COLUMN' in item:
        exec(f'from earthquakes.tools import {item}')

Is this considered Pythonic ? If not, is there a better way or should this not even be done ?

For information, I have tried searching for regex in import statements and other solutions but did not find anything significant.

Please do not mention from ... import * as it is not considered Pythonic

CodePudding user response:

All the _COLUMN-prefixed variables should probably be a dict in the first place, but if you can't do that in earthquake.tools yourself, you can build a local one using getattr.

import earthquake.tools


column_names = ["foo", "bar", "baz", ...]

columns = {k: getattr(earthquake.tools, f'{k}_COLUMN') for k in column_names}

Don't use dir to "infer" the columns names. No one reading the scipt will know what variables are defined without knowing what earthquake.tools defines in the first place, so be explicit and list the names you expect to be using. (There is no point creating a variable you will never actually use.)

CodePudding user response:

you can use this trick

from earthquakes.tools import *

CodePudding user response:

You can override the __all__ variable of the module:

tools.py

__all__ == ['var1_COLUMN', 'var2_COLUMN', 'var3_COLUMN']

main.py:

from earthquakes.tools import *

To know more: Importing * From a Package

  • Related