homepage - wintellect - write pythonic code...wintellect core services consulting custom software...
TRANSCRIPT
Michael KennedyHost, Talk Python To Me podcast
Write Pythonic CodeThrough 5 Examples
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
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
Topics
Python lightning refresher Tuple assignment and unpacking Dictionaries for performance Generators Leverage inline methods with lambda expressions __slots__
Who decides what is Pythonic?
The community
Who decides what is Pythonic?
Python core developers + Tim Peters
Who decides what is Pythonic?
PEP 8 Style Guide
Python is a good career bet
Python is a good career bet
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.
Who am I anyway?
Michael Kennedy@mkennedy
talkpython.fm pythonbytes.fm
#0: Lightning refresher
#1 Tuple assignment and unpacking
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))
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.
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
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
#2: Dictionaries for performance
#3: Leverage inline methods with lambda expressions
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.
#4: Generators
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
Generators (that’s a generator)
def fibonacci_generator():current, nxt = 0, 1while True:
current, nxt = nxt, nxt + currentyield current
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
)
#5: Hacking Python’s memory with __slots__
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.
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.
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)