Python style: lowercase names for "namespaces"?

I know the PEP-8 convention for ClassName class ClassName . But we often use small classes as pseudo-spaces, enumerations, etc. In other words, this is not a real class that you are going to create. We have chosen a lowercase naming convention for such "classes" because they really are namespace / enumeration names.

Does anyone have other styles for this or other ways to achieve the same thing?

Example:

 import urllib2 class config: # pseudo-namespace for module-level config variables api_url = 'http://example.com/api' timeout = 1.5 debug = True class countries: # pseudo-enum new_zealand = 1 united_states = 2 def func(): if config.debug: print 'Calling func()' return urllib2.urlopen(config.api_url) 
+6
python coding-style
source share
4 answers

For all enumerations and constants, I prefer to use capitalized versions.

 class COUNTRIES: # pseudo-enum NEW_ZEALAND = 1 UNITED_STATES = 2 

I'm still fine if the class name is not all capitalized. Since it is associated with enumeration values. I will always use it as Countries.NEW_ZEALAND , which tells me this listing.

 class COUNTRIES: # pseudo-enum NEW_ZEALAND = 1 UNITED_STATES = 2 
+5
source share

You can also create a module called config with the following contents:

 api_url = 'http://example.com/api' timeout = 1.5 debug = True 
+4
source share

Instead, I use dictionaries:

 config = dict( api_url = 'http://example.com/api', timeout = 1.5, debug = True) countries = dict( new_zealand = 1, united_states = 2) 

If you find attribute access cumbersome in a Python dict , try attrdict :

 class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self 

It allows you to access dictionary entries with keys that are valid identifiers as attributes, for example. config.api_url instead of config["api_url"] .

Of course, I use lowercase names for them.

+2
source share

Why not

 class PseudoNamespace: pass config = PseudoNamespace() config.api_url = 'http://example.com/api' config.timeout = 1.5 config.debug = True countries = PseudoNamespace() config.new_zealand = 1 config.united_states = 2 

if you really care about pep?

+1
source share

All Articles