- 浏览: 109016 次
- 性别:
- 来自: 北京
最新评论
-
hzpfly:
...
Amusing Python 2: range/xrange -
bcw104:
不支持中文路径
Python 中怎么 copy 文件和目录 -
snageyang:
10000的结果xrange 0.65599989891 0 ...
Amusing Python 2: range/xrange -
caesarok:
有的没那么简单,呵呵
Python 中使用 FTP -
cloudhe:
qubic 写道
引用
Ruby 没有类似 Jython 的东 ...
Python and Ruby
If you're not willing to read English, here is a translation:
http://blog.csdn.net/lanphaday/archive/2008/08/03/2762251.aspx
What the heck does "pythonic" mean?
This was a question asked a few months ago, on, of all places, the EuroPython mailing list, which is mainly used to plan the EuroPython conference. It was an interesting question though. I realized I've seen the word been used a lot, but that I've hardly seen any attempts to explain what it means. In the thread that ensued, different people, including myself, gave their own answers. I rewrote my answer for my weblog, as it may benefit others.
"Pythonic" is a vague concept, but not necessarily that much more vague than concepts like "intelligence" or "life", which, when you try to actually define them, tend to be slippery. That they're hard to define doesn't mean that they're useless though; humans work well with messy definitions. "Pythonic" means something like "idiomatic Python", but now we'll need to describe what that actually means.
Over time, as the Python language evolved and the community grew, a lot of ideas arose about how to use Python the right way. The Python language actively encourages a large number of idioms to accomplish a number of tasks ("the one way to do it"). In turn, new idioms that evolved in the Python community has have in turn influenced the evolution of the language to support them better. The introduction of the dictionary .get() method, which combines in one operation what would be done with a combination of has_key() and item access before, can be considered an example of such an evolution.
Idioms are frequently not straightforwardly portable from another programming language. For example, the idiomatic way to perform an operation on all items in a list in C looks like this:
for (i=0; i < mylist_length; i++) { do_something(mylist[i]); }
The direct equivalent in Python would be this:
i = 0 while i < mylist_length: do_something(mylist[i]) i += 1
That, however, while it works, is not considered Pythonic. It's not an idiom the Python language encourages. We could improve it. A typical idiom in Python to generate all numbers in a list would be to use something like the built-in range() function:
for i in range(mylist_length): do_something(mylist[i])
This is however not Pythonic either. Here is the Pythonic way, encouraged by the language itself:
for element in mylist: do_something(element)
A frequent question on comp.lang.python involves how to pass or modify references directly, something that is not possible in Python; there's just assignment (and its close relatives the import, class and def statements). This is undoubtedly sometimes driven by the desire to write code that returns multiple values from a function. The idiomatic way to do this in C and a number of other languages is to pass to this function pointers or references:
void foo(int* a, float* b) { *a = 3; *b = 5.5; } ... int alpha; int beta; foo(&alpha, &beta);
It's possible in Python to hack up strategies to pass function results through arguments, such as like this:
def foo(a, b): a[0] = 3 b[0] = 5.5 alpha = [0] beta = [0] foo(alpha, beta) alpha = alpha[0] beta = beta[0]
This is however considered to be screamingly unpythonic, as the idiomatic way to return multiple values from a function is quite different and looks much nicer. It exploits tuples and tuple unpacking:
def foo(): return 3, 5.5 alpha, beta = foo()
Code that is not Pythonic tends to look odd or cumbersome to an experienced Python programmer. It may also be overly verbose and harder to understand, as instead of using a common, recognizable, brief idiom, another, longer, sequence of code is used to accomplish the desired effect. Since the language tends to support the right idioms, non-idiomatic code frequently also executes more slowly.
To be Pythonic is to use the Python constructs and datastructures with clean, readable idioms. It is Pythonic is to exploit dynamic typing for instance, and it's definitely not Pythonic to introduce static-type style verbosity into the picture where not needed. To be Pythonic is to avoid surprising experienced Python programmers with unfamiliar ways to accomplish a task.
The word "Pythonic" can also be applied beyond low-level idioms. For a library or framework to be Pythonic is to make it as easy and natural as possible for a Python programmer to pick up how to perform a task. A library or framework, although written in Python, could be considered unpythonic if it necessitated programmers using it to write cumbersome or non-idiomatic Python code. Perhaps it's not using constructs Python offers, such as classes, even though they would make the library more convenient or easier to understand. Possibilities like being allowed to pass functions and methods as arguments to functions might be overlooked where they could be handy. A class defined in a library might be trying to do its best to enforce information hiding like you have in a language like Java, while Python more operates under the looser strategy of 'advisory locking', where attributes are typically available but the programmer is hinted about their privacy by a leading underscore.
Of course, when you get to such a larger scale, to libraries and frameworks, it gets more contentious whether something is Pythonic or not. There are still some guidelines though. One is that of lesser verbosity: APIs of Python libraries tend to be smaller and more lightweight than those of Java libraries doing the same thing. Python library which have a heavy-weight, overelaborate API are not considered to be very "Pythonic". The W3C XML DOM API, for instance, which has been implemented in
Python quite a few times, is not considered to be Pythonic. Some people think it's "Java-esque", though from what I heard it's in fact not considered very Java-like either by many Java programmers...
A Python-based framework can be considered Pythonic if it doesn't try to reinvent the wheel too much where there already language idioms to accomplish the same thing. It should also follow common Python conventions concerning idioms.
Of course the problem is that frameworks, being frameworks, almost inevitably try to introduce patterns and ways of doing things that may not be familiar if you're used to smaller applications. That's how you exploit the power of a framework. Zope 2, a framework I'm intimately familiar with, is an example of a framework that definitely introduces a lot of particular ways of doing things that you don't run into so often elsewhere. Acquisition is an example. As a result, it's not considered very Pythonic by many experienced Python programmers.
It's difficult to create a Pythonic framework. It isn't helped by that the fact that the notion of what is cool, idiomatic, good Python code has evolved quite significantly over the years. Features like generators, sets, unicode strings and datetimes are now considered Pythonic. Zope 2 is an example of a framework that definitely shows its age there, and in part it cannot be blamed for it, as it was first developed in 1997 or so. Considering that, it's holding up very well indeed, thank you.
An example of a new trend in Pythonicness that I witnessed myself in recent years is the movement towards standardizing idioms of package and module structure in Python. Newer codebases like Twisted, Zope 3, and PyPy all more or less follow this pattern:
- package and modules names are brief, lowercase, and singular
- packages are frequently namespace packages only, i.e. have empty __init__.py files.
I've also tried to follow this convention in libraries I wrote, such as lxml.
Sometimes I think the condemnation of software as 'unpythonic' may be somewhat unfair and may obscure other positive aspects of the software. A less powerful framework that is easy to pick up for a Python programmer may be considered more Pythonic than a far more powerful system that takes more of a time investment to learn.
Finally, for another, complementary perspective on what is Pythonic design, try the following in a python interpreter:
import this
From http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0
发表评论
-
Python and Ruby
2008-10-06 16:13 1620Python 和 Ruby 的相同点: 都强调语法 ... -
Feel Pythonic: The Zen of Python
2008-09-24 14:20 1070Let's feel about what "pyt ... -
Python 中使用 pyrex 生成 Linux 可执行文件
2008-08-15 14:30 10450这个问题是相当有意义的,如果有了比较好的方法,Pyth ... -
Python 模块之 threading: 在 Python 中使用多线程
2008-08-15 14:25 4157Python 是支持多线程的,并且是 native 的 ... -
Python 模块之 ConfigParser: 用 Python 解析配置文件
2008-08-15 14:23 4045在程序中使用配置文件来灵活的配置一些参数是一件很常见的 ... -
Python 中怎么 copy 文件和目录
2008-08-15 14:20 2594>>> import shutil > ... -
Python 中使用 FTP
2008-08-15 14:19 1801import ftplib ftp = ftplib.FTP ... -
Python 中列出目录中所有文件的方法
2008-08-15 14:17 29394import string, os, sys dir = ' ... -
用 C 为 Python 写个简单的模块
2008-08-15 14:09 1859Python 语言是支持用 C 来 ... -
Amusing Python 2: range/xrange
2008-08-15 14:03 2489这两个基本上都是在循环的时候用。 for i in rang ... -
在 Python 代码中进行自动测试
2008-08-15 13:49 1316Python 有一个叫 doctest 的模块,很有意思,它可 ... -
Python2.5 中的新类型:set (集合)
2008-08-15 13:46 1614Python2.5 中新增加了集合内容,让我想起了初中数学。看 ... -
Amazing Python 3: "@"
2008-08-15 13:44 9901. This an interesting usage th ... -
用 Python 下载网页,超级简单!
2008-08-15 13:42 1909from urllib import urlopen web ... -
Amusing Python 1: "*"
2008-07-25 15:15 849Take a look at the three differ ... -
Amazing Python 2: "exec/eval/repr"
2008-07-25 14:35 13581. exec: Executing comm ... -
Amazing Python 1: "yield"
2008-07-23 11:37 897"yield" is used for G ... -
Syntax highlights of Python in UltraEdit
2008-05-09 16:39 2702Open \UEStudio 06\wordfile.txt ... -
[Copy] 有限状态自动机(FSM)的简单实现
2007-12-12 11:17 3937Sometimes, a quite simple conce ... -
Bewildering service names of python application on maemo
2007-12-07 15:51 1159A simple file structure of pyth ...
相关推荐
《PyPI官网下载 | Pythonic-0.12.tar.gz:深入理解Python库与云原生技术》 PyPI(Python Package Index),是Python社区官方的软件包仓库,提供了丰富的Python库供开发者下载和使用。资源"Pythonic-0.12.tar.gz"即...
第14章 Pythonic与Python杂记.mp4
Redisworks 0.4.0 Pythonic Redis 客户端为什么选择 Redisworks?惰性 Redis 查询动态类型易于使用您是否曾经使用过 PyRedis,并想知道为什么您必须一直考虑类型?您是否必须不断地将对象转换为字符串并反复转换,...
fabric, 简单,Pythonic 远程执行和部署 fabric 是 python ( 2.5 -2.7 ) 库和命令行工具,用于简化应用程序部署或者系统管理任务的SSH使用。它为执行本地或者远程 shell 命令( 。正常或者通过 sudo ) 和上载/下载...
14.6_None|Pythonic与Python杂记|Python3.8入门_&_进阶_&_原生爬虫实战完全解读
bidict-Pythonic双向映射数据结构
这个库的核心理念是提供一种“pythonic”的方式,即符合Python编程习惯的方式来操作数据库,使得开发人员在处理数据库任务时能更加高效、便捷。 在Python中,通常我们使用诸如SQLite、MySQL、PostgreSQL等数据库的...
Pythonic-PHP-Code-Formatter, Pythonic PHP代码格式化程序只是为了好玩 Pythonic-PHP-Code-FormatterPythonic PHP代码格式化程序。仅供娱乐? 由 Twitter 激发。=========== =演示演示:http://www.94cb.com/Python
Pythonic and Reusable Code,python代码的可重用,更Pythonic 的技巧,好的代码,书中有将近30多个例子,让你了解更Pythonic代码写法,让你更了解python语言
Zipline, a Pythonic Algorithmic Trading Library
简单的、Pythonic 的远程执行和部署。 欢迎来到 Fabric!Fabric 是一个高级 Python(2.7、3.4+)库,旨在通过 SSH 远程执行 shell 命令,从而产生有用的 Python 对象。它建立在Invoke(子进程命令执行和命令行功能)...
"Python编程与实战 上有关项目实战的代码-Pythonic.zip"这个压缩包文件显然包含了用于教学或自我实践的Python项目代码,旨在帮助学习者更好地理解和运用Python语言的精华。Pythonic一词通常指的是遵循Python编程哲学...
刚刚获得的模式验证Pythonic模式是一个用于验证Python数据结构的库,例如从config / files,forms,外部服务或命令行解析获得的数据,这些数据是从JSON / YAML转换而来的(或者其他els Schema验证刚刚得到的Pythonic...
Matlab代码sqrt 八度Pythonic软件包 Pythonic是一个软件包,可为提供本地调用接口。 用法 使用pkg命令将此软件包安装在Octave中 pkg install ...
要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码,github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,下面列举一些常见的Pythonic写法。 0. 程序必须先让人读...
标题中的"PyPI 官网下载 | rkd.pythonic-2.4.1.dev144.tar.gz"表明这是一个从Python Package Index (PyPI) 官方网站获取的软件包,名为`rkd.pythonic`,版本号为2.4.1的开发版,具体是第144次迭代(dev144)。...