[chirp_devel] Naming convention for class fields?
Craig Jones
Tue May 16 16:43:52 PDT 2023
(Going off on a tangent here. Just FYI, folks.)
Actually, __foo__ and __foo are two different things, according to PEP8.
The former standard (with the trailing __; which is nicknamed "dunder")
is indeed as you describe, and developers are not supposed to create
their own dunders. The latter (with only leading __) invokes something
called "mangling" where the name of the class is prefixed to the
variable name as it's compiled. This effectively makes it a private
field by disambiguating the variables within the same namespace. So, in
this one case, the leading __ making it "private" isn't just a style
convention, but actually enforced by Python (somewhat).
I honestly didn't remember this mangling stuff from when I read through
PEP8, previously (2 years ago?), and I can't imagine actually using it
(which undoubtedly why I forgot about it). Maybe it ought to be stricken
from PEP8, just to reduce the complexity? Not enough bang for the buck
on this one, IMHO.
On 5/15/2023 5:42 PM, Stuart Longland VK4MSL via chirp_devel wrote:
> On 16/5/23 10:32, Craig Jones via chirp_devel wrote:
>> FYI: I stand corrected. I reread PEP8. One leading underscore is meant
>> to say protected, not private. Thus, it is part of the subclass API.
>> It's double leading underscores that means completely private.
> Double leading underscore normally refers to things that are special to
> Python. Things like `__len__` (implements `len()`), `__repr__`, etc
> which implement various operators.
>
> Or deeply internal things like `__slots__` which is used to define what
> attributes a class instance has so it can be "set in stone" as a
> `struct` rather than using a `dict` implementation which consumes more
> memory.
>
> In general:
>
> - leading underscore → private/protected (not enforced)
> - UPPER_CASE_WITH_UNDERSCORES → constant
>
> `_model` as a class attribute suggests the attribute might sometimes
> change to reference something else, but it is otherwise
> private/protected. `_MODEL` might be better if we know it won't change
> -- but the interpreter does not care; such designations are just for us
> meat bags to better understand what's going on.
--
This email has been checked for viruses by AVG antivirus software.
www.avg.com
More information about the chirp_devel
mailing list