organized https://www.e-learn.cn/tag/organized zh-hans Python - Best/Cleanest way to define constant lists or dictionarys https://www.e-learn.cn/topic/3186206 <span>Python - Best/Cleanest way to define constant lists or dictionarys</span> <span><span lang="" about="/user/81" typeof="schema:Person" property="schema:name" datatype="">人盡茶涼</span></span> <span>2020-01-12 03:59:25</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>First time user on stack overflow and I'm excited to be here.</p> <p>INTRO: I recently began the magical adventure into the world of Python programming - I love it. Now everything has gone smoothly in my awkward transition from C, but I'm having trouble creating something which would be synonymous to a HEADER file (.h).</p> <p>PROBLEM: I have medium sized dictionaries and lists (about 1,000 elements), lengthy enums, and '#defines' (well not really), but I can't find a CLEAN way to organize them all. In C, I would throw them all in a header file and never think again about it, however, in Python that's not possible or so I think.</p> <p>CURRENT DIRTY SOLUTION: I'm initializing all CONSTANT variables at the top of either the MODULE or FUNCTION (module if multiple functions need it). </p> <p>CONCLUSION: I would be forever grateful if someone had come up with a way to CLEANLY organize constant variable's. </p> <p>THANK YOU SO MUCH!</p> <br /><h3>回答1:</h3><br /><p>Put your constants into their own module:</p> <pre><code># constants.py RED = 1 BLUE = 2 GREEN = 3 </code></pre> <p>Then import that module and use the constants:</p> <pre><code>import constants print "RED is", constants.RED </code></pre> <p>The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same.</p> <br /><br /><br /><h3>回答2:</h3><br /><p>Usually I do this:</p> <p>File: <strong>constants.py</strong></p> <pre><code>CONSTANT1 = 'asd' CONSTANT_FOO = 123 CONSTANT_BAR = [1, 2, 5] </code></pre> <p>File: <strong>your_script.py</strong></p> <pre><code>from constants import CONSTANT1, CONSTANT_FOO # or if you want *all* of them # from constants import * ... </code></pre> <p>Now your constants are in one file and you can nicely import and use them.</p> <br /><br /><br /><h3>回答3:</h3><br /><p>Make a separate file <code>constants.py</code>, and put all globally-relevant constants in there. Then you can <code>import constants</code> to refer to them as <code>constants.SPAM</code> or do the (questionable) <code>from constants import *</code> to refer to them simply as <code>SPAM</code> or <code>EGGS</code>.</p> <p>While we're here, note that Python doesn't support <em>constant</em> constants. The convention is just to name them in <code>ALL_CAPS</code> and promise not to mutate them.</p> <br /><br /><br /><h3>回答4:</h3><br /><p>If you want to mess with nested constants and don't like dicts, I came up with this fun solution: </p> <pre><code># Recursively transform a dict to instances of the desired class import json from collections import namedtuple class DictTransformer(): @classmethod def constantize(self, d): return self.transform(d, klass=namedtuple, klassname='namedtuple') @classmethod def transform(self, d, klass, klassname): return self._from_json(self._to_json(d), klass=klass, klassname=klassname) @classmethod def _to_json(self, d, access_method='__dict__'): return json.dumps(d, default=lambda o: getattr(o, access_method, str(o))) @classmethod def _from_json(self, jsonstr, klass, klassname): return json.loads(jsonstr, object_hook=lambda d: klass(klassname, d.keys())(*d.values())) </code></pre> <p>Ex:</p> <pre><code>constants = { 'A': { 'B': { 'C': 'D' } } } CONSTANTS = DictTransformer.transform(d, klass=namedtuple, klassname='namedtuple') CONSTANTS.A.B.C == 'D' </code></pre> <p>Pros:</p> <ul><li>handles nested dicts</li> <li>can potentially generate other types of dicts/classes</li> <li>namedtuples provide immutability for constants</li> </ul><p>Cons:</p> <ul><li>may not respond to .keys and .values if those are not provided on your klass (though you can sometimes mimic with ._fields and list(A.B.C))</li> </ul><p>Thoughts?</p> <p>h/t to @hlzr and you guys for the original class idea</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/11111632/python-best-cleanest-way-to-define-constant-lists-or-dictionarys</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/c-1" hreflang="zh-hans">c</a></div> <div class="field--item"><a href="/tag/header" hreflang="zh-hans">header</a></div> <div class="field--item"><a href="/tag/constants" hreflang="zh-hans">constants</a></div> <div class="field--item"><a href="/tag/organized" hreflang="zh-hans">organized</a></div> </div> </div> Sat, 11 Jan 2020 19:59:25 +0000 人盡茶涼 3186206 at https://www.e-learn.cn