[Tutor] is it legal to have a class within a def

Kent Johnson kent37 at tds.net
Thu Jan 3 20:47:27 CET 2008


johnf wrote:
> So I started thinking why would I need the class outside of the function.  If 
> I instead used "import class" would I get a performance improvement?  The 
> function creates an instance each time it is required and then releases and 
> closes.  
> 
> I am very interested in this possible difference between importing the class 
> vs using the inline class.

There is another possibility which is probably what I would do - just 
define the class at global scope in the same module that uses it. 
Instead of

def f():
   class Z(object):
     pass
   # do something with Z

write

def f():
   # do something with Z

class Z(object):
   pass


I.e. you don't have to put the class def'n in a separate module.
Kent


More information about the Tutor mailing list