Descriptor Naming Convention

I have a handle

class ReferredItem(): def __init__(self, method): self.method = method def __get__(self, obj, objtype): ... 

I use it as a decorator:

 class MyClass(): @ReferredItem some_method(self): ... 

I saw that the decorators are lowercase. But classes should be called in the case of a camel.

Should I name a class like referred_item ? Or leave it as it is now?

+7
source share
4 answers

PEP8 claims that

Almost without exception, class names use the CapWords convention.

without explaining what exceptions are, but in the standard library the classes that are most often used as functions usually follow the function naming convention. For example. itertools.groupby is actually a class, but you do not notice this in normal use; this is a drillthrough implementation and groupby can be rewritten as a valid function.

You can use a similar style using the lower case naming convention for classes used as decorators: referred_item , not ReferredItem .

+9
source

Although any callable object can be used as a decorator, they are usually considered functions, and objects like functions should follow the lowercase_with_underscores convention.

You must hide the fact that your decorator is a class, as it is an implementation detail. Therefore, the decorator must follow the style of "lowercase_with_underscores". Thus, you do not need to change the user code if someday you decide to implement the decorator as a function.

Personally, I will still use CapWords for the (internal) decorator class name and provide an alias variable that should be used for the decorator:

 class _ReferredItem: def __init__(self, method): self.method = method def __get__(self, obj, objtype): # ... referred_item = _ReferredItem 
+4
source

PEP8 is not particularly clear on this issue ... But unofficially, I found a good rule: if the class will be used as a function (for example, as a decorator, but also such things as context managers), this should have lowercase names, such as functions. This is apparently an agreement followed by a standard library.

So I would rather look at referred_item than ReferredItem .

+1
source

I usually use CamelCase for a class, and then add an alias that I use as a decorator.

 referred_item = ReferredItem 
0
source

All Articles