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?

5 Answers 5

4

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

type(x) == datetime.timedelta # or, the better Python practice isinstance(x, datetime.timedelta) 
Sign up to request clarification or add additional context in comments.

2 Comments

does not seem to work.Traceback (most recent call last): File "eval.py", line 14, in <module> test() File "eval.py", line 8, in test if isinstance(x, datetime.timedelta): AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
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 stackoverflow.com/questions/1087255/use-of-eval-in-python for details.
1

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

>>> type(x) == timedelta True 

Comments

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 

Comments

0

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

Comments

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.