A case against accessors in Python


I was asked by one of fellow devs why I use accessors for instance vars in Python. Because I’m used to accessors after coding in Ruby and Objective-C, I replied and went with my own business. But today a post by Dropbox about optimizing Python code popped into my head. It states that Python function calls are slow. I coded a small snippet to see how accessors perform compared to just accessing an instance variable.

Here it is:

400: Invalid request

The results are shocking:

Shire:proptest bilbo$ python proptest.py 
Without accessor: 0.0742480754852
With accessor: 0.279271841049

Accessor function is about 3.75 times slower than direct access. Now, while this may not matter in many cases I think this matters in case of a Web app, especially one written to handle heavy load. A millisecond more per request multiplied by a thousand of requests turns to a second. Funny that Tornado example code suggests using @property accessor function for DB connection in request handlers.

Tomek Wójcik

Developer, webmaster, part-time bassist, music addict.

BTHLabs owner and mastermind.