What are the advanced techniques in Python development?

Source: Internet
Author: User

Reply content:

Thank you Lao Yuan @ Original Blog invitation:)

I listed a few, do not know is not high-level skills, but I personally feel very useful.

1. Use iterators

Iterators are available in many languages, and in Python the appropriate scenarios are very "cool" with iterators. Because the iterator produces one object at a time, the appropriate use can save memory effectively, and it can achieve the effect of some "lazy calculation". In addition, iterators can sometimes be used to improve code readability because of the presence of the Generator (yield keyword) and Generator Expression.

For example, Itertools.islice ((Calculate_for_value (v) for V in Values), 0, 12) can be calculated only within the range of [0, 12), and is deferred, that is, the object is iterated to calculate. And if any (i% 3 = = 0 for i in numbers) can find the first value in numbers that can be divisible by 3, because it is a Generator Expression (one of the iterators), so find out later any function will return immediately, do not need To calculate I% 3 for the entire numbers list.

Incidentally, we recommend this library Erikrose/more-itertools , which contains a lot of useful iterator functions, is a good complement to the standard library itertools.

2. Use descriptors (descriptor)

The Python descriptor is an abstraction of the "attribute", a descriptor defined as a class property that controls the get, set, delete behavior of instance attributes of the same name on instances of this class, with finer granularity than instance-level magic method such as __getattr__. and more easily reused. This document has a simple description descriptor HowTo Guide , it can be seen that Python's "instance method", @property is fully implemented by it, and some third party libraries are also useful (such as the SQLAlchemy Column, the wtforms Field, and even the new enum for Python 3.4. Enum type).

With descriptor attributes, you can implement some very convenient customizations in your business code, such as a cached_property that can cache the return value yourself (or you can do it without your own implementation, directly with Werkzeug ).

3. Try not to use reflective techniques to fight with language

My personal point of view: With a programming language should be the same as the Romans, fight with language things do not do too much for good. Because the wheel built behind closed doors is difficult to make a circle, not to mention the language user's level and language design to fight is very hard.

The question is "advanced techniques", so for a dynamic language, reflection is certainly a high-level technique. But I've seen some. Use Python's reflection to scan all the. py files in some packages and then automatically import all the modules under the package. And not to say that this is destroying the Python "module is namespace" and lazy import settings, just from "correctness" there is a lot of problems. This approach only takes into account the scenario in the module file system and does not take into account the possibility of a module in a zip. Even if you enhance the implementation, consider the import of Zip, Python and PEP 302 The definition of Import Hook usage, it is completely useless by such a hack. This fight with language's approach is hard to really "correct".

so I think there is a Python technique that you should consider carefully when using "advanced techniques." Calm down to think oneself is not in fight with language, if is, suggest stop. Or do as the Romans do, or seriously consider whether Python is really worth improving. The latter is needed after a lot of thoughtful thinking, not 10 minutes of thought is enough. If the latter answer is really "yes", I think it might be right to write a PEP and then discuss it with the community to see if the improvements can be applied directly to the future version of Python, rather than in their own code using a seemingly advanced technique that is an ugly hack implementation against the language itself.

-------------------------------------------------------------------------------

Other Python-specific techniques, such as decorator, ContextManager, etc., because the Python developers are basically familiar with each other, I am not listed.

-------------------------------------------------------------------------------

Add: Actually there's a super long list Hidden features of Python ...... But a lot of the features are now routine. Recommend this post on Stack Overflow:
Hidden Features of Python can look at my blog, this is I watch while thinking of the record, not yet finished, basically a day to two of the rhythm.

Advanced features of Python 1: Immutable types that are easy to ignore
Advanced features of Python 2: List derivation, generator vs. iterator
Advanced features of Python 3: Magical __call__ and return functions
Advanced features of Python 4: Functional programming
Python's advanced feature 5: Talk about Python's dynamic properties
Advanced features of Python 6: Using __slots__ really saves a lot of memory
Advanced features of Python 7: Closures and decorators
Advanced features of Python 8: Do you really understand classes, objects, instances, methods?
Advanced features of Python 9: Crappy polymorphic
Advanced features of Python 10: Boring @property
Advanced features of Python 11: Extending the base data type (DICT) It is recommended to take a look at "Python advanced Programming".
Inside such as yield, property and other usage is considered more advanced skills.
There is a lot to be mentioned, and it is too laborious to enumerate them.
As for the list of what kind of a very basic thing. Personally feel The most important philosophy of the Python language is readability, so it is most important to improve the readability of the code and also to distinguish it from the advanced techniques.


Often accomplishing one thing is easy, the difference is the cost of it, is the elegance level. Writing Python is definitely a way to use it. There are no advanced techniques, just a few tips on teamwork:
1. DocString
It's a good practice to write docstring to modules or classes and functions, and see the official example:
>>>  def  my _function   ():    "" "does nothing, but document it.   ...   ... No, really, it doesn ' t do anything.   ... "" "  pass   ...  >>>  print  my_function   __doc__  do  nothing   but  document  it   no   really   it  doesn   ' t do anything.  
Lambda
Like what
calculator{ 'plus' : lambda x,y : x + y, 'minus' : lambda x,y : x - y}res = calculator['plus'](2, 3) # res = 5
Take a look at Python advanced programming
And also http://www. kokojia.com/course-526. HTML This link in the east is very good, interested to see, hope can help you
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.