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 {
All are in the end design decisions.
[...] why does python allow us to first of all do something like
list = list()
https://www.python.org/dev/peps/pep-0020/ says (try also >>> import this
)
And this would be a special case.
[...] why is it not
list = List()
https://www.python.org/dev/peps/pep-0008/#class-names says:
Class Names
Class names should normally use the CapWords convention.
The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.
Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants. [emphasis mine]
All other classes should use the CapWorlds convention. As list
, object
, etc are built-in names, they follow this separate 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.
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 all PyTypeObject
s. I'd be curious to know if that's the only distinction and, hence, the difference in convention.
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
, not numpy.Array
).
Nonetheless, the convention is to use uppercase-initial for your own classes in Python code.
According to PEP 8, a nice set of guidelines for Python developers:
Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.
PEP 8 is directed at Python development for the standard library in the main Python distribution, but they're sensible guidelines to follow.