[Tutor] importing

Emile van Sebille emile at fenx.com
Tue Dec 22 22:36:49 CET 2009


On 12/22/2009 1:14 PM Robert Johansson said...
> Hi all, suppose I need to import a module inside a class and that I need 
> to use it in to different methods. Is this is the way to do it?

Well, neither is really (see comments below).  I generally import only 
at the top of a module.  You can of course import within a method as 
needed, and I sometimes will do so if the imported module will only be 
used in the single method, but I tend not to as I've come over time to 
expect the imports at the top.

> 
>  
> 
> class test():
>     import time
>     def method1(self):
>         print 'method 1: ', time.clock()

this won't work -- time isn't within method1's accessible scope (local, 
global, builtin).  You could do test.time.clock() to access it, but 
importing globally won't confuse a reader by thinking it's something 
different.

Emile


>     def method2(self):
>         print 'method 2: ', time.clock()
>        
> 
> If I only need the module in one method should I then place it inside 
> that method or keep it outside?
> 
>  
> 
> class test():
>     def method1(self):
>         import time
>         print 'method 1: ', time.clock()
>     def method2(self):
>         print 'method 2: '



More information about the Tutor mailing list