1. 程式人生 > >Python 中的那些坑總結——持續更新

Python 中的那些坑總結——持續更新

多說 分享 earlier als lse image code while HA

1.三元表達式之坑

技術分享圖片

很顯然,Python把第一行的(10 + 4)看成了三元表達式的前部分,這個坑是看了《Python cookbook》(P5)中學到的,書中的代碼:

技術分享圖片

2.Python生成器(yield)+遞歸

前兩天一直糾結python的生成器遞歸該怎麽寫,今天看了os.walk()的代碼恍然大悟,編程真是博大精深啊!不多說,上代碼:

from os import path

def walk(top, topdown=True, onerror=None, followlinks=False):
    islink, join, isdir = path.islink, path.join, path.isdir
    
try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if
isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: new_path = join(top, name) if followlinks or not islink(new_path): for x in walk(new_path, topdown, onerror, followlinks): #
生成器遞歸 yield x if not topdown: yield top, dirs, nondirs

3.try...finally + return:

  如果寫了try模塊內有return且最後還有finally,那麽會執行return後再執行finally。

  這是從Queue的get方法裏看到的,貼上自己寫的測試代碼:

  技術分享圖片

  附加Queue的get方法:

# Queue.py
......
    def get(self, block=True, timeout=None):
        self.not_empty.acquire()
        try:
            if not block:
                if not self._qsize():
                    raise Empty
            elif timeout is None:
                while not self._qsize():
                    self.not_empty.wait()
            elif timeout < 0:
                raise ValueError("‘timeout‘ must be a non-negative number")
            else:
                endtime = _time() + timeout
                while not self._qsize():
                    remaining = endtime - _time()
                    if remaining <= 0.0:
                        raise Empty
                    self.not_empty.wait(remaining)
            item = self._get()
            self.not_full.notify()
            return item
        finally:
            self.not_empty.release()

Python 中的那些坑總結——持續更新