2014-01-17 35 views
0

我試圖從__builtins__無法獲取內建類型

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

得到一個類型,我收到以下錯誤:

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' 

但是當我測試,在命令行

vtype = getattr(__builtins__, 'int') 

它正在工作。我在哪裏犯錯誤。

+2

實際的代碼和回溯中的代碼是不同的。哪一個是正確的? – thefourtheye

回答

2

您應該使用__builtin__ module代替:

import __builtin__ 

vtype = getattr(__builtin__, subset[i]) 

__builtins__(與s)可以是一個字典或模塊,根據上下文無論是。這個對象的存在實際上是一個實現細節。來自__builtin__文檔:

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.

+0

你在'getattr'中仍然有'__builtins__':P –

+0

@kroolik:是的,c&p-and-don't-修正錯誤。 –

+0

但爲什麼它使用命令行工作,而不是代碼? –