1 Replies - 1091 Views - Last Post: 09 December 2013 - 02:26 AM Rate Topic: -----

#1 MentalFloss  Icon User is offline

  • .
  • member icon

Reputation: 577
  • View blog
  • Posts: 1,500
  • Joined: 02-September 09

[Help] Calling eval() on an object

Posted 09 December 2013 - 01:38 AM

[SOLVED]

I'm not getting the results I expect when I am calling eval() for an object. I created this:

class Product(object):
    def __init__(self, name, price):
        self.name = name
        self.price = price
        
    def __str__(self):
        return format("name=%s,price=%.2f" % (self.name,self.price))
        
    def __repr__(self):
        return format("Product(%r,%.2f)" % (self.name,self.price))



I'm to understand from the documentation (2.7) that eval() will retrieve from __repr__() on that object. The thing is, the hashes are not matching up. Let me show you what I mean.

>>> from repr_test import Product
>>> p = Product('widget',1.0)
>>> p
Product('widget',1.00)
>>> eval('p')
Product('widget',1.00)
>>> # they are the same right?
... 
>>> eval(repr(p))
Product('widget',1.00)
>>> a = eval(repr(p))
>>> hash(p) == hash(a)
False
>>> a.__dict__
{'price': 1.0, 'name': 'widget'}
>>> p.__dict__
{'price': 1.0, 'name': 'widget'}
>>> id(a)
139639415770384
>>> id(p)
139639415769552
>>> hash(a)
8727463485649
>>> hash(p)
8727463485597
>>> # now i will call eval on the object.
... 
>>> b = eval('p') # as you remember, this returned Product('widget',1.00)
>>> hash(p) == hash(B)/>/>/>
True
>>> # What is going on?



Please help. I am very confused.

This post has been edited by MentalFloss: 09 December 2013 - 05:46 PM


Is This A Good Question/Topic? 0
  • +

Replies To: [Help] Calling eval() on an object

#2 jon.kiparsky  Icon User is offline

  • Screw Trump (before he screws you)
  • member icon


Reputation: 10625
  • View blog
  • Posts: 18,185
  • Joined: 19-March 11

Re: [Help] Calling eval() on an object

Posted 09 December 2013 - 02:26 AM

Quote

# What is going on?


Look at the types.


>>> class Foo:
...     def __init__ (self, val):
...             self.val = val
...     def __repr__(self):
...             return self.val
... 

>>> f1 = Foo('foo')
>>> type(eval('f1'))
<type 'instance'>
>>> type(f1)
<type 'instance'>
>>> f1 == eval('f1')
True
>>> 


So it's not surprising that

>>> hash(f1) == hash (eval('f1'))
True



eval ('f1') returns the object f1. This makes sense. Consider the documentation case
>>> x = 1
>>> print eval('x+1')
2


This could only work if

>>> print eval('x')
1


(that is, it returns the number 1, not the string representation '1')

This post has been edited by jon.kiparsky: 09 December 2013 - 02:26 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1