0

I have a class which hold some variables as strings. e.g.

x = "1"
y = "2.0"
z = "timedelta(seconds=10)"

As you can see above the variables are actually int/float/timedelta-types. I need to return these variables with their real type. (x should be returned as a int, y should be returned as a float, z should be returned as datetime.timedelta)

I was thinking of changing the getattr and try to find out the type before returning the value, but the small test I did, does not seem to work:

from datetime import datetime, timedelta

def test():
    string = "timedelta(seconds=10)"
    x = eval(string)
    print x
    print type(x)
    if type(x) == 'datetime.timedelta':
        print "YES"
    else:
        print "NO"

The output is:

0:00:10
<type 'datetime.timedelta'>
NO

why is the if-case returning false? is there a better way to return these variables with the real type?

theAlse
  • 5,577
  • 11
  • 68
  • 110

5 Answers5

4

Because type(x) returns type not string. Instead use:

type(x) == datetime.timedelta

# or, the better Python practice

isinstance(x, datetime.timedelta)
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
  • does not seem to work.Traceback (most recent call last): File "eval.py", line 14, in test() File "eval.py", line 8, in test if isinstance(x, datetime.timedelta): AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' – theAlse Oct 18 '12 at 07:56
  • It's because you have `from datetime import datetime` and in my example I refer to `timedelta` via a full "module path". Just replace `datetime.timedelta` with `timedelta`. And note that using `eval()` is considered a VERY bad practice in Python, see http://stackoverflow.com/questions/1087255/use-of-eval-in-python for details. – Zaur Nasibov Oct 18 '12 at 08:00
1

You are comparing a type and a string. Try this instead:

>>> type(x) == timedelta
True
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
1

you are comparing string with type , hence it is returning false.

It's best if you use :

 isinstance(x, datetime.timedelta)

See this piece of code, it clearly tells you how to check for type :

    >>> foo = {}

    >>> type(foo)
    <type 'dict'>

    >>> class MyDict(dict):
    ...     pass

    >>> bar = MyDict()

    >>> type(bar)
    <class '__main__.MyDict'>

    >>> type(bar) == dict
    False                     # Unexpected result

    >>> isinstance(bar, dict)
    True                      # Expected result
The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
0

the type of 'datetime.timedelta' is str. I think you mean to do if type(x) == timedelta:, which will do the correct typecheck.

stein
  • 180
  • 7
0

brief answer(I think this is what you want just for this question):

1.you import the timedelta,and it's name timedelta._name_ is a string 'timedelta'.

2.x = eval(string),here x's type is timedelta which you imported aboved.

so, it's simple,just compare type(x)._name_ with timedelta._name_ if you just want compare them with string :)

sashimi
  • 793
  • 2
  • 8
  • 14