What are the tricks of Python?

Source: Internet
Author: User
0. although this problem is to look for "tricks and tricks", it is actually intended to attract others. if you want to share with you the python tips that you think are fun or powerful, could you give me some detailed explanations? 0. although this problem is to look for "tricks and tricks", it is actually intended to inspire others.
1. if you want to share with you the python usage skills that you think are fun or powerful, could you give me a detailed explanation? The reply content: Starting from Python 2.3, the sys package has an attribute, meta_path. You can register a finder object for sys. meta_path to change the import behavior. You can even use this function to import data in a json file through import.

For example, a tester. json file contains the following content:

{    "hello": "world",    "this": {        "can": {            "be": "nested"        }    }}
Update a recently discovered technique. One line of code implements multi-threaded/multi-process, which comes from the public account of the python developer.

First, let's look at the Code:


Import urllib2
From multiprocessing. dummy import Pool as ThreadPool

Urls = [
'Http: // www.python.org ',
'Http: // www.python.org/about /',
'Http: // www.onlamp.com/pub/a/python/2003
]

Pool = ThreadPool (4)
Results = pool. map (urllib2.urlopen, urls)
Pool. close ()
Pool. join ()

Yes, you are not mistaken. You only need a line of code to convert a common task into a parallel task. You do not need to manually manage the thread. All tasks are automatically completed by map. Here we demonstrate multithreading. If you want to have multiple processes, you only need to change from multiprocessing. dummy to from multiprocessing, which is so capricious!

The following is a detailed introduction to this database:

In Python, there are two libraries that contain the map function: multiprocessing and its little-known sub-database multiprocessing. dummy.

Here are two more sentences: multiprocessing. dummy? What is the clone of the mltiprocessing library's thread version? Is this Xiami? Even in the official documentation of the multiprocessing library, there is only one description of this sub-database. This statement is basically translated into a human saying: "Well, you know it is like this." Believe me, this library is seriously underestimated!

Dummy is a complete clone of the multiprocessing module. The only difference is that multiprocessing acts on the process, while the dummy module acts on the thread (which also includes all the common multithreading restrictions of Python ).
Therefore, it is easy to replace the two databases. You can select different libraries for IO-intensive tasks and CPU-intensive tasks.


Http://mp.weixin.qq.com/s? _ Biz = MzA4MjEyNTA5Mw ==& mid = 2652563685 & idx = 2 & sn = f563f8913630a4334219ed4a9fa99653 & scene = 0 # wechat_redirect

------- The following is the original answer -----------

I searched and found no one said this.
Don't talk nonsense, directly:


In python, the slide bar represents the result of the previous operation. I don't know why.
This trick was unexpectedly discovered when I checked scapy's materials. There seems to be very little information about this technique on the internet, well. (By The Way, scapy is a very powerful library that covers almost all network-related functions and is recommended for learning .)

Let's talk about the dynamic modification of code. Directly run the Code:

# Socket. py # import sysdel sys. modules ['socket '] # Delete the current socket package from the memory import sysimport timeimport loggingimport typespath = sys. path [0] sys. path. pop (0) import socket # import the real socket package sys. path. insert (0, path) # Dynamic path class method def re_class_method (_ class, method_name, re_method): method = getattr (_ class, method_name) info = sys. version_info if info [0]> = 3: # the syntax of py2 and py3 is slightly different. You need to make a judgment. Setattr (_ class, method_name, types. methodType (lambda * args, ** kwds: re_method (method, * args, ** kwds), _ class) else: setattr (_ class, method_name, types. methodType (lambda * args, ** kwds: re_method (method, * args, ** kwds), None, _ class) # def re_self_method (self, method_name, re_method): method = getattr (self, method_name) setattr (self, method_name, types. methodType (lambda * args, ** kwds: re_method (method, * args, ** kwds), self, self) # The class method def re_accept (old_method, self, * args, ** kwds): return_value = old_method (self, * args, ** kwds) # do something return return_value # instance method to be modified def re_recvfrom (old_method, self, * args, ** kwds): return_value = old_method (* args, ** kwds) # do something return return_value # class method to be modified (no return value) def re_bind (old_method, self, * args, ** kwds): re_self_method (self, 'recvfrom', re_recvfrom) # Replace the recvfrom method of the self instance with re_recvfrom # do something old_method (self, * args, ** kwds) setattr (socket. socket, '_ list_client_ip', {}) # bind class attributes (socket cannot dynamically bind instance attributes, so you have to bind class attributes) re_class_method (socket. socket, 'bind', re_bind) # Replace the bind method of the socket class with re_bindre_class_method (socket. socket, 'access', re_accept) # Replace the accept method of the socket class with re_accept
There is also an amazing Python trick to share with you, let Python 2 + 2 = 5:

In [1]: import ctypesIn [2]: ctypes.memmove(id(4), id(5), 24)Out[2]: 15679760In [3]: 2 + 2Out[3]: 5
You can see
From Advanced python Programming The author @ Dong weiming explained that he was sharing a slide about advanced python programming for the company. The corresponding video is also explained here

========================================================== ======================================

Another feeling is that this library has ajalt/fuckitpy-GitHub The implementation in the middle is quite powerful, and the access source code is added line by line Try: finallyPython doesn't have any tricks... Hidden features of Python There are many small examples on this link
For example, for else is worth mentioning. Execute else if you do not have a break

For I in range (10): if I = 10: break print (I) else: print ('10 is not in it! ')
In fact, the PYC file is very simple:

>>> import dis, marshal>>> with open('hello.pyc', 'rb') as f:...     f.seek(8)...     dis.dis(marshal.load(f))
What I saw in StackOverflow yesterday is a multi-tier break loop: python-Breaking out of nested loops.

for x in xrange(10):    for y in xrange(10):        print x*y        if x*y > 50:            break    else:        continue  # executed if the loop ended normally (no break)    break  # executed if 'continue' was skipped (break)
Configurable Singleton, learned from tornado
On Stack Overflow, there is an answer edited by many people, which is comprehensive and often updated:
Hidden features of Python

Add this page to your favorites and give me some comments. 1. metaclass)
The source code of PyPy contains pair and extendabletype.

"""Two magic tricks for classes:    class X:        __metaclass__ = extendabletype        ...    # in some other file...    class __extend__(X):        ...      # and here you can add new methods and class attributes to XMostly useful together with the second trick, which lets you buildmethods whose 'self' is a pair of objects instead of just one:    class __extend__(pairtype(X, Y)):        attribute = 42        def method((x, y), other, arguments):            ...    pair(x, y).attribute    pair(x, y).method(other, arguments)This finds methods and class attributes based on the actualclass of both objects that go into the pair(), with the usualrules of method/attribute overriding in (pairs of) subclasses.For more information, see test_pairtype."""class extendabletype(type):    """A type with a syntax trick: 'class __extend__(t)' actually extends    the definition of 't' instead of creating a new subclass."""    def __new__(cls, name, bases, dict):        if name == '__extend__':            for cls in bases:                for key, value in dict.items():                    if key == '__module__':                        continue                    # XXX do we need to provide something more for pickling?                    setattr(cls, key, value)            return None        else:            return super(extendabletype, cls).__new__(cls, name, bases, dict)def pair(a, b):    """Return a pair object."""    tp = pairtype(a.__class__, b.__class__)    return tp((a, b))   # tp is a subclass of tuplepairtypecache = {}def pairtype(cls1, cls2):    """type(pair(a,b)) is pairtype(a.__class__, b.__class__)."""    try:        pair = pairtypecache[cls1, cls2]    except KeyError:        name = 'pairtype(%s, %s)' % (cls1.__name__, cls2.__name__)        bases1 = [pairtype(base1, cls2) for base1 in cls1.__bases__]        bases2 = [pairtype(cls1, base2) for base2 in cls2.__bases__]        bases = tuple(bases1 + bases2) or (tuple,)  # 'tuple': ultimate base        pair = pairtypecache[cls1, cls2] = extendabletype(name, bases, {})    return pair

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.