Python 有什麼奇技淫巧?

來源:互聯網
上載者:User
0.這個問題雖說是找尋“奇技淫巧”,但其實是想拋磚引玉
1.如果想把自己認為或好玩或強大的python提示拿出來跟大家分享,可否稍微詳細的講解一下

回複內容:

從 Python 2.3 開始,sys 包有一個屬性,叫 meta_path 。可以通過給 sys.meta_path 註冊一個 finder 對象,改變 import 的行為。甚至可以實現這樣的功能:通過 import 來匯入一個 json 檔案中的資料。

舉個例子,有一個 tester.json 檔案,裡面的內容是:
{    "hello": "world",    "this": {        "can": {            "be": "nested"        }    }}
更新一個最近發現的技巧,一行代碼實現多線程/多進程,來源於python開發人員公眾號。

首先來看下代碼:


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()

對,你沒有看錯,只要一行代碼就可以把普通的任務變成並行任務。不用手動管理線程,一切都由map自動完成。這裡示範的是多線程,如果要多進程的話只需把 from multiprocessing.dummy 改成 from multiprocessing ,就是這麼任性!

以下為這個庫的詳細介紹:

在 Python 中有個兩個庫包含了 map 函數: multiprocessing 和它鮮為人知的子庫 multiprocessing.dummy.

這裡多扯兩句: multiprocessing.dummy? mltiprocessing 庫的線程版複製?這是蝦米?即便在 multiprocessing 庫的官方文檔裡關於這一子庫也只有一句相關描述。而這句描述譯成人話基本就是說:”嘛,有這麼個東西,你知道就成.”相信我,這個庫被嚴重低估了!

dummy 是 multiprocessing 模組的完整複製,唯一的不同在於 multiprocessing 作用於進程,而 dummy 模組作用於線程(因此也包括了 Python 所有常見的多線程限制)。
所以替換使用這兩個庫異常容易。你可以針對 IO 密集型任務和 CPU 密集型任務來選擇不同的庫。


原文連結 : http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652563685&idx=2&sn=f563f8913630a4334219ed4a9fa99653&scene=0#wechat_redirect

———————以下為原答案———————————

搜了一下,發現沒人說這個。
廢話不說,直接:


在python中,下滑杠代表上一次啟動並執行結果。不要問我為什麼,我也不知道。
這個奇技淫巧是我在查scapy的資料的時候意外發現的,網上關於這個技巧的資料似乎也很少,嗯。(順便提一下,scapy是個非常強大的庫,幾乎涵蓋了所有網路相關的功能,推薦學習。)

再來說一個吧,關於動態修改代碼的。直接上代碼:

# socket.py#import sysdel sys.modules['socket']   # 從記憶體中刪除當前的socket包import sysimport timeimport loggingimport typespath = sys.path[0]sys.path.pop(0)        import socket    # 匯入真正的socket包sys.path.insert(0, path)# 動態path類方法def re_class_method(_class, method_name, re_method):    method = getattr(_class, method_name)    info = sys.version_info    if info[0] >= 3:   # py2和py3的文法略有不同,需要做下判斷。        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))# 動態path執行個體方法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))# 需要修改的類方法def re_accept(old_method, self, *args, **kwds):    return_value = old_method(self, *args, **kwds)    #do something    return return_value# 需要修改的執行個體方法def re_recvfrom(old_method, self, *args, **kwds):    return_value = old_method(*args, **kwds)    # do something    return 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, *args, **kwds)setattr(socket.socket, '_list_client_ip', {})  #  綁定類屬性(socket不能動態綁定執行個體屬性,只好綁定類屬性了)re_class_method(socket.socket, 'bind', re_bind)  #把socket類的bind方法替換成re_bindre_class_method(socket.socket, 'accept', re_accept)  #把socket類的accept方法替換成re_accept
也有一個 Python 的奇技淫巧分享給大家,讓 Python 的 2+2=5:

In [1]: import ctypesIn [2]: ctypes.memmove(id(4), id(5), 24)Out[2]: 15679760In [3]: 2 + 2Out[3]: 5
剛好看到個
來自於 來自於 python進階編程 作者是 @董偉明 說明在分享一個準備給公司講python進階編程的slide 這裡還有對應的視頻講解

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

另外一個感覺就是這個庫了ajalt/fuckitpy · GitHub 中間的實現挺厲害的,訪問源碼逐行加入 try: finallyPython沒有什麼奇技淫巧吧。。。Hidden features of Python 這個連結上有很多小例子
比如for else值得說下。不break的話就執行else
for i in range(10):    if i == 10:        break    print(i)else:    print('10不在裡面!')
其實 PYC 檔案很簡單:
>>> import dis, marshal>>> with open('hello.pyc', 'rb') as f:...     f.seek(8)...     dis.dis(marshal.load(f))
昨天剛在 StackOverflow 看到的,break 多層迴圈: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)
可配置單例,從tornado學來的
Stack Overflow上有一個多人編輯整理的答案,非常全而且經常更新:
Hidden features of Python

收藏這個頁面,順便給我的回答點個贊同啊。1. 元類(metaclass)
PyPy的源碼裡有個pair和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
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.