Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get built-in function from the function name

Tags:

python

How can I get the int(), float(), dict(), etc. callables from their names? For example, I'm trying to save Python values to xml and storing the variable type as a string. Is there a way to get the callable from the string when converting from string back to the 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've also tried getattr(object, 'str'), but this doesn't work either since these functions are not part of the base 'object' type, merely globals to the language.

like image 868
durden2.0 Avatar asked Mar 01 '12 19:03

durden2.0


People also ask

How do I get the built-in function in Python?

The built-in function dir() returns a list of names of attributes, methods, etc. of the object specified in the argument. You can get a list of names of built-in objects, such as built-in functions and constants, by passing the builtins module or __builtins__ to dir() . To make the output easier to read, use pprint.

What is a built-in function?

Built-in functions are ones for which the compiler generates inline code at compile time. Every call to a built-in function eliminates a runtime call to the function having the same name in the dynamic library.

Is val () built-in function in Python?

Solution 1. Please try solution from below , as there is no in built equivalent fucntion for Val() in Python .

Is print () a built-in function?

You have already used some of the Python built-in functions, for example, the print() function is used to output a string on the console. As of now, the latest version of Python 3.8 has 69 built-in functions.


1 Answers

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.

Wrong, there is:

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

(In Python 3.x: import builtins)

like image 68
Sven Marnach Avatar answered Oct 11 '22 12:10

Sven Marnach