What artifice do Python have?

Source: Internet
Author: User
0. The problem is to seek "artifice", but in fact it is to stimulate
1. If you want to share your thought or playful or powerful Python skills with you, can you explain it in a little more detail?

Reply content:

Starting with Python 2.3, the SYS package has an attribute called Meta_path. You can change the import behavior by registering a Finder object with Sys.meta_path. You can even implement the ability to import data from a JSON file via import.

For example, there is a Tester.json file that contains:
{    "hello": "world",    "this": {        "can": {            "be": "nested"        }    }}
Update a recently discovered technique, one line of code to implement multi-threaded/multi-process, from the Python developer public number.

First 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're not mistaken, as long as one line of code can turn ordinary tasks into parallel tasks. Instead of manually managing threads, everything is done automatically by map. Here is a demonstration of multi-threading, if you want to process more than just change from multiprocessing.dummy to from multiprocessing, is so capricious!

The following is a detailed description of this library:

There is a two library in Python that contains the map function: multiprocessing and its little-known subpackage multiprocessing.dummy.

Here are two more words: Multiprocessing.dummy? Mltiprocessing Library for threaded version cloning? Is this a shrimp? Even in the official document of the multiprocessing library there is only one sentence related to this sub-library. And this sentence is basically said: "Well, there is such a thing, you know it." Trust me, this library is grossly undervalued!

The dummy is a complete clone of the multiprocessing module, the only difference being that the multiprocessing acts on the process, and the dummy module acts on the thread (and therefore includes all the common multithreading limitations of Python).
So replacing using these two libraries is exceptionally easy. You can select different libraries for IO-intensive tasks and CPU-intensive tasks.


Original link: http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652563685&idx=2&sn= F563f8913630a4334219ed4a9fa99653&scene=0#wechat_redirect

——————— below are the original answers ———————————

Searched and found no one to say this.
Nonsense not to say, directly:


In Python, the slide bar represents the result of the last run. Don't ask me why, I don't know.
This artifice is I found in the scapy of information, the online information on this technique seems to be very few, uh. (Incidentally, Scapy is a very powerful library that covers almost all of the network-related features and is recommended for learning.) )

Let's say one more thing about dynamically modifying code. Directly on the code:

# socket.py#import Sysdel sys.modules[' socket ' # Remove the current socket package from memory import sysimport timeimport Loggingimport Typespath = Sys.path[0]sys.path.pop (0) Import Socket # imports the real socket package Sys.path.insert (0, path) # Dynamic Path class method Def Re_class_method (_c   Lass, Method_name, Re_method): Method = GetAttr (_class, method_name) info = sys.version_info if info[0] >= 3:        # py2 and Py3 's syntax is slightly different and needs to be judged. 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) # Dynamic Path instance method 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 that needs to be modified Def re_accept (Old_method, Self,    *args, **kwds): Return_value = Old_method (self, *args, **kwds)#do something return return_value# The instance method that needs to be modified Def re_recvfrom (Old_method, Self, *args, **kwds): Return_value = Old_met    Hod (*args, **kwds) # do something return return_value# need to modify the class method (no return value) def re_bind (Old_method, Self, *args, **kwds): Re_self_method (self, ' recvfrom ', re_recvfrom) #把self实例的recvfrom方法替换成re_recvfrom #do something Old_method (self, *ar GS, **kwds) setattr (socket.socket, ' _list_client_ip ', {}) # Binding class properties (sockets cannot bind instance properties dynamically, have to bind class properties) Re_class_method ( Socket.socket, ' bind ', Re_bind) #把socket类的bind方法替换成re_bindre_class_method (Socket.socket, ' accept ', re_accept) # Replace the Accept method of the socket class with re_accept
There is also a python artifice to share with everyone, so Python's 2+2=5:

inch [1]: Import cTYPESinch [2]: cTYPES.Memmove(ID(4), ID(5),  -) out[2]: 15679760inch [3]: 2 + 2 out[3]: 5
Just saw a
from the From Python advanced programming The author is @ Dong Weiming description in sharing a preparation for the company to speak Python advanced programming slide There's also a video tutorial

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

Another feeling is this library. Ajalt/fuckitpy GitHub In the middle of the implementation is very strong, access to the source code line to join try:finallyPython has no artifice ... Hidden Features of Python There are many small examples of this link.
such as for else is worth the next. Execute else if you don't break.
foriinrange(10):    ifi==10:        break    print(i)else:    print('10不在里面!')
In fact, the PYC file is simple:
>>> import dis, marshal>>> with open('hello.pyc', 'rb') as f:...     f.seek(8)...     dis.dis(marshal.load(f))
I saw it yesterday at StackOverflow. Break Multilayer Loop: python-breaking out of nested loops
 for x inch xrange(Ten):     for y inch xrange(Ten):        Print x*y        if x*y >  -:             Break    Else:        Continue  # executed If the loop ended normally (no break)     Break  # executed if ' Continue ' was skipped (break)
Configurable Singleton, learned from tornado
There is a multi-person compilation of answers on Stack overflow, very full and often updated:
Hidden Features of Python

Collect this page, by the way to my answer to the point of approval AH. 1. Meta-Class (Metaclass)
PyPy's source has a pair and a extendabletype.
"""The magic tricks for classes:class X:__metaclass__ = Extendabletype        ...# In some other file ...class __extend__ (X):... # and here's 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 =Def Method ((x, y), other, arguments):            ...pair (x, y). Attributepair (x, Y). Method (Other, arguments)This finds methods and class attributes based on the actualclass of both objects that go to 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 extendsThe definition of ' t ' instead of creating a new subclass. "" "    def __new__(CLS, name, Bases, Dict):        if name == ' __extend__ ':             for CLS inch Bases:                 for Key, value inch 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 (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 inch CLS1.__bases__]        Bases2 = [Pairtype(CLS1, Base2)  for Base2 inch 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.