Hacker News new | ask | show | jobs
by masklinn 5719 days ago
> and avoid many of the little python headaches that come up often like d['k'] vs d.k vs d('k').

When does that come up? d['k'] is a key access (to a collection), d.k is an attribute access (to an object) and d('k') is a method call. I'm not sure where the headache/confusion would be here, unless you're trying to do very weird things with Python (which you should not)

1 comments

They are all mapping functions, though. You have a key 'k', which is accepted by d and will return a unique result. Why should I have to care whether d is a collection, object, or method? In fact in many cases it's pretty easy to implement all three.

    class months(object):
        def __init__(self):
            m='jan feb mar apr may jun jul aug sep oct nov dec'.split(' ')
            n=range(1,13)
            self.__dict__.update(dict(zip(m,n)))
        def __getitem__(self, key):
            return self.__dict__[key]
        def __call__(self, key):
            return self.__dict__[key]
    
    d=months()
    
    print d['jan']  # 1
    print d('jan')  # 1
    print d.jan     # 1
> I'm not sure where the headache/confusion would be here, unless you're trying to do very weird things with Python (which you should not)
I never said there was confusion. The headache comes when you're trying decide whether to present an interface to a mapping function as a collection, an object, or a function.