Skip to content

Instantly share code, notes, and snippets.

@xxleyi
Last active June 17, 2019 01:18
Show Gist options
  • Save xxleyi/8547c07b0ab63f33c0defe85069ef45b to your computer and use it in GitHub Desktop.
Save xxleyi/8547c07b0ab63f33c0defe85069ef45b to your computer and use it in GitHub Desktop.
整理代码风格,并聚集一些短小精悍的代码实例

用代码说话。

@xxleyi
Copy link
Author

xxleyi commented Jun 17, 2019

EAFP vs. LBYL

It's easier to ask forgiveness than permission

Look before you leap

Generally EAFP is preferred, but not always.

  • Duck typing

If it walks like a duck, and talks like a duck, and looks like a duck: it's a duck. (Goose? Close enough.)

  • Exceptions

Use coercion if an object must be a particular type. If x must be a string for your code to work, why not call

str(x) 

instead of trying something like

isinstance(x, str)

EAFP try/except Example

You can wrap exception-prone code in a try/except block to catch the errors, and you will probably end up with a solution that's much more general than if you had tried to anticipate every possibility.

try: 
    return str(x) 
except TypeError: 
    ... 

Note: Always specify the exceptions to catch. Never use bare except clauses. Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.

@xxleyi
Copy link
Author

xxleyi commented Jun 17, 2019

Moral: don't use wild-card imports!

@xxleyi
Copy link
Author

xxleyi commented Jun 17, 2019

Packages

 package/
    __init__.py
    module1.py
    subpackage/
        __init__.py
        module2.py

@xxleyi
Copy link
Author

xxleyi commented Jun 17, 2019

Simple is Better Than Complex

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

—Brian W. Kernighan, co-author of The C Programming Language and the "K" in "AWK"

In other words, keep your programs simple!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment