On Mon, Feb 2, 2009 at 1:58 PM, Stephen Hansen <apt.shan...@gmail.com>wrote:
> 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 :) It make sense :-). So my reasoning......let A is imported in B, i.e. name A is put in B's namespace. When we call something like A.a then the interpreter first resolve A in B's namespace, then to get a, it need to look up A's namespace. And there is no way to populate A's namespace without executing A, and as all statements, including 'def', 'class' etc., are treated in the same way, whole script need to be executed. So whether a script can be imported as module or not is mainly dependent on how the script is written and largely on the intention of the coder. > > > --Stephen > -- > http://mail.python.org/mailman/listinfo/python-list >
-- http://mail.python.org/mailman/listinfo/python-list