Write idiomatic python(1)

The original text of this series of blog posts is from the book writing idiomatic python (writing idiomatic python) by jeff knupp. The copyright of the original book belongs to the original author.

About the if statement

  1. Avoid comparing directly with True, False or None. In python, the following conditions are treated as False:

    1. None

    2. False

    3. 0 for numeric types

    4. empty list or dict

    5. 0 value or when __len__ or __nonzero returns False

    All other cases will be treated as True, you can override the two built-in functions in e to customize how to return True or False.

    You can just write if foo: instead of if foo == True:

    The advantage of this is that after future refactoring, foo may become a value of type int and will never == True, just write if foo: without modifying the original function.

    There is a point to note here, that is the difference between == and is, == means whether the values ​​are equal, it calls _eq inside the class, is means whether they are the same object, that is, whether the two variables are the same Pointing to the same memory, is behaves like == in some places, but this is unreliable.

    Note that some cases must be compared with None, such as

    def insert_data(self, position=None):
        if position is None:

    Since 0 is also a valid value here, if position cannot be written directly:

    There is also a case that if you compare with None, you must use is or is not, do not use ==. (PEP8 regulations)

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324225948&siteId=291194637