2013-04-21 83 views
0

我經常在開源或「專業」python代碼中看到註釋 - 比如webapp2或webob,看起來非常分散。評論似乎超過了代碼。我注意到個別開發人員也在自己的應用程序中執行此操作。大的間距,大量的評論,然後每隔幾行代碼幾行代碼。我應該如何評論python代碼?

我想我喜歡這種風格,它感覺更有組織。現在,我是Python中的大型項目,我想知道是否應該組織一個大型項目,其中包含代碼和評論,就像我見過的其他人一樣。我認爲這可能會使它更具可讀性和可維護性,也可能使我成爲更好的編碼器 - 因爲事情會更加清晰。

只是想過:這個問題更好的代碼審查? 聽到的是服從

目前我就是這樣的評論,例如:

#U - Idempotent. b-atching requests 
    # which can be PUT, DELETE or GET. 
    #@control.access.collector_or_owner   
    def patch(s,*a,**k): 
      s.resolve(*a,**k) 
      for mod in s.requested_modifications: 
        method = mod.get('method') or 'PUT' 
        point = s.current_point+mod.get('point') or '' 
        body = mod.get('body') or '' 
        s.say('Will execute %s on %s for %s\n' % (method,point,body)) 
        # create the in-app request 
        mod_request = webapp2.Request.blank(point) 
        mod_request.body = str(body) 
        mod_request.method = method 
        mod_request.app = s.app 
        # then find the handler and report 
        execute_tuple = s.app.router.match(mod_request) 
        mod_request.route,mod_request.route_args,mod_request.route_kwargs = execute_tuple 
        handler = mod_request.route.handler 
        if handler not in s.app.router.handlers: 
          s.app.router.handlers[handler] = handler = webapp2.import_string(handler) 
        else: 
          handler = s.app.router.handlers[handler] 
        s.say('Will execute %s on %s for %s via %s\n' % (method,point,body,execute_tuple)) 
        # then execute 
        in_app_response = webapp2.Response() 
        handler = handler(mod_request,in_app_response) 
        handler.dispatch() 
        s.say('Response is %s\n' % (in_app_response)) 

剛剛論點集中在「什麼是要做」,但並不能說明別的。我確信有更好的辦法,但我不想用自己更好的方式來提出聖人的智慧。

我已經有Style Guide PEP的讀 - 這是有幫助的,但一些評論提煉的智慧auteurs與不是「寫英語時,斯特倫克和白色的更詳細一點的大複雜的Python項目申請「是必需的。

回答

1

不是一個直接的答案,但我覺得它與問題有關。

在他的重要著作代碼大全,史蒂夫·麥康奈爾主張首先編寫粗糙的僞代碼解釋你要完成的,用字從問題域(例如的「客戶」,而不是「CustomerRecords的名單」)什麼。然後對僞代碼進行細化,直到「編寫代碼比編寫代碼更容易」(從內存釋義)。

現在註釋掉僞代碼和僞代碼的每一行下面的實際代碼填寫,並留下僞它在哪裏,因爲它是現在非常漂亮充當解釋代碼的意圖評論

+0

是的,我認爲這就像我的目標,作爲我的戰略之一,以解決更大的項目。謝謝! – 2013-04-21 08:18:02

4

聲明:我不是一個聖人。

Python本身非常易讀,但我通常看到缺少可讀性的間距。我主要使用間距/註釋來顯示代碼中的結構,偶爾用於解釋棘手的代碼塊。對於後一種情況,重構代碼通常會更好,如果可能的話,這樣做不那麼棘手,而不是深入研究長文檔。

鑑於谷歌的編程專業知識,他們的Python Style Guide (Comments)通常是一個很好的資源。

2

記錄該功能應該在docstring中完成。您對功能的評論對我來說是難以理解的。文檔字符串看起來是這樣的:

def patch(s,*a,**k): 
    """Patch a ... 

    Arguments: 
    s - A ... object 
    Any additional arguments are handed to s.resolve(). 

    Returns: 
    bla 

    Raises: 
    ValuesError when s is not ... 
    """ 
    s.resolve(*a,**k) 
    for mod in s.requested_modifications: 
     ... 

在你的代碼中的內聯註釋是不是非常有幫助的,因爲他們只是粗糙地代碼做什麼,有效地複製它。

取而代之的是使用註釋做描述爲什麼如果代碼沒有立即顯現,它會做些什麼。