Herramientas de usuario

Herramientas del sitio


wiki2:python:basic

¡Esta es una revisión vieja del documento!


Python basic recipes

Base lib

dicts

pop

>>> a = {'a': 1, 'b': 2}
>>> a.pop('a')
1
>>> a
{'b': 2}
>>> a.pop('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> a.pop('a', 0)
0

Custom parameters in logging

import logging
extra = {'app_name':'Super App'}

logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger = logging.LoggerAdapter(logger, extra)
logger.info('The sky is so blue')

logs (something like): 2013-07-09 17:39:33,596 Super App : The sky is so blue

Strings

Template

from string import Template
s = Template('$who is from $where')
 
d = {}
d['who'] = 'Bill'
d['where'] = 'Boston'
 
p = s.substitute(d)

Decorators

Class decorator

def decorator(cls):
    class Wrapper(object):
        def __init__(self,*args,**kwargs):
            self.wrapper = cls(*args,**kwargs)

        """
        def __getattr__(self, name, *args, **kwargs):
            print('Getting the {} of {}, {}, {}'.format(name, self.wrapped, repr(args), repr(kwargs)))
            return getattr(self.wrapped, name)
        """

        def __getattr__(self, attr):
            print attr
            def wrapper(*args, **kw):
                print('called with %r and %r' % (args, kw))
                return getattr(self.wrapper, attr)(*args, **kw)
            return wrapper

    return Wrapper

@decorator
class C(object):
    def method(self, x, y):
        print 'b'

if __name__ == '__main__':
    c = C()
    c.method(1,2)

Call several Python functions

#!/usr/bin/python
# -*- coding: utf-8 *-*
 
def funciona (a, b):
	return a + b
 
calls = [(funciona, {'a': 1, 'b': 3})]
 
for c in calls:
	print c[0](**c[1])

Paths

Path from where the script was called:

cwd = os.getcwd()

File name from a path:

os.path.basename(value)

Implementar tu propio Context Manager

class Saved():
    def __init__(self, cr):
        self.cr = cr
    def __enter__(self):
        self.cr.save()
        return self.cr
    def __exit__(self, type, value, traceback):
        self.cr.restore()

cr.translate(68, 68)
for i in xrange(6):
    with Saved(cr):
        cr.rotate(2 * math.pi * i / 6)
        cr.rectangle(-25, -60, 50, 40)
        cr.stroke()
wiki2/python/basic.1546001994.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)