Is Python worth putting classes in different files?

I am a Java programmer and I have always created separate files for classes, I am trying to learn python and I want to learn it correctly. Is it worth it to put classes in different files in python, that is, one file contains only one class. I read on the blog that this is expensive because the permission of the operator . happens at runtime in python (this happens during Java compilation).

Note I read in other posts that we can put them in separate files, but they don’t mention if they are more expensive

+6
source share
1 answer

This is a little expensive, but not to the extent that you are likely to care. You can hide this extra cost by doing the following:

 from module import Class 

As then, the class will be assigned to a variable in the local namespace, that is, you do not need to search through the module.

In reality, however, this is unlikely to be important. The cost of finding something like this will be tiny, and you should focus on what makes your code the most readable. Separate classes for all modules and packages, as it is logical for your program, and as soon as it becomes clear.

If, for example, you use something repeatedly in a loop, which is the bottleneck for your program, you can assign it a local variable for this loop , for example:

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

Please note that such optimization is unlikely to be important, and you should only optimize where you have the evidence you need to do.

+8
source

Source: https://habr.com/ru/post/914956/


All Articles