6

So, I need to cast a value to a given type:

if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...

Is there a way to do that generically? E.g.:

type_instance = get_type_instance(type_name)
value = type_instance(value)

I'm using Python 2.7, but would be interested in a Python 3.X solution as well.

Update:

Here's the solution I'm using:

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe

This is just a toy parser. Don't use in production!

3 Answers 3

7

If you need only __builtins__ types you can do

value = getattr(__builtins__, type_name)(value)
Sign up to request clarification or add additional context in comments.

9 Comments

clever ... I'm not sure that I like it, but definitely clever (+1)
One problem with this approach is that it allows "eval" for the type_name The dict-based version allows (in fact, requires) programmer control over what conversions are allowed.
This is what I was after. I know it's not safe, but I was curious if it could be done. Thanks!
@larsmans, perhaps you could first check that type(getattr(__builtins__, type_name)) is type? That will prevent eval from being called.
@Kevin: that fixes some issues, but it's still hacky and unreliable. E.g., file is a type in Python 2, so this can be used to open files, not just lexically cast strings. (Also, the fact that enumerate and reversed are types is an implementation detail of CPython.)
|
7

Build a dict

TYPES = {
  'int' : int,
  'str' : str,
...
}

value = TYPES[type_name](value)

1 Comment

you should suggest reflection to the good people of python. somehow function parameters can be typed using strings, but this problem doesn't seem solved except through grow your own solutions like this which are tedious.
0

Since you specified float64 in an earlier version of the question, I assumed you were also interested in getting numpy types. If so, the following function should solve this:

def can_typecast(type, value):        
    try:
        tp = getattr(__builtins__, type)
    except AttributeError:
        try:
            np = __import__('numpy')
            tp = getattr(np, type)
            if not isinstance(tp, type):
                raise ValueError('type string is not a type')
        except AttributeError:
            raise ValueError('Invalid type specified')
        except ImportError:
            raise ValueError('Numpy not found')
    try:
        tp(value)
    except ValueError:
        return False
    return True

What this does is it first looks to see if the given type name can be resolved to a built-in type. If that fails, it looks to see if the type name can be found in numpy and if it is a valid type object and if so, tries the cast operation on that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.