[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Checking For Pygame



Rikard Bosnjakovic wrote:

If Kris' function is called lots of times, issuing an "import pygame"
in it will consume unnecessary cpu-power. This is because as soon as
soon as the function exits, the pygame-module will be unloaded.

It's not clear what you mean by "unloaded" here. There's still a reference to it in sys.modules, so the module object will stay around for the life of the program.

Importing an already-loaded module isn't much more
work than reading a global -- they both require
a dictionary lookup. If the function uses the
module name more than a couple of times, it might
actually be faster overall, since reading a local
is *much* faster than reading a global (an array
index vs. a dictionary lookup).

If you really want to avoid executing the import
statement more than once, but still want it
loaded "on demand", you could do something like

  pygame = None

  def my_pygame_using_function():
    global pygame
    if not pygame:
      import pygame
    ...

But it's not clear whether this would be a net
win when you take the overhead of doing the test
into account.

I wouldn't worry about any of this unless
(a) your code is too slow AND (b) profiling
reveals that imports inside functions are
contributing significantly to this. In other
words, don't do premature optimisation.

--
Greg