Accessing dict keys like an attribute?

前端 未结 27 2522
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  余生分开走
    2020-11-22 05:00

    What would be the caveats and pitfalls of accessing dict keys in this manner?

    As @Henry suggests, one reason dotted-access may not be used in dicts is that it limits dict key names to python-valid variables, thereby restricting all possible names.

    The following are examples on why dotted-access would not be helpful in general, given a dict, d:

    Validity

    The following attributes would be invalid in Python:

    d.1_foo                           # enumerated names
    d./bar                            # path names
    d.21.7, d.12:30                   # decimals, time
    d.""                              # empty strings
    d.john doe, d.denny's             # spaces, misc punctuation 
    d.3 * x                           # expressions  
    

    Style

    PEP8 conventions would impose a soft constraint on attribute naming:

    A. Reserved keyword (or builtin function) names:

    d.in
    d.False, d.True
    d.max, d.min
    d.sum
    d.id
    

    If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore ...

    B. The case rule on methods and variable names:

    Variable names follow the same convention as function names.

    d.Firstname
    d.Country
    

    Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.


    Sometimes these concerns are raised in libraries like pandas, which permits dotted-access of DataFrame columns by name. The default mechanism to resolve naming restrictions is also array-notation - a string within brackets.

    If these constraints do not apply to your use case, there are several options on dotted-access data structures.

提交回复
热议问题