Often when I see class definitions class Foo:
, I always see them start with upper case letters.
However, isn't a list []
or a dict {}
or some other built-in type, a class as well? For that matter, everything typed into the Python's IDLE which is a keyword that is automatically color coded in purple (with the Window's binary distribution), is itself a class, right?
Such as spam = list()
spam
is now an instance of a list()
So my question is, why does Python allow us to first of all do something like list = list()
when nobody, probably, does that. But also, why is it not list = List()
Did the developers of the language decide not to use any sort of convention, while it is the case that most Python programmers do name their classes as such?
I think that the only person who really knows the entire answer to your question is the BDFL. Convention outside of the types implemented in C is definitely to use upper-case (as detailed in PEP8). However, it's interesting to note that not all C-level types follow the convention (i.e.
Py_True
,Py_False
) do not. Yes, they're constants at Python-level, but they're allPyTypeObject
s. I'd be curious to know if that's the only distinction and, hence, the difference in convention.PEP8 is the place to go for code style.
To address your question on why
list = list()
is valid,list
is simply a name in the global namespace, and can be overriden like any other variable.All are in the end design decisions.
https://www.python.org/dev/peps/pep-0020/ says (try also
>>> import this
)And this would be a special case.
https://www.python.org/dev/peps/pep-0008/#class-names says:
All other classes should use the CapWorlds convention. As
list
,object
, etc are built-in names, they follow this separate convention.According to PEP 8, a nice set of guidelines for Python developers:
PEP 8 is directed at Python development for the standard library in the main Python distribution, but they're sensible guidelines to follow.
Yes, uppercase-initial classes are the convention, as outlined in PEP 8.
You are correct that many builtin types do not follow this convention. These are holdovers from earlier stages of Python when there was a much bigger difference between user-defined classes and builtin types. However, it still seems that builtin or extension types written in C are more likely to have lowercase names (e.g.,
numpy.array
, notnumpy.Array
).Nonetheless, the convention is to use uppercase-initial for your own classes in Python code.