简体   繁体   中英

Python dot notation dict breaks for hyphenated keys?

I'm using a Javascript-style dictionary as discussed here . Implementation:

class DotDict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

I've used this structure for some time with no issues, but recently needed a dictionary with a hyphenated key, like this:

    foo = DotDict()
    foo.a = 'a'        #Business as usual
    foo.a-b = 'ab'     #Broken

Assigning to foo.ab results in:

SyntaxError: can't assign to operator

This breaks because the '-' is seen as a minus operation and not as part of the key name. Is there another way to create a dictionary with dot-style member access?

ab is not a valid identifier in Python. Valid identifiers can consist of letters, numbers and underscores ( _ ). Any other character is not legal in variable name.

Is there another way to create a dictionary with dot-style member access?

There is no way of having dot-style access with keys that are not valid identifiers.

I'm not sure why you are surprised. In JavaScript, the same expression also throws an error:

>>> foo.a-b = 'ab'
ReferenceError: invalid assignment left-hand side

So, just as in JavaScript, fall back to:

>>> foo['a-b'] = 'ab'

That is not possible in a direct way. Best way would be to allow for mixed access - as you already do - and use it. Or, alternatively, use setattr()/getattr() , as Not_a_Golfer suggests .

well, it's sorta possible, but you really don't want to be doing that.

>>> class foo():
...    pass
... 
>>> f = foo()
>>> setattr(f, 'foo-bar', 1)
>>> getattr(f, 'foo-bar')
1

ab is not a valid identifier but is interpreted as an expression using the operator - . You can set such fields though: setattr(foo, 'a-b', 'ab')

它可能不适合您要实现的惯用语,但是如果您要用下划线替换连字符,则代码将起作用:

foo.a_b = 'ab'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM