Reputation: 11044
I know the PEP-8 convention for class names is ClassName
. But we often use small classes as pseudo-namespaces, enums etc. In other words, not a real class that you're going to instantiate. We've opted for a lowercase naming convention for such "classes", because they're really a namespace/enum name.
Does anyone else have in-house styles for this, or other ways of achieving the same thing?
An 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)
Upvotes: 6
Views: 2070
Reputation: 20910
You can also create a module named config
with the following content:
api_url = 'http://example.com/api'
timeout = 1.5
debug = True
Upvotes: 4
Reputation: 602035
I use dictionaries instead:
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 an attrdict
:
class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
It allows to access dictionary entries with keys that are valid identifiers as attributes, e.g. config.api_url
instead of config["api_url"]
.
Of course I use lower-case names for these.
Upvotes: 1
Reputation: 176850
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 the PEP?
Upvotes: 1
Reputation: 66729
For all enums and constants, I prefer to use capitalized versions.
class COUNTRIES: # pseudo-enum
NEW_ZEALAND = 1
UNITED_STATES = 2
It is still ok with me, if the class name is not all capitalized. Since, any way it is tied up with the enum values. I am always going to use it like Countries.NEW_ZEALAND
, which tells me that it is an enum.
class Countries: # pseudo-enum
NEW_ZEALAND = 1
UNITED_STATES = 2
Upvotes: 5