28
Michael Kennedy Host, Talk Python To Me podcast Write Pythonic Code Through 5 Examples

Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Michael KennedyHost, Talk Python To Me podcast

Write Pythonic CodeThrough 5 Examples

Page 2: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Wintellect Core Services

ConsultingCustom software application development and architecture

Instructor Led TrainingMicrosoft’s #1 training vendor for over 14 years having trained more than 50,000 Microsoft developers

On-Demand TrainingWorld class, subscription based online training

Page 3: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

FAQ Can I get the code from this webcast?

Yes: https://github.com/Wintellect/WintellectWebinars

Can I get the slides?

Yes: https://github.com/Wintellect/WintellectWebinars

Will the webinar be recorded?

Yes

Where do I go to get more afterwards?

https://www.wintellect.com/software-development-training/courses/write-pythonic-code-like-a-seasoned-developer-workshop

https://www.wintellect.com/software-development-training/courses/python-jumpstart-by-building-10-apps-workshop

Page 4: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Topics

Python lightning refresher Tuple assignment and unpacking Dictionaries for performance Generators Leverage inline methods with lambda expressions __slots__

Page 5: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Who decides what is Pythonic?

The community

Page 6: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Who decides what is Pythonic?

Python core developers + Tim Peters

Page 7: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Who decides what is Pythonic?

PEP 8 Style Guide

Page 8: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Python is a good career bet

Page 9: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Python is a good career bet

Page 10: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Python is a good career bet

Python shot to the most wanted language this year (as in, the language developers want to use the language this year more than any other), after ranking fourth last year.

Page 11: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Who am I anyway?

Michael Kennedy@mkennedy

talkpython.fm pythonbytes.fm

Page 12: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#0: Lightning refresher

Page 13: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#1 Tuple assignment and unpacking

Page 14: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Tuple assignment and unpacking

t = ("Hello", 1, 3, " a tuple") # t is a tuple

# we can assign individual variables via unpacking:greeting, n1, n2, closing = t

print("Greeting={}, n1={}, n2={}, closing='{}'".format(greeting, n1, n2, closing

))# prints: Greeting=Hello, n1=1, n2=3, closing=' a tuple'

# You'll find this often in loops:for idx, val in enumerate(['a', 'b', 'c']):

print("Value {} found at index {}".format(val, idx))

Page 15: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Tuples for swapping values

x = 7y = 11

print("x={}, y={}".format(x, y))# prints: x=7, y=11

# swapy, x = x, y # creates tuple (x,y) and unpacks to y, x

print("x={}, y={}".format(x, y))# prints: x=11, y=7

Creates the tuple (x, y) and unpacks into y and x.

Page 16: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Multiple return values from a function

# There are no ref parameters but you could stash them elsewheredef out_params_bad(base: float, args: list):

if len(args) == 0:args.append(0)args.append(0)

if len(args) != 2:raise Exception("Need to return values")

args[0] = base * baseargs[1] = math.sqrt(base * base * base)

args_list = list()out_params_bad(7, args_list)

print("Return values (bad): {} & {:.2f}".format(args_list[0], args_list[1]))# prints: Return values (bad): 49 & 18.52

Page 17: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Multiple return values from a function

# Tuple unpacking works brilliantlydef compute_values(base):

b2 = base * baseb32 = math.sqrt(base * base * base)

return b2, b32

b2, b32 = compute_values(8)

print("Return values (good): {} & {:.2f}".format(b2, b32)) # prints: Return values (good): 64 & 22.63

Page 18: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#2: Dictionaries for performance

Page 19: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#3: Leverage inline methods with lambda expressions

Page 20: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Leverage inline methods with lambda expressions

def find_special_numbers(special_selector, limit=10):found = []n = 0while len(found) < limit:

if special_selector(n):found.append(n)

n += 1return found

find_special_numbers(lambda x: x % 6 == 0)

Lambda expressions are small, inline methods.

Page 21: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#4: Generators

Page 22: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Generators (not a generator)

def classic_fibonacci(limit):nums = []current, nxt = 0, 1

while current < limit:current, nxt = nxt, nxt + currentnums.append(current)

return nums

Page 23: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Generators (that’s a generator)

def fibonacci_generator():current, nxt = 0, 1while True:

current, nxt = nxt, nxt + currentyield current

Page 24: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Inline generators via expressions

# direct loop stylehigh_measurements = []for m in measurements:

if m.value >= 70:high_measurements.append(m.value)

# generator stylehigh_measurements = (

m.valuefor m in measurementsif m.value >= 70

)

Page 25: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

#5: Hacking Python’s memory with __slots__

Page 26: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Hacking Python’s memory with __slots__

Saving 9 GB of RAM with Python’s __slots__http://tech.oyster.com/save-ram-with-python-slots/

Special cases aren't special enough to break the rules.Although practicality beats purity.

Page 27: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Hacking Python’s memory with __slots__

class ImmutableThing:__slots__ = ['a', 'b', 'c']

def __init__(self, a, b, c):self.a = aself.b = bself.c = c

Defining __slots__ restricts values allowed in type but removes per instance dictionarybacking store.

Page 28: Homepage - Wintellect - Write Pythonic Code...Wintellect Core Services Consulting Custom software application development and architecture Instructor Led Training Microsoft’s #1

Thanks, now what?

Thank you for coming! Up next: Q&A

Afterwards: Get the recording Consider the live courses Python Jumpstart by Building 10 Apps (Live workshop edition) Write Pythonic Code Like a Seasoned Developer (Live workshop edition)