10 Tips for Writing Pythonic Code by Michael KennedyMichael Kennedy
?
Watch: https://youtu.be/_O23jIXsshs
Course: https://talkpython.fm/pythonic
One of the special concepts in Python is the idea of writing idiomatic code that is most aligned with the language features and ideals. In Python, we call this idiomatic code Pythonic. While this idea is easy to understand, it turns out to be fairly hard to make concrete.
In this webcast, Michael Kennedy from the Talk Python To Me podcast will take you on a tour of 10 of the more popular and useful code examples demonstrating examples of Pythonic code. In the examples, you'll first see non-Pythonic code and then the more natural Pythonic version.
Topics covered include the expansive use of dictionaries, hacking Python's memory usage via slots, using generators, comprehensions, and generator expressions, creating subsets of collections via slices (all the way to the database) and more. Several of these are Python 3 features so you'll have even more reason to adopt Python 3 for your next project.
This document discusses Django, a Python web framework. It provides an overview of Django's features like MVT architecture, DRY principles, and Unix philosophy. It also describes starting a Django project, using the admin interface, generic views, templates, tags, filters, pagination, middleware, authentication, caching, internationalization and various Django tools. The document aims to introduce Django and its capabilities for building web applications and sites.
10 Tips for Writing Pythonic Code by Michael KennedyMichael Kennedy
?
Watch: https://youtu.be/_O23jIXsshs
Course: https://talkpython.fm/pythonic
One of the special concepts in Python is the idea of writing idiomatic code that is most aligned with the language features and ideals. In Python, we call this idiomatic code Pythonic. While this idea is easy to understand, it turns out to be fairly hard to make concrete.
In this webcast, Michael Kennedy from the Talk Python To Me podcast will take you on a tour of 10 of the more popular and useful code examples demonstrating examples of Pythonic code. In the examples, you'll first see non-Pythonic code and then the more natural Pythonic version.
Topics covered include the expansive use of dictionaries, hacking Python's memory usage via slots, using generators, comprehensions, and generator expressions, creating subsets of collections via slices (all the way to the database) and more. Several of these are Python 3 features so you'll have even more reason to adopt Python 3 for your next project.
This document discusses Django, a Python web framework. It provides an overview of Django's features like MVT architecture, DRY principles, and Unix philosophy. It also describes starting a Django project, using the admin interface, generic views, templates, tags, filters, pagination, middleware, authentication, caching, internationalization and various Django tools. The document aims to introduce Django and its capabilities for building web applications and sites.
This document summarizes an advanced Python programming course, covering topics like performance tuning, garbage collection, and extending Python. It discusses profiling Python code to find bottlenecks, using more efficient algorithms and data structures, optimizing code through techniques like reducing temporary objects and inline functions, leveraging faster tools like NumPy, writing extension modules in C, and parallelizing computation across CPUs and clusters. It also explains basic garbage collection algorithms like reference counting and mark-and-sweep used in CPython.
PyCon Poland 2016: Maintaining a high load Python project: typical mistakesViach Kakovskyi
?
The talk is about typical mistakes which a Python developer without much experience in high load systems can make. Possible issues and preventive actions will be discussed. Expected audience: developers who are new to an existing highly loaded service or folks who develop a system from scratch. All the stuff based on own production experience.
3. Zen of Python>>> import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.…优美胜于丑陋明了胜于晦涩简洁胜于复杂…
8. 交换值一般写法:temp = a;a = b;b = temp;当然,一般情况下,这种写法不错,可惜…别忘记了,我们用的是Python!只需要一行,没看错!只需要一行!a, b = b, a
9. list把列表拼成字符串colors = ['red', 'blue', 'green', 'yellow']result = ‘’for s in colors: result += s这些当然可以,不过可以来的更简洁点!result = ''.join(colors)注意,比如有一堆字符串操作s += “aaa”s += “bbb”s += “ccc”这样,还不如:d = []d.append(“aaa”)d.append(“bbb”)d.append(“ccc”)s = “”.join(d)
10. dict突然想输出dict的所有key,怎么办?for key in d.keys(): print key嗯,这个已经不错了,很可读。但是我们可以做的更好!for key in d: print key如果想判断某key在不在dict里,你是不是想到了?if key in d: ...do something with d[key]而不是if d.has_key(key): ...do something with d[key]
12. list to dict有两组数据,一个是姓名,一个是城市,想得出一个对应的数据,怎么办呢?>>> name = ["smallfish", "user_a", "user_b"]>>> city = ["hangzhou", "nanjing", "beijing"]>>> d = dict(zip(name, city))>>> print d{'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'}是不是很简单?还需要两次for循环,一个临时的变量么?
13. open file一般写法是fp = open(“a.txt”)while True: line = fp.readline() if not line: break print line来一个酷的写法把with open("d:/1.log") as fp: line = fp.readline() print line其他想用with释放资源,请在__exit__里实现
15. 输出数组的index和值一般写法:i = 0for item in items: print i, itemi += 1改进一下,不需要i这个临时变量:for i in range(len(items)): print i, items[i]是不是还不太满意,每次总range,len一下,很烦躁?for(index, item) in enumerate(items): print index, item
16. 百分号很久以前,连接字符串和变量,有人这么写…print “name=”+ str(name) + “, age=”+int(age)后来在Python里也发觉了类似C的printf函数,而且进化的更优美!print “name=%s, age=%d” % (name, age)上面的只是针对单个变量格式化,如果针对一个dict,是不是要写N个读取变量来格式化?NO!values = {'name': name, 'messages': messages}print ('Hello %(name)s, you have %(messages)i ' 'messages' % values)你还可以更懒惰的这么写…print ('Hello %(name)s, you have %(messages)i ‘ 'messages' % locals())
19. 神器:列表推导(1)什么是列表 推导?它的英文名词好长好长… list comprehension还是来点实例,我想从一个数组里过滤出一些数值,保存到另外数组里a_list = [1 , 2, 3, 4, 5, 6] b_list = []for item in a_list: if item % 2 == 0:b_list.append(item)好吧,是不是大家都这么写? 那多无趣…b_list = [item for item in a_list if item % 2 == 0]>>> b_list[2, 4, 6]适用于list、tuple、string…
20. 神器:列表推导(2)重新实现前面的map、reduce、filtermap,数组里每个值都乘以2>>> [i * 2 for i in range(1, 10)][2, 4, 6, 8, 10, 12, 14, 16, 18]reduce,求和>>> sum(i for i in range(1, 10))45filter,过滤数字>>> [i for i in range(1, 10) if i % 2 == 0][2, 4, 6, 8]还需要for循环么?就是如此简单,就是如此的酷!当然,一切千万别过渡滥用 ?
21. Decorator(1)介个新特性是2.4之后新增的,很帅很酷!问题:我想记录每个函数执行的时间,怎么办?start = time.time()… run many many codeprint time.time() – start难道每个函数都如此写么?太龌龊了把。。先来一个包装函数def func_time(func): def _wrapper(*args, **kwargs): start = time.time()func(*args, **kwargs) print func.__name__, “run:", time.time()-start return _wrapper
22. Decorator(2)再来一个普通函数def sum(n): sum = 0 for i in range(n): sum += i return sum其实我们可以这样调用a = func_time(sum)a(100)有一种更加简便 方法@func_timedef sum(n): …. code调用一下把>>> sum(1000000)sum run: 0.265000104904看到了么?如果只是这么一个函数,这么写没啥好处如果你有一堆一堆只需要在函数上面加一个@func_time不需要改动函数本身多酷!