Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Tricks

Python Tricks

Python está lleno de pequeños "trucos" con los que puedes optimizar tu código y hacerlo más legible. Tal vez conozcas algunos, pero seguro aprenderás algo nuevo y útil.

Python Pereira

April 24, 2019
Tweet

More Decks by Python Pereira

Other Decks in Technology

Transcript

  1. Make sure you use assertions “The proper use of assertions

    is to inform developers about unrecoverable errors in a program”.
  2. Common errors with assertions 1. Don’t use it for data

    validation, use regular Exceptions. 2. Asserts which never fail.
  3. Context Managers, when to use? • Safe acquisition and release

    of system resources. • Avoids resource leaks and makes code easier to read.
  4. String formatting, which to use? if strings_are_user_supplied: use = “TemplateStrings”

    elif PYTHON_VERSION >= 3.6: use = “Interoplation” else: use = “New style”
  5. Functions are first-class citizens 1. Functions are objects (everything is).

    2. Functions can be stored in data structures. 3. Functions can be passed to other functions! (high-order functions). 4. Functions can be nested. 5. Functions can capture local state. 6. Objects can behave like functions.
  6. Lambda functions • Shortcut for declaring small anonymous functions. •

    Restricted to a single expression. • Don’t go crazy with them
  7. Decorators • Allow you to extend and modify the behavior

    of a callable without permanently modifying the callable itself. • Any sufficiently generic functionality is a great candidate: ◦ Logging ◦ Enforcing access control and authentication ◦ Instrumentation and timing functions. ◦ Rate-limiting. ◦ Caching. ◦ More!
  8. *args and **kwargs • You can create more flexible APIs

    with variable number of arguments. • Essential for decorators and other wrappers. • If we call the function with additional arguments, args will collect them as a tuple. • Likewise, kwargs will collect extra keyword arguments as a dictionary.
  9. Every class needs a __repr__ • Python fallsback to repr

    if str is not defined. • print and format use str. • str should be readable. • repr should be unambiguous.
  10. Defining your own Exceptions • First of all, use Exceptions!

    • Asking for permission instead of forgiveness. • Custom exceptions make it clearer. • You can use inheritance to have a hierarchy.
  11. Cloning objects • Beware of shallow copying. • Use copy

    module for deep copies. • It works even for arbitrary objects
  12. Abstract classes • Abstract classes are useful. • Python is

    not very strict. • We are human. • The sooner we fail, the better.
  13. Abstract classes • ABC ensures that derived classes implement methods

    from the base class. • Using ABC helps avoiding bugs and makes class hierarchies easier to maintain.