python syntactic suger

目录

      • 装饰器不改变原函数名
      • redis模块
            • StrictRedis
            • Redis
      • json解包float转str

装饰器不改变原函数名

修改最里层函数函数名,函数属性__name__重新赋值

# encoding=utf8

def deco1():
    def func1(func):
        def func2(*args, **kwargs):
            return func(*args, **kwargs)
        func2.__name__ = func.__name__
        return func2
    return func1

def deco2():
    def func1(func):
        def func2(*args, **kwargs):
            return func(*args, **kwargs)
        return func2
    return func1

@deco2()
def main(*args, **kwargs):
    pass

print(main.__name__)

@deco1()
def main(*args, **kwargs):
    pass

print(main.__name__)

>>> func2
>>> main

redis模块

2.9.1版本中,redis客户端有两个类,分别是StrictRedisRedis,相同的方法入参的顺序和命名有些区别,需要特别注意。

StrictRedis
def lrem(self, name, count, value):
Redis
def lrem(self, name, value, num=0):

json解包float转str

当json串中有浮点型数据时,不能精确解包

import json
# json.__version__ = 1.9
j = '''{"float": 9.9}'''
print json.loads(j)
>>> {u'float': 9.9000000000000004}

可以通过设置json.loads方法的parse_float参数把浮点型数据转化为字符串

print json.loads(j, parse_float=lambda x: x)
>>> {u'float': '9.9'}

json.loads函数中有说明,当parse_float != None时,解码时会把浮点型转换为整形。类似的,当设置了parse_int参数,也会做同样的预处理

print json.loads.__doc__
>>> ...
	``parse_float``, if specified, will be called with the string
    of every JSON float to be decoded. By default this is equivalent to
    float(num_str). This can be used to use another datatype or parser
    for JSON floats (e.g. decimal.Decimal).
    ...

json.decoder.py有以下转换

def JSONNumber(match, context):
    match = JSONNumber.regex.match(match.string, *match.span())
    integer, frac, exp = match.groups()
    if frac or exp:
        fn = getattr(context, 'parse_float', None) or float
        res = fn(integer + (frac or '') + (exp or ''))
    else:
        fn = getattr(context, 'parse_int', None) or int
        res = fn(integer)
    return res, None
pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber)

你可能感兴趣的:(python syntactic suger)