[Python-Dev] Set the namespace free! (original) (raw)

John Nagle nagle at animats.com
Thu Jul 22 20:04:26 CEST 2010


On 7/22/2010 5:45 AM, python-dev-request at python.org wrote:

Message: 10 Date: Thu, 22 Jul 2010 16:04:00 +0200 From: Bartosz Tarnowski<bartosz-tarnowski at zlotniki.pl> To:python-dev at python.org Subject: [Python-Dev] Set the namespace free! Message-ID:<4C484FD0.2080803 at zlotniki.pl> Content-Type: text/plain; charset=UTF-8; format=flowed

Hello, guys. Python has more and more reserved words over time. It becomes quite annoying, since you can not use variables and attributes of such names. Suppose I want to make an XML parser that reads a document and returns an object with attributes corresponding to XML element attributes: > elem = parsexml("") > print elem.param What should I do then, when the attribute is a reserver word?

 That's a misuse of attributes.  When you need objects with

unconstrained fields, inherit them from "dict", and write

 print(elem['param'])

This protects you not only from name clashes, but from difficulties with names that don't fit Python attribute syntax. (BeautifulSoup occasionally crashes due to this problem when parsing malformed HTML). You can still provide a "getattr" function, if desired, for convenient access to commonly used attributes.

 Using "setattr" to set attributes, where the attribute string

comes from an external source, can create a security hole. Remember that you can override functions on an object, for that object only, by setting an attribute. This offers the opportunity for an attack similar to SQL injection. Think about what this can do to a parser that has and calls a method "display" for each element:

<element display='lambda x : subprocess.Popen("rm -r -f /")'>

You are pwned.

            John Nagle


More information about the Python-Dev mailing list