Herramientas de usuario

Herramientas del sitio


wiki2:python:code_notes

Python snippets

Getters & setters

import flask
class MyFlask(flask.Flask):
    @property
    def static_folder(self):
        if self.config.get('STATIC_FOLDER') is not None:
            return os.path.join(self.root_path, 
                self.config.get('STATIC_FOLDER'))
    @static_folder.setter
    def static_folder(self, value):
        self.config.get('STATIC_FOLDER') = value

Ignore all warnings

import warnings
from exceptions import Warning
warnings.simplefilter('ignore', Warning)

Import a class from string

def dynamic_import(name):
    components = name.split('.')
    mod = __import__(components[0])
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

Tricks

# Different ways to test multiple
# flags at once in Python
x, y, z = 0, 1, 0
if x == 1 or y == 1 or z == 1:
    print('passed')
if 1 in (x, y, z):
    print('passed')
# These only test for truthiness:
if x or y or z:
    print('passed')
if any((x, y, z)):
    print('passed')

Conditional tricks (Short circuit)

You can use the conditional operators and and or for deciding how to execute code. Next piece won't print hola.

def foo():
    print('hola')
    
False and foo()

See the low level actions

We can see the low level actions of a function with the dis package:

>>> def func(a):
...     a += 10
...     return a
... 
>>> import dis
>>> dis.dis(func)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 (10)
              6 INPLACE_ADD         
              7 STORE_FAST               0 (a)
 
  3          10 LOAD_FAST                0 (a)
             13 RETURN_VALUE 
wiki2/python/code_notes.txt · Última modificación: 2020/06/20 10:02 (editor externo)