Get inline function on behalf of function

How can I get calls to int (), float (), dict (), etc. from their names? For example, I am trying to save Python values ​​in xml and save the variable type as a string. Is there a way to get called from string when converting from string back to Python type?

Normally I would do something like getattr (myobj, 'str'), but there is no module to use as the first argument for these built-in conversion functions. I also tried getattr (object, 'str'), but this will not work, since these functions are not part of the base type of the object, but simply globalize the language.

+4
source share
3 answers

Normally I would do something like getattr(myobj, 'str') , but there is no module as the first argument for these built-in conversion functions.

Wrong, there are:

 import __builtin__ my_str = getattr(__builtin__, "str") 

(In Python 3.x: import builtins )

+14
source

You do not need to import anything

 vars(__builtins__)['dict'] vars(__builtins__)['float'] vars(__builtins__)['int'] 

and etc.

+3
source

One quick way is to call it from the __builtin__ module. for instance

 >>> import __builtin__ >>> __builtin__.__dict__['str'](10) '10' 
0
source

Source: https://habr.com/ru/post/1399246/


All Articles