Convert String to function call in Python

Python String to function

Strings are one of the most used data structures when we process text data. We also use different functions in our program. But, have you ever tried to convert a string to a function given that a function with the same name has been defined in a different module or class? In this article, we will discuss how we can convert string to function call using different ways in python

String To Function Using The eval() Function In Python

The eval() function takes a string expression as input, parses it, and returns the output after evaluating the input expression. For instance, we can evaluate a mathematical expression using the eval() function as follows.

Output:

We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ‘()’ separated by the addition symbol ‘+’. Upon execution, the eval() function will call the input function and will return the output of the function whose name was given as the input argument.

For instance, look at the following example.

Output:

Here, we have declared a function named ‘printTenNumbers’ that prints the numbers from 1 to 10. We have passed the function name i.e. ‘printTenNumbers’ and ‘()’ separated by + sign to the eval() function. The eval() function first calculated the expression ‘‘printTenNumbers + “()”’ to ‘printTenNumbers()’. After that printTenNumbers() is executed and the numbers are printed. Hence, we have converted a string to a function in python, Given that a function with the name of the given string is already defined.

String To Function Using The getattr() Function In Python

In python, the getattr() function is used to extract the value of an attribute from a class or a module using its name. The syntax for the getattr() function is as follows.

getattr(object, attribute,default)

Here,

  • The ‘object’ may be a class name, a module name, or an instance of a class.
  • attribute’ is the name of the field, function, or method that we want to extract from the class or the module.
  • default’ is the default value if the input  ‘attribute’ name is not found in the object. 

Let us understand the working of the getattr() function using the following example.

Output:

Here, we have defined a class Laptop with three attributes namely model, RAM, and processor. Then we have created a Laptop object named myLaptop. After that, we have extracted the value of the attribute processor using the getattr() function. We can obtain the value of any attribute of the myLaptop object.

Hence, getattr() function can be used to obtain values of different attributes of a class, object, or module.

Having understood the working of the getattr() function, let us now use the getattr() function to convert a string to function in python.

String To Function Using The getattr() Function And Module Name

If we have the name of a function defined in a different module, we can convert the string to function using the getattr() function. For this, we will pass the name of the function to the getattr() function as the first argument and the name of the module as the second argument. The getattr() function will return a function that will behave exactly the same as the function whose name is given as input. 

For instance, we can use the factorial() function defined in the math module using the string ‘factorial’ and the module name ‘math’ to define a function that behaves exactly like the factorial() function as follows.

Output:

Here,you can observe that output_function works exactly the same as the factorial function. Hence, we have converted the string factorial to a function. You should always import the module whose name you are passing as an input argument to the getattr() function. Otherwise, the program will run into errors.

String To Function Using The getattr() Function And Class Name

Instead of the module name, we can use the class name and the name of a method defined in the class to convert a string to a function. Here, we will pass the name of the method as the first argument to the getattr() function and the name of the class as the second input argument. The getattr() function will return a function that will behave in a similar manner to the method whose name we have passed to the getattr() function. You can execute the output function by passing an instance of the class as its first argument. 

For instance, look at the following example.

Output:

Here, we have also defined a print_details() method in the Laptop class. We have then converted the string print_details to function using the getattr() function and class name. You can observe that the output_function behaves the same ways as the print_details() method.

String To Function Using The getattr() Function And Class Instance

Instead of passing the class name to the getattr() function, we can also give the instance of the class i.e. object name as input along with the name of the method. After converting the string to function using this approach, we don’t need to pass the name of the object as input to the output function of the getattr() function. You can understand this using the following example.

Output:

Here, you can observe that we have given the myLaptop instance to the getattr() function instead of Laptop. Due to this, we don’t need to pass myLaptop instance as an input argument to the output_function().

Conclusion

In this article, we have used different ways to convert a string to function in python. We used the eval() function and getattr() function for the same. You can use any approach to covert string to function in python as long as it works for you.

I hope you found the discussion interesting. Stay tuned for more informative articles.

That’s all about Python String to function.

Happy Learning.

Related Posts

  • Python check for null
    17 November

    How to check for null in Python

    Table of ContentsHow to check if a variable is NULL in Python?Using the is operator to check if a variable is NULL in Python.Using the if condition to check if a variable is NULL in Python.Using the not equal to operator to check if a variable is NULL in Python. This article demonstrates the different […]

  • Sort dictionary by value in Python
    17 November

    Sort dictionary by value in python

    Table of ContentsHow to sort sort dictionary by value in Python?Using for loop along with the sorted() function.Using the sorted() function to sort dictionary by value in Python.Using operator.itemgetter() function to sort sort dictionary by value in Python.Using lambda function to sort sort dictionary by value in Python.Using the OrderedDict() method to sort sort dictionary […]

  • Get class name in Python
    17 November

    Get class name in Python

    Table of ContentsHow to get the attributes of an object?Get Class name in python using the __class__ attribute Get Class name in python using type() functionConclusion While working with objects in python, several times we need to get their class name. In this article, we will discuss several ways to get the class name of an […]

  • Python print to file
    17 November

    How to Print to File in Python?

    Table of ContentsThe print() function in pythonHow to Print to file in python?Print to file using the file parameter in the print functionPrint to file by redirecting standard outputConclusion We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() […]

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.