Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 3432

How to use @property decorator correctly in python 3?

I have method annotated with @property in athleteModel.py script:

@property
def get_from_store():
    with open(athleteFilePath,'rb') as pickleFile:
        athleteMap = pickle.load(pickleFile)
    print('Loaded athleteMap ',athleteMap)
    return athleteMap

I use this method in another script:

from athleteModel import get_from_store

athletes = get_from_store
print(yate.u_list(athletes[athName].sortedTimes))

At last line (print method) I get exception:

TypeError: 'function' object is not subscriptable 
      args = ("'function' object is not subscriptable",) 
      with_traceback = <built-in method with_traceback of TypeError object>

What is wrong in my code?

Upvotes: 3

Views: 1316

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121276

@property only works on methods, not on functions.

get_from_store is not a method, it is a function. A property object act as a descriptor object and descriptors only work in the context of classes and instances.

In your case there is no need to make get_from_store a property, really. Remove the @property decorator and just use it like a function:

athletes = get_from_store()

You cannot otherwise make top-level functions act like attributes.

Upvotes: 4

Related Questions