On Sun, Feb 1, 2009 at 11:43 PM, Taskinoor Hasan <taskinoor.ha...@csebuet.org> wrote: > Can anyone explain what is the necessity of executing whole script when > importing. Isn't it enough to just put the module name in the namespace and > execute when some function is called?
I'm not sure if I'm going to explain this right-- so bear with me. The code: def something(other): return other + 1 Doesn't exist until that def statement is executed. "def", "class" and such are not magical and immediately register something somewhere. Its a statement that has to be executed to get a result, and that result is bound as an assignment to the name specified. Its not really all that different from: something = lambda other: other + 1 It can't pick through the top level instructions to determine what to execute if imported vs run, as every statement has the possibility of producing some binding of name to value and until you go and execute it you won't know. You may do something like: try: import blah except: blah = None You have to execute all of that to get a value for 'blah'. In Python, there's nothing really special about a function vs any other value. They are all objects that are assigned to a name in a given namespace. You can do dynamic things at the top level to result in different things being bound to the modules namespace based upon the statements and expressions evaluated. Does that make sense? If not someone else'll have to explain :) --Stephen -- http://mail.python.org/mailman/listinfo/python-list