Slide 1

Slide 1 text

gotchas

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

Erick Mendonça, Software Engineer, eShares

Slide 4

Slide 4 text

mutable default values

Slide 5

Slide 5 text

def append_to(element, to=[]): to.append(element) return to Source: http://docs.python-guide.org/en/latest/writing/gotchas/

Slide 6

Slide 6 text

my_list = append_to(12) print(my_list)

Slide 7

Slide 7 text

my_list = append_to(42) print(my_list)

Slide 8

Slide 8 text

print(my_list) [12, 42]

Slide 9

Slide 9 text

mutable function arguments

Slide 10

Slide 10 text

def print_sorted(sequence): sequence.sort() print(sequence) my_list = [2, 1, 5, 3] print_sorted(my_list) print(my_list)

Slide 11

Slide 11 text

loop updating lists or dicts

Slide 12

Slide 12 text

def wrong_loop(): a = list(range(10)) for i in a: a[i+1] = 1 print(a) wrong_loop()

Slide 13

Slide 13 text

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 1, 3, 4, 5, 6, 7, 8, 9] [0, 1, 1, 3, 4, 5, 6, 7, 8, 9] [0, 1, 1, 3, 1, 5, 6, 7, 8, 9] [0, 1, 1, 3, 1, 5, 6, 7, 8, 9] [0, 1, 1, 3, 1, 5, 1, 7, 8, 9] [0, 1, 1, 3, 1, 5, 1, 7, 8, 9] [0, 1, 1, 3, 1, 5, 1, 7, 1, 9] [0, 1, 1, 3, 1, 5, 1, 7, 1, 9] Traceback (most recent call last): File "", line 1, in File "", line 4, in wrong_loop IndexError: list assignment index out of range

Slide 14

Slide 14 text

def wrong_loop_2(): a = list(range(10)) for i in a: if i % 2: a.append(i) print(len(a)) wrong_loop_2()

Slide 15

Slide 15 text

Slide 16

Slide 16 text

late binding lambdas

Slide 17

Slide 17 text

def create_multipliers(): return [ lambda x : i * x for i in range(5) ] for multiplier in create_multipliers(): print multiplier(2) Source: http://docs.python-guide.org/en/latest/writing/gotchas/

Slide 18

Slide 18 text

scope

Slide 19

Slide 19 text

msg = "Python Rio <3" def print_msg(): print(msg)

Slide 20

Slide 20 text

msg = "Python Rio <3" def print_msg(): print(msg) msg = "and that's awesome!" print(msg)

Slide 21

Slide 21 text

UnboundLocalError: local variable 'msg' referenced before assignment

Slide 22

Slide 22 text

hash()

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

data = { 'full_name': 'Bruce Banner', 'birth_date': '1962-05-01', # a lot of other data } cache_id = hash(data['full_name']) | hash(data['birth_date']) cache.set(cache_id, data)

Slide 25

Slide 25 text

app-01$ >>> hash('PythonRio') 90314343757402039 app-02$ >>> hash('PythonRio') 5622018667917605056

Slide 26

Slide 26 text

Thank you! /@erickmagnus