Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it costly in Python to put classes in different files?

I am a Java programmer and I have always created separate files for Classes, I am attempting to learn python and I want to learn it right. Is it costly in python to put Classes in different files, meaning one file contains only one class. I read in a blog that it is costly because resolution of . operator happens at runtime in python (It happens at compile time for Java).

Note: I did read in other posts that we can put them in separate files but they don't mention if they are costlier in any way

like image 716
Alwin Doss Avatar asked May 05 '12 09:05

Alwin Doss


1 Answers

It is slightly more costly, but not to an extent you are likely to care. You can negate this extra cost by doing:

from module import Class

As then the class will be assigned to a variable in the local namespace, meaning it doesn't have to do the lookup through the module.

In reality, however, this is unlikely to be important. The cost of looking up something like this is going to be tiny, and you should focus on doing what makes your code the most readable. Split classes across modules and packages as is logical for your program, and as it keeps them clear.

If, for example, you are using something repeatedly in a loop which is a bottleneck for your program, you can assign it to a local variable for that loop, e.g:

import module

...

some_important_thing = module.some_important_thing

#Bottleneck loop
for item in items:
   #module.some_important_thing()
   some_important_thing()

Note that this kind of optimisation is unlikely to be the important thing, and you should only ever optimise where you have proof you need to do so.

like image 83
Gareth Latty Avatar answered Oct 13 '22 00:10

Gareth Latty