Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling types via their name as a string in Python

Tags:

python

getattr

I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in this question) but unless I'm missing something obvious I can't seem to use this with calling types.

e.g.:

In [12]: locals()['int']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

e:\downloads_to_access\<ipython console> in <module>()

KeyError: 'int'

In [13]: globals()['int']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

e:\downloads_to_access\<ipython console> in <module>()

KeyError: 'int'

getattr(???, 'int')...

What's the best way of doing this?

like image 295
mavnn Avatar asked Oct 30 '09 15:10

mavnn


2 Answers

There are locals,globals, and then builtins. Perhaps you are looking for the builtin:

import __builtin__
getattr(__builtin__,'int')
like image 134
unutbu Avatar answered Sep 30 '22 01:09

unutbu


You've already gotten a solution using builtins, but another worthwhile technique to hold in your toolbag is a dispatch table. If your CSV is designed to be used by multiple applications written in multiple languages, it might look like this:

Integer,15
String,34
Float,1.0
Integer,8

In such a case you might want something like this, where csv is a list of tuples containing the data above:

mapping = {
    'Integer': int,
    'String': str,
    'Float': float,
    'Unicode': unicode
}
results = []
for row in csv:
    datatype = row[0]
    val_string = row[1]
    results.append(mapping[datatype](val_string))
return results

That gives you the flexibility of allowing arbitrary strings to map to useful types. You don't have to massage your data to give you the exact values python expects.

like image 20
jcdyer Avatar answered Sep 30 '22 02:09

jcdyer