theAlse
theAlse

Reputation: 5747

Convert string variables into other types

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?

Upvotes: 0

Views: 253

Answers (5)

sashimi
sashimi

Reputation: 843

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

Upvotes: 0

The Dark Knight
The Dark Knight

Reputation: 5585

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

Upvotes: 1

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

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

type(x) == datetime.timedelta

# or, the better Python practice

isinstance(x, datetime.timedelta)

Upvotes: 4

stein
stein

Reputation: 180

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

Upvotes: 0

Janne Karila
Janne Karila

Reputation: 25197

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

>>> type(x) == timedelta
True

Upvotes: 1

Related Questions