What is the naming convention for a variable referencing a class in Python?
class MyClass(object):
pass
# which one is correct?
reference_to_class = MyClass
# or
ReferenceToClass = MyClass
Here is another example that resembles my situation:
# cars.py
class Car(object):
pass
class Sedan(Car):
pass
class Coupe(Car):
pass
class StatonWagon(Car):
pass
class Van(Car):
pass
def get_car_class(slug, config):
return config.get(slug)
# config.py
CONFIG = {
'ford-mustang': Coupe,
'buick-riviera': Coupe,
'chevrolet-caprice': Sedan,
'chevy-wan' Van:
'ford-econoline': Van
}
# main.py
from config.py import CONFIG
from cars import get_car_class
MyCarClass = get_car_class('buick-riviera')
my_car = MyCarClass()
I would prefer ReferenceToClass, that everybody new to the code knows it's a class and not an instance. But as @poplitea wrote, literature reference would be great.
On module level the second:
ReferenceToClass = MyClass
As a function argument, the first:
reference_to_class = MyClass
tl;dr: for global/public names use
AllCaps
like XORcist said:For function parameters and function locals, make it clear that you are dealing with the class object with a descriptive name like this:
or something along the lines
when the word
"class"
is actually in your classname. Forclassobj
, see alsoclass_
andklass
.Analysis/Motivation (long version)
No thorough reading, but at a glance PEP 8 doesn't seem to be explicit on this (neither google's python style guide for that matter).
Since a variable name is probably just yet-another name binding in python, in my opinion it doesn't really matter whether you bind that name with the definition block or later with the
=
equal sign to some object.For this I agree with XORcist in that module level "alias" references should adhere to your class naming standard, probably AllCaps:
However when it comes to parameter and variable names, supposedly
lowercase_underscores
should apply, right? I'm unhappy with only that, since it will push you into the instance vs class reference ambiguity. There is the potential that an all-lowercase name may be an attempt to hint the object being an instance. For that matter, I recommend postfixing your all-lowercase, class-referencing variable names with the "class" suffix, like this:I renamed your example class
MyClass
toLogger
because in real scenarios only a few class name contains the string"class"
. However in that latter case I propose to avoid the ambiguity with descriptive naming yet again. For example, you may use aclassobj
suffix:Another alternative I tend to take is to use the suffix
klass
, likemy_class_klass
. Not everyone seems to get the latter, but anyway I'm yet to test whether they would get the former any better.I treat it the same as an instance variable, which PEP8 defines as using lowercase_underscore_style. (lowercase, with words separated by underscores as necessary to improve readability.)
http://www.python.org/dev/peps/pep-0008/#id34