构建更好的API:使用namedtuple作为返回值。


一个好的API 应该返回具体类型(强)。 函数返回值相比dict,namedtuple 是更好的选择。


  • 简单使用
from collections import namedtuple 
# factory function
awesome_data = namedtuple("awesomeAPIDataModel", ["name", "age", "skill"])
print(awesome_data(1,2,3))
# awesomeAPIDataModel(name=1, age=2, skill=3)
  • 返回十分清晰的结果
from collections import namedtuple 
awesome_data = namedtuple("awesomeAPIDataModel", ["name", "age", "skill"])
def awesomeAPI():
    d = {}
    d['name'] = '小王'
    d['age'] = 12
    d['skill'] = {
        'os': 'Linux',
        'database': 'postgresql'
    }
    return awesome_data(**d)
role = awesomeAPI()
print(role.name, role[1], *role)
# 小王 12 小王 12 {'os': 'Linux', 'database': 'postgresql'}
print(role._asdict())
# OrderedDict([('name', '小王'), ('age', 12), ('skill', {'os': 'Linux', 'database': 'postgresql'})])
print(awesomeAPI())
# awesomeAPIDataModel(name='小王', age=12, skill={'os': 'Linux', 'database': 'postgresql'})
  • 默认值及更多扩展
from functools import partial
awesome_data = namedtuple("awesomeAPIDataModel", ["name", "age", "skill"])

# awesome_data.__new__ = partial(awesome_data.__new__, age = 15)
def awesomeAPI():
    d = {}
    d['name'] = '小王'
    d['age'] = 12
    d['skill'] = {
        'os': 'Linux',
        'database': 'postgresql'
    }
    return awesome_data(**d)
print(awesomeAPI())
# awesomeAPIDataModel(name='小王', age=15, skill={'os': 'Linux', 'database': 'postgresql'})
# TypeError: __new__() missing 1 required positional argument: 'age'
  • 扩展
from collections import namedtuple 
class awesome_data(namedtuple("awesomeAPIDataModel", ["name", "age", "skill"])):
    def __new__(cls, name, age, skill=None):
       return super(cls, awesome_data).__new__(cls, name, age, skill)
# JSON API WEB REST
def awesomeAPI():
    d = {}
    d['name'] = '小王'
    d['age'] = 12
    # d['skill'] = {
    #     'os': 'Linux',
    #     'database': 'postgresql'
    # }
    return awesome_data(**d)

    # DO NOT RETURN DICT


print(awesomeAPI())
# awesome_data(name='小王', age=12, skill=None)

参考: 哲的王经验分享


发布时间:
2018-08-18 11:53
分类:
标签: