0

Please help me on this simple question

x=1
if x["status"] == "Error":
     print "Fine"
elif x == 1:
     print "Good

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'int' object has no attribute '__getitem__'

The x is a return value from a function which could be an integer or a dictionary. I don't want my IF condition to alert me if it is vice versa..

Sathy
  • 303
  • 2
  • 8
  • 18

4 Answers4

4

One obvious solution is slightly modify your current code to handle the error:

try:
    if x["status"] == "Error":
        print "Fine"
except TypeError:
    if x == 1:
        print "Good"

Another option is to explicitly check whether x is an int or a dict:

if isinstance(x, dict) and x["status"] == "Error":
    print "Fine"
elif isinstance(x, int) and x == 1:
    print "Good"

although this removes some of the benefits of Python's duck typing; with the first version, it still works if the function providing x returns a float (x = 1.0), for example.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

You can check whether x is dictionary using isinstance.

if isinstance(x, dict) and x["status"] == "Error":
     print "Fine"
elif x == 1:
     print "Good

But, more preferably, I'd rather change the function to return one type.

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

Use type(x) == int to check if it is an int

Use type(x) == dict to check if it is a dict

And then appropriate action

  • Prefer `isinstance` to `type`: http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python – jonrsharpe Jan 09 '14 at 07:42
0

It most flexible to use duck-typing:

if x == 1:
    print("Good")
elif hasattr(x, '__getitem__') and x["status"] == "Error":
    print("Fine")

The above accepts any x that is integer or dictionary. In order to check the value of an item in a dictionary, one needs a _getitem__ method and the above checks for that and no more.

There are two reasons for duck-typing: one is that users may create their own classes and expect your code to work with them. The other is that official python classes may change. The latter, for example, is occurring with the python 2-->3 transition. Old code may have used isinstance(x, unicode) will fail under python3 while code that uses duck-typing will likely survive.

John1024
  • 109,961
  • 14
  • 137
  • 171