am i using hasattr() and getattr() wrong?

Fredrik Lundh fredrik at pythonware.com
Mon May 19 02:47:33 EDT 2003


"Doug" <doug at notAvalidEmail.com> wrote:

> the code that is related and doesnt seem to be working is:
>
> ---------
> passed_data  = cgi.FieldStorage()
>
> if hassattr(passed_data, "user"):
>     user1 = passed_data.getvalue("user")
> else:
>     user1 = "Null"
> -------------
>
> if i just do a straight assignment without any testing user1 gets assigned
> user's value. I realized later that i could simplify all of this by just
> using getattr(), but that also did not work. am i using these to functions
> wrongly? and if so can someone point me to a function or object.method i
> should be using to do this type of test?

cgi FieldStorage instances work like dictionaries, and support the
same methods, so this should work:

    if passed_data.has_key("user"):
        user1 = passed_data.getvalue("user")
    else:
        user1 = "Null"

see the "Using the cgi module" section in the library reference for
more information (including more has_key examples).

    http://www.python.org/doc/current/lib/node297.html

</F>








More information about the Python-list mailing list