简体   繁体   English

如何避免在Python中对大量的dict键字符串进行硬编码

[英]How to avoid hard-coding tons of dict key strings in Python

May be it is a common question, but I am new in python! 可能是一个普遍的问题,但是我是python新手!

I am working on some libraries that handle json queries and asked myself if there is some best practice to avoid hard-coding tons of json keys like: 我正在处理一些处理json查询的库,并问自己是否有最佳实践,以避免对大量json键进行硬编码,例如:


# just an example..
var1 = response.json()["ACRI"]["message"]["title"]
var2 = response.json()["ACRI"]["message"]["content"]
var3 = response.json()["ACRI"]["message"]["meta"]["timestamp"]

when I saw it, it didn't likes me and I created a class with constants like: 当我看到它时,它不喜欢我,因此我创建了一个具有如下常量的类:


class _const:
    class headers:
        X_Auth_Token = "X-Auth-Token"
        X_Username = 'X-Username'
        X_Password = 'X-Password'

    class params:
        ID = "DocumentID"
        Symbols = "Symbols"
        ACRICode = "ACRICode"rketSegmentID"
        entries = "entries"
        depth = "depth"
        date = "date"
        meta = "meta"
        timestamp = "timestamp"
        message = "message"
        # ...

Is that a good practice? 这是个好习惯吗? Is there something I don't understanding about python compiler? 关于python编译器,我是否不了解?

Thanks 谢谢

edit: I'm facing performance and/or memory consumption best practices especially 编辑:我正在面对性能和/或内存消耗的最佳做法,尤其是

The performance should be least of your concerns , the maintainability is more important. 性能应该是您最不关心的问题 ,可维护性更为重要。 A good reason to use a symbolic name for a string is that you cannot typo it that easily then, cf 为字符串使用符号名的一个很好的理由是,您不能轻易地对它打错字,参见

KEY_SYMBOLS = "Symbols"

foo[KEY_SYMOBLS]

vs

foo["Symobls"]

An IDE or a linter can find the former typo and highlight it even before running the code, but not so likely the latter one. IDE或linter甚至可以在运行代码之前找到前一种错字并突出显示它,但不太可能是后者。


When it comes to performance the most performant Python code is the one that does not store strings in variables. 在性能方面,性能最高的Python代码是将字符串存储在变量中的代码。 Upon compilation the distinct uses of the same string within the same module are merged to reference just one string constant: 编译后,将同一模块中相同字符串的不同用法合并为仅引用一个字符串常量:

>>> 'foo' is 'foo'
True

Still, the point raised in Chepner's answer remains: you need not resolve subdictionaries from the root unnecessarily. 尽管如此,切普纳答案中提出的观点仍然是:您不必从根本上解决子词典。

Your initial strategy follows Zen of Python very well. 您的初始策略非常适合Python Zen It is very readable, and anyone who uses Python will understand it right away. 它具有很高的可读性,使用Python的任何人都会立即理解它。 Your second example, however, is overly complicated, and difficult to understand. 但是,您的第二个示例过于复杂,难以理解。

That said, it is possible to parse json so that it becomes an object with attributes instead of a dict with keys. 也就是说,可以解析json,使其成为具有属性的对象,而不是具有键的字典。 Your code would then look something like this: 您的代码将如下所示:

import json
from collections import namedtuple

x = json.loads(response, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

var1 = x.ACRI.message.title
var2 = x.ACRI.message.content
var3 = x.ACRI.message.meta.timestamp

Alternatively, define a simple class that takes care of it: 或者, 定义一个简单的类来处理它:

import json

class x(object):
    def __init__(self, j):
        self.__dict__ = json.loads(j)

var1 = x.ACRI.message.title
var2 = x.ACRI.message.content
var3 = x.ACRI.message.meta.timestamp

Each nested dict is a dict you can store a reference to. 每个嵌套字典都是可以存储引用的字典。

resp = response.json()["ACRI"]["message"]
var1 = resp["title"]
var2 = resp["content"]
var3 = resp["meta"]["timestamp"]

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

相关问题 避免在 Python 中硬编码文件路径的方法 - Methods to avoid hard-coding file paths in Python 如何避免在webapp模板中硬编码网址 - how to avoid hard-coding urls in webapp templates Python / Matplotlib - 如何在不进行硬编码的情况下计算/绘制导数? - Python / Matplotlib - How to compute/plot derivative without hard-coding it? 如何避免将多个元素硬编码到我的 Django model 中? - How can I avoid hard-coding multiple elements into my Django model? Sqlalchemy:在查询中参考当前 class 名称以避免硬编码 - Sqlalchemy: Refer to current class name in query to avoid hard-coding 如何在python脚本的条件下避免硬编码 - How to avoid hard coding in if condition of python script 如何在 python 中动态导入模块而不是硬编码导入? - How can you dynamically import modules instead of hard-coding import in python? 如何让 Python 在没有硬编码路径名的子文件夹中查找文件? - How to have Python find files in a subfolder without hard-coding path names? 在 python 脚本中硬编码 html 代码的正确方法? - Correct way of hard-coding html code in python script? 如何以可移植的方式将tox指向所有python版本(例如,不对tox.ini中的路径进行硬编码)? - How can I point tox to all python versions in a portable way (eg. without hard-coding the paths in tox.ini)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM