[Tutor] this module
bob gailer
bgailer at gmail.com
Sun Aug 9 12:44:08 CEST 2009
Alan Gauld wrote:
>
> "Mark Young" <marky1991 at gmail.com> wrote
>
>> Thanks everybody, I didn't know modules ran code when you imported
>> them, I
>> just thought they defined the functions, etc. in them.
>
> They do that too.
> But in Python a function definition is created by running the code!
>
> So you write
>
> def foo():
> return 42
>
> To define foo you need to execute those two lines of code.
> The result is that you create a function object.
>
> So when you import a moduile it runs all of the code in there
Almost. It runs all the top-level code.
def foo():
print 3
def foo(): will run, defining the function foo
print 3 will NOT run
unless some other top-level code CALLs foo such as
foo()
> most of the code usually consists of function and variable
and class
> definitions.
> But it can be anything at all.
>
Note also that "usually" is very hard to measure unless you read and or
write many many modules.
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list