py3k concerns. An example

Aaron Watters aaron.watters at gmail.com
Fri Apr 18 17:58:56 CEST 2008


Why is the migration to py3k a concern?
For example I have libraries which use string%dictionary
substitution where the dictionary is actually an object
which emulates a dictionary.  The __getitem__ for
the object can be very expensive and is only called when
needed by the string substitution.

In py3k string%dictionary is going away.  Why?
I have no idea.

The replacement is a string.format(...) method
which supports dictionary calling.
    string.format(**dictionary)
But dictionary
calling doesn't support dictionary emulation.
So in the example below the substitution works
but the call fails.

=== code

class fdict(dict):
    def __getitem__(self, item):
        return "got("+item+")"

def fn(**d):
    print d["boogie"]

if __name__=="__main__":
    fd = fdict()
    print "attempting string substitution with fake dictionary"
    print
    print "hello there %(boogie)s" % fd # <-- works
    print
    print "now attempting function call with fake dictionary"
    print
    fn(**fd) # <-- fails

=== output

% python2.6 dtest.py
attempting string substitution with fake dictionary

hello there got(boogie)

now attempting function call with fake dictionary

Traceback (most recent call last):
  File "dtest.py", line 17, in <module>
    fn(**fd)
  File "dtest.py", line 7, in fn
    print d["boogie"]
KeyError: 'boogie'

==== end of output

Consequently there is no simple way to translate
my code, I think.  I suspect you will find this kind of subtle
issue in many places.  Or worse, you won't find it
until after your program has been installed
in production.

It's a damn shame because
if string%dict was just left in it wouldn't be an issue.

Also, if making f(**d) support dict emulation
has any negative  performance implications
then I don't want it please.

sigh.  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=crack+open



More information about the Python-list mailing list