Mokus
Mokus

Reputation: 10400

Unable to get the built in type

I am trying to get a type from the __builtins__

if params.type in ["int", "long", "float"]:
     vtype = getattr( __builtins__, params.type )
     para = [vtype( para[0] )]

I am getting the following error:

Traceback (most recent call last):
  File "message_ajax_handler.py", line 267, in get
    vtype = getattr( __builtins__, subset[i] )
AttributeError: 'dict' object has no attribute 'int'

But when I test that in the command line

vtype = getattr( __builtins__, 'int' )

it is working. Where do I make the error.

Upvotes: 1

Views: 113

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123500

You should use the __builtin__ module instead:

import __builtin__

vtype = getattr(__builtin__, subset[i])

__builtins__ (with the s) can either be a dictionary or the module, depending on the context. The presence of this object is actually an implementation detail. From the __builtin__ documentation:

CPython implementation detail: Most modules have the name __builtins__ (note the 's') made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

Upvotes: 2

Related Questions