Newbie questions for Python usage

Fredrik Lundh fredrik at pythonware.com
Tue Aug 22 19:08:30 EDT 2006


Caolan wrote:

>    1. I understand HOW to use the lambda operator, but WHY would you
>       want to use it? Can anyone please give an example of WHY you would
>       need it as opposed to just declaring a function either in the
>       local scope, or outside?

you don't *need* it, because

     callback = lambda arg: expression

is, for most practical purposes, the same thing as

     def callback(arg):
         return expression

(the only difference is that the __name__ attribute for the function 
objects will differ; all lambdas are named "<lambda>", while objects 
created by "def" have the original name.)

however, in some cases, it's may be convenient to use the lambda form, 
for stylistic reasons.

>    2. I would like to be able to declare as a member attribute a file
>       object, however because there is no declaration of variable types
>       like there is in C++, there doesn’t seem to be a way to do this
>       without first making a fobj = open(…) call. Is this true?

not sure what you mean, really -- attributes are not typed, and there's 
no way to "declare" them.  just assign to the attribute and be done with 
it.  if you want to use a placeholder value, use None:

     class foo:
         def __init__(self):
             self.file = None # not opened yet
         def open(self, name):
             self.file = open(name)

or

     class foo:
         file = None # shared placeholder
         def __init__(self):
             pass
         def open(self, name):
             self.file = open(name)

> Now for an os import question for Windows. I wish to automate the
> builds of VS.NET 2005 and I can do so by executing the os.system(...)
> command however I cannot see how to execute the vcvars32.cmd first to
> set environment variables and then execute the actual command-line for
> the build itself.

there's no easy way to do that: environment variables set by a sub- 
process isn't available to the main process.

the easiest way to do this might be to simply generate a short temporary 
BAT-file for each command, and do os.system() on that file:

     f = open("temp.bat", "w")
     f.write("@call vcvars32.bat\n")
     f.write("cl ...\n")
     f.close()

     os.system(f.name)

     os.remove(f.name)

</F>




More information about the Python-list mailing list