Chuyển tới nội dung chính

Python Style Guide References

Peak examples

Naming from Guido's Recommendations
TypePublicInternal
Packageslower_with_under
Moduleslower_with_under_lower_with_under
ClassesCapWords_CapWords
ExceptionsCapWords
Functionslower_with_under()_lower_with_under()
Global/Class ConstantsCAPS_WITH_UNDER_CAPS_WITH_UNDER
Global/Class Variableslower_with_under_lower_with_under
Instance Variableslower_with_under_lower_with_under (protected)
Method Nameslower_with_under()_lower_with_under() (protected)
Function/Method Parameterslower_with_under
Local Variableslower_with_under
Parentheses
Yes: if foo:
       bar()
   while x:
       x = bar()
   if x and y:
       bar()
   if not x:
       bar()
   # For a 1 item tuple the ()s are more visually obvious than the comma.
   onesie = (foo,)
   return foo
   return spam, beans
   return (spam, beans)
   for (x, y) in dict.items(): ...

No:  if (x):
       bar()
   if not(x):
       bar()
   return (foo)
  
from collections.abc import Callable
from typing import ParamSpec, TypeVar
_P = ParamSpec("_P")
_T = TypeVar("_T")
...
def next(l: list[_T]) -> _T:
return l.pop()

def print_when_called(f: Callable[_P, _T]) -> Callable[_P, _T]:
def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:
print("Function was called")
return f(*args, **kwargs)
return inner