Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

However, if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?

Isn't this:

class SomeClass(object):

    def not_often_called(self)

   from datetime import datetime

   self.datetime = datetime.now()

more efficient than this?

from datetime import datetime

class SomeClass(object):

    def not_often_called(self):

         self.datetime = datetime.now()

1 Answer

0 votes
by (106k points)

Actually, yes there are many benefits of putting import statements at the top of a module some are as follows:-

  • When you put the imports at the top of the module it is fine, why because it is like a trivial cost where you only pay once and use as many times as you want.

  • Another reason why we put them at the top if you won’t put them at the top and you are putting the imports within a function will cause calls to that function in a longer time.

  • To make your code more efficient, you should put the import statement at the top.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...