Thursday, July 19, 2012

PyFlakes-clean import of local_settings.py

Any project have own bunch of settings for different environments: for dev, production, staging. Everyone use it on daily basis. But annoying thing is that PyFlakes, great code analysis tool, warn about that. And it's reasonable.

So, to have this functionality, but without warning I use this pattern:

try:
    import local_settings
    for setting in dir(local_settings):
        if setting.startswith('_'):
            continue
        locals()[setting] = getattr(local_settings, setting)
except ImportError:
    pass

Simple and useful!


Update: I've added ignore of attributes which starting with underscore. Thanks to Igor Davydenko

2 comments:

  1. hm, i think it's not right to copy all vars from local_settings, this will rewrite __name__, __file__ and other private vars of current settings

    for setting in dir(local_settings):
    if setting.startswith('_'):
    continue
    locals()[setting] = getattr(local_settings, setting)

    ReplyDelete