Если видео недоступно для просмотра, попробуйте выключить блокировщик рекламы.

###Functions in Python

Common structure

def name(arg1, ... argN, kwarg1, ... kwargN, *args, **kwargs):
    """Short description
       Long description...
    """
....operator1
....operatorN
....return value

Naming rules

  • lower_underscore_case
  • letters, numbers, underscores
  • leading underscore for private funcs
myFunc()          # bad
My_func           # bad
100_top_users     # SyntaxError
get_top_users()   # ok
_fetch_data()     # perhaps you shouldn't call that directly

Why need docstring

  • Keep code and docs at the same place
  • Useful for IDEs, editors
  • Build documentation from code
  • help(func) or func.doc prints the doc
  • Doctests
def test(a, b, c=3, d=4)

test()                   TypeError
test(1, 2)               a=1, b=2, c=3, d=4
test(4, 10, c=22)        a=4, b=10, c=22, d=4
test(a=6, b=5)           a=6, b=5, c=3, d=4
test(d=4, a=1)           TypeError
test(c=1, b=4, a=5)      a=5, b=4, c=1, d=4
test(9, 8, 7)            a=9, b=8, c=7, d=4
test(9, 8, 7, 6)         a=9, b=8, c=7, d=6

What does function return

- Use return <value> statement
- There might be several return statements
- None if there is no return statement
- Use tuple to return multiple values

def func(foo, bar, baz=42):
    if baz == 42:
        return (False, "some-error")
    else:
        return (True, "OK")

ok, message = func(1, 2)            False, "some-error"
ok, message = func(1, 2, baz=3)     True, "OK"

Function is object

- Copy, delete function
- Pass it into a function call
- Might be either a key or value of a dict
- Has special attrs (__name__, __module__, etc)

def user_auth(user):
    pass

def user_logout(user)
    pass

actions = {"auth": user_auth, "logout": user_logout}

actions[action](user)

args, kwargs

  • def (*args, **kwargs)
  • aggregate rest arguments and keyword arguments
  • args is a tuple, kwargs is a dict
  • useful when you construct arguments step by step
params = {"name": "Ivan", "age": 29}
if ...
    params["created_at"] = datetime.now()
if ...
    params["friends"] = ["Joe", "Mary"]

create_user(**params)
create_user(name="Ivan", age=29,
                    created_at=datetime.now(),
                    friends=["Joe", "Mary"]
)

Never use mutable defaults!

def test(a=[]):
    a.append(1)
    print a

test()     [1]
test()     [1, 1]
test()     [1, 1, 1]
test()     [1, 1, 1, 1]

Lambdas

  • Came from functional programming
  • A short expression with only one statement inside
  • Pros:
  1. just-in-place function
  2. supports argument unpacking
  • Cons:
  1. long ones are ugly
  2. hard to debug
double = lambda x: 2 * x
map(double, [1, 2, 3])                  [2, 4, 6]

calc = lambda (x, y, x): x * y - z
map(calc, [(1, 2, 3), (4, 5, 6)])       [-1, 14]

avg = lambda *args: sum(args) / float(len(args))
avg(1, 2, 3)                            2.0

lambda x: pass                          SyntaxError
Мы учим программированию с нуля до стажировки и работы. Попробуйте наш бесплатный курс «Введение в программирование» или полные программы обучения по Node, PHP, Python и Java.

Хекслет

Подробнее о том, почему наше обучение работает →