简体   繁体   English

编写一个返回 dict 或 OrderedDict 的函数会是 Pythonic 吗?

[英]Would it be pythonic to write a function which either returns dict or OrderedDict?

I am in doubt if a regular dict and an OrderedDict objects are truly interchangeable in a sense that the same function or method could return once a dict and other times an OrderedDict depending on the input arguments or for example in case of a class method depending on some other internal class instance attributes.我怀疑常规 dict 和 OrderedDict 对象是否真的可以互换,因为相同的函数或方法可以根据输入参数返回一次 dict 和其他时间返回 OrderedDict ,或者例如在类方法的情况下取决于其他一些内部类实例属性。 If returning an OrderedDict would be significantly more costly than returning just a regular dict which should suffice as well why doing it the hard way?如果返回一个 OrderedDict 比只返回一个普通的 dict 成本要高得多,这应该足够了,为什么要这样做呢? Would it be pythonic to create such a function or menthod?创建这样的函数或方法会是 pythonic 吗? I use Python 2.7.我使用 Python 2.7。

I have seen "Why should functions always return the same type?"我看过“为什么函数应该总是返回相同的类型?” and I felt my case is more special and less obvious to the unseasoned eye.而且我觉得我的情况更特别,对于没有经验的人来说不太明显。

Python uses duck typing. Python 使用鸭子类型。 as long as an object presents the necessary interface required for an action, the type of object is irrelevant.只要对象提供操作所需的必要接口,对象的类型就无关紧要。 An OrderedDict will present all the interfaces a dict would, so what the function returns is irrelevant. OrderedDict将显示dict将出现的所有接口,因此函数返回的内容无关紧要。 It'll be up to whatever uses what was returned.这取决于使用返回的内容。 You should figure out the implementation of the use not the returning function.您应该弄清楚 use 的实现而不是返回函数。

What's your use case?你的用例是什么? Detailing that would help in suggesting an answer or alternatives.详细说明将有助于建议答案或替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 /graphql/ 处的 AssertionError 查询字段必须是一个以字段名称作为键的映射(dict / OrderedDict)或返回此类映射的 function - AssertionError at /graphql/ Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping 编写函数以传入参数或参数元组的大多数pythonic方式 - Most pythonic way to write a function to either pass in arguments or a tuple of arguments 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? to_dict() function 从 dataframe 而不是 OrderedDict 创建一个列表 - to_dict() function makes a list from dataframe instead of OrderedDict 用函数总和更新字典的python方式 - pythonic way to update dict with sum of function Python dict / OrderedDict:将函数分配给值而不立即执行 - Python dict / OrderedDict: Assign function to value without executing it immediately 返回列表的正面或负面元素的函数 - Function which returns either the positive or negative elements of the list 写一个constrain()函数的pythonic方法 - a pythonic way to write a constrain() function 编写此函数的更多pythonic方法 - More pythonic way to write this function OrderedDict与Python中的Dict - OrderedDict vs Dict in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM