Could not import the module (but not use it) in Python?

I run the site using Django, and I import ipdb at the beginning of almost all of my scripts to simplify debugging. However, most of the time I never use functions from a module (only when I am debugging).

Just wondering, will it reduce my work? Just when I want to create a breakpoint, I prefer to write:

ipdb.set_trace() 

Unlike:

 import ipdb; ipdb.set_trace() 

But I saw a second example, made in several places, which makes me wonder if this is more efficient ...

I just don't know how to import python modules for efficiency (assuming you don't use module methods in your script).

+7
source share
3 answers

As @wRAR mentioned, loading a module can mean executing any amount of code, which can take some time. On the other hand, the module will be loaded only once, and any subsequent import attempt will find the module present in os.sys.modules and refer to it.

In the Django environment in debug mode, the modules are removed from the Django AppCache and are actually re-imported only when they are changed, which you probably will not do with ipdb , so this should not be a problem in your case.

However, in cases where this would be a problem, there are some ways around this. Suppose you have a custom module that you use to load anyway, you can add a function to it that imports ipdb only when you need it:

 # much used module: mymodule def set_trace(): import ipdb ipdb.set_trace() 

in the module you want to use ipdb.set_trace :

 import mymodule mymodule.set_trace() 

or, at the top of your module, use the __debug__ cross-module __debug__ :

 if __debug__: from ipdp import set_trace else: def set_trace(): return 
+4
source

Short answer: usually not

Long answer:

It will take time to load the module. This may be noticeable if you are loading python from a network drive or other slow source. But if you run straight from the hard drive, you will never notice.

As @wRar points out, importing a module can execute any amount of code. You can use any code that you want to execute when the module starts. However, most modules avoid running unreasonable amounts of code at startup. So this is probably not a huge reason.

However, importing very large modules, especially those that also lead to the import of a large number of c-modules, will take time.

Therefore, it will take time to import, but only once for each module. If you import modules at the top of your modules (as opposed to functions), this only applies to startup time. Basically, you are not going to get a lot of optimization by eliminating the import of modules.

+2
source

Import of a module, but not using it, is reduced (system):

  • It takes time to import the module
  • Imported modules use memory

While the first point makes your program run slower, the second point can make ALL of your programs slower, depending on the total amount of memory that you have on your system.

0
source

All Articles