`
flex_莫冲
  • 浏览: 1095648 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

[effective python]改善python代码的91个建议-chapter1

阅读更多
## 建议1 使用pep8校验代码规范性
pep8 --first test.py
长字符串换
print 'You\'d need to know \'bout escapes with' \
      '\\ that do \n newlines and \t tabs.'


print ('You\'d need to know \'bout escapes with' 
      '\\ that do \n newlines and \t tabs.') :?: 

 
print语句下面应该有个空行(new line)

pep8 --show-source --show-pep8 test.py


推荐使用空格来进行缩进。

Tab应该只在现有代码已经使用tab进行缩进的情况下使用,以便和现有代码保持一致。

Python 3不允许tab和空格混合使用。

Python 2的代码若有tab和空格混合使用的情况,应该把tab全部转换为只有空格。

当使用命令行运行Python 2时,使用-t选项,会出现非法混用tab和空格的警告。当使用-tt选项时,这些警告会变成错误。强烈推荐使用这些选项!

每行最大长度(Maximum Line Length)
将所有行都限制在79个字符长度以内。

有时续行只能使用反斜杠才。例如,较长的多个with语句不能采用隐式续行,只能接受反斜杠表示换行:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

   
空行(Blank Line)
使用2个空行来分隔最高级的函数(function)和类(class)定义。

使用1个空行来分隔类中的方法(method)定义。

Imports
Imports应该分行写,而不是都写在一行,例如:
# 分开写
import os
import sys
# 不要像下面一样写在一行
import sys, os
这样写也是可以的:

from subprocess import Popen, PIPE
Imports应该写在代码文件的开头,位于模块(module)注释和文档字符串之后,模块全局变量(globals)和常量(constants)声明之前。


Imports应该按照下面的顺序分组来写:

标准库imports
相关第三方imports
本地应用/库的特定imports
不同组的imports之前用空格隔开。

Python有一种独一无二的的注释方式: 使用文档字符串.
文档字符串是包, 模块, 类或函数里的第一个语句.
这些字符串可以通过对象的__doc__成员被自动提取, 并且被pydoc所用.
(你可以在你的模块上运行pydoc试一把, 看看它长什么样).
我们对文档字符串的惯例是使用三重双引号”“”( PEP-257 ).
一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行).
接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐.
下面有更多文档字符串的格式化规范.
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass

   
代码规范:
http://nanshu.wang/post/2015-07-04/
https://www.douban.com/note/134971609/
https://lizhe2004.gitbooks.io/code-style-guideline-cn/content/python/python-pep8.html
http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/#comments

将notepad++ python语言默认的tab改成4个空格的方法:
设置->首选项->制表符设置->python->取消‘使用默认值’

其它代码规范标准和工具:
Google python style guide
Pylint,Pyflakes,Pychecker 等

三元操作符
x=0
y=-2
print x if x<y else y
输出-2

python不支持switch case
可以用if..elif..else 代替
或者用
def f(x):
    return {
        0:"first",
        1:"second",
        2:"third",
        3:"four"
    }.get(x, "error input")

   

定义常量,参考:http://www.malike.net.cn/blog/2013/11/03/python-constants/
class _const:
    class ConstError(TypeError): 
        pass
    class ConstCaseError(ConstError): 
        pass
    
    def __setattr__(self, name, value):
        if (self.__dict__.has_key(name)):
            raise self.ConstError, "Can't change const.%s" % name
        if not name.isupper():
            raise self.ConstCaseError, \
                  'const name "%s" is not all uppercase' % name
        self.__dict__[name] = value 
        
    def __delattr__(self, name):
        self.__dict__.has_key(name):
            raise self.ConstError, "Can't unbind const const instance attribute (%s)" % name

        raise AttributeError, "const instance has no attribute '%s'" % name
        

import sys
sys.modules[__name__] = _const()


使用const
import const
const.COMPANY = "NMG"



   
分享到:
评论

相关推荐

    Python for DevOps Learn Ruthlessly Effective Automation.pdf

    In this chapter, we draw on our decades of Python DevOps experience to teach only the elements of the language that you need. These are the parts of Python you use daily. They form the essential ...

    Effective-Robotics-Programming-with-ROS——中文学习笔记

    在开始深入学习《Effective Robotics Programming with ROS》之前,首先需要搭建一个合适的开发环境。本书的学习笔记主要基于ROS (Robot Operating System) Indigo版本进行讲解。为了能够顺利运行书中提供的示例代码...

    Use MySQL with Python - M. MOka

    learn to use many more advanced features of Python for MySQL that facilitate effective administration of your database through Python. Every chapter is illustrated with a project that you can deploy ...

    Mastering Python Data Visualization(PACKT,2015)

    Commencing with a chapter on the data framework, the book covers the complete visualization process, using the most popular Python libraries with working examples. You will learn how to use NumPy, ...

    Scientific.Computing.with.Python.3.2nd.Ed.epub

    Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, ...

    Machine.Learning.in.Python

    Title: Machine Learning in Python: Essential Techniques for Predictive Analysis Author: Michael Bowles Length: 360 pages Edition: 1 Language: English Publisher: Wiley Publication Date: 2015-04-20 ISBN...

    Fluent.Python.1491946008

    With this hands-on guide, you’ll learn how to write effective, idiomatic Python code by leveraging its best—and possibly most neglected—features. Author Luciano Ramalho takes you through Python’s...

    Numerical.Python.2nd.Edition

    scientific thinking is a fundamental requirement for effective computational work. Equally important is solid training in computer programming and computer science. The role of this book is to bridge ...

    Learning.Django.Web.Development

    Chapter 1. Introduction to Django Chapter 2. Getting Started Chapter 3. Code Style in Django Chapter 4. Building an Application Like Twitter Chapter 5. Introducing Hashtags Chapter 6. Enhancing the ...

    Django.Unleashed.0321985079.epub

    Chapter 1 Starting a New Django Project: Building a Startup Categorizer with Blog Chapter 2 Hello World: Building a Basic Webpage in Django Chapter 3 Programming Django Models and Creating a SQLite ...

    Selenium.Testing.Tools.Cookbook.2nd.Edition.178439251

    Chapter 1: Getting Started Chapter 2: Finding Elements Chapter 3: Working with Elements Chapter 4: Working with Selenium API Chapter 5: Synchronizing Tests Chapter 6: Working with Alerts, Frames, and ...

Global site tag (gtag.js) - Google Analytics