newbie apply() question

xtian at hyperactive.co.nz xtian at hyperactive.co.nz
Tue Jul 3 02:09:41 EDT 2001


On Tue, 03 Jul 2001 04:37:54 GMT, "Aaron Edsinger"
<edsinger at ai.mit.edu> wrote:

>hi.  i'm stumped on something that seems easy.  why doesn't this work:
>
>x=4
>apply(sys.stdout.write,x) #fails
>apply(sys.stdout.write,(x,)) #fails
>
>is there a way to make this work?
>
>thanks,
>    aaron

If you try to run this by itself (without doing anything else), it
fails with the traceback

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in ?
    apply(sys.stdout.write,(x,))
NameError: name 'sys' is not defined

What this means is that Python has tried to look at the object
referred to by 'sys' to find out what it's 'stdout' attribute is, and
discovered that the name 'sys' hasn't been set (or 'bound') yet.

Names can be bound in quite a few ways, the main one being assignment.
In this case, you want the binding 'sys' to refer to the sys module -
to bind the name 'sys' to the sys module, you need to import the
module with...

import sys

...at the start of your script (or at least before the first use of
sys). Incidentally, when importing a module, you can pick the name you
want to bind it to; if you'd had (I'm assuming Python 2.0 or up
here)...

import sys as fish

...at the start, you could then use...

apply(fish.stdout.write,(x,)) 
# this is the form that works, by the way.

...just as well.

(I'm assuming that your confusion was caused by not understanding what
was meant by NameError. If I sounded patronising - sorry! Also, as a
general hint, if you're asking people for help working out what's
causing an error, post the traceback (long error message) - they're
very useful in diagnosing the problem.)

The best explanation of name binding of which I know is the effbot
guide to Python objects:
http://effbot.org/guides/python-objects.htm

Any others around?

So, to wrap up, you need an 'import sys' at the start.

(Good choice trying Python - it's so cool!)

Hey - I feel like the Martellibot - that was long.

xtian

Question 6:
I'm trying to implement a Content Management System. Should I use
Scissors, XML, or dirt?



More information about the Python-list mailing list