Dup Ver Goto 📝

6 Clean Tips to Improve Your Python Functions

To
37 lines, 164 words, 991 chars Page '6_Clean_Tips_to_Improve_Python_Functions' does not exist.

Source: this Indently video.

1 Function return type

def func() -> int:
    return 1

2 Function arg types

def func(x: int) -> int
    return x + 1

def func(numbers: list[int]) -> list[int]
    numbers.<tab> # will autocomplete to list methods
    return numbers

3 star args

def sum_numbers(*numbers: float) -> float:
    # numbers is a tuple(float)
    return sum(numbers)

4 Keep code simple

5 Documentation

def f():
    "Explain what f does and how to use it"

6 Avoid globals

Sometimes globals are useful, but are messy as soon as you want to reuse code. If code needs state to persist between function calls, factor things into a class. One exception I have is a should_quit variable that other threads can pay attention to, as a means to tell an arbitrary group of threads that they should quit at the earliest opportunity.