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.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 June

    Get Day Name from Date in Python

    Table of ContentsUse the Calendar Module to Get the Name of the Day in PythonUse the strftime() Method to Get the Name of the Day in PythonUse Pandas Timestamp Method to Get the Name of the Day in PythonUse the weekday() Method to Get the Name of the Day in PythonUse the isoweekday() Method to […]

  • 27 June

    Fill Array with Random Numbers in Python

    Table of ContentsFill array with random numbers in PythonWays to fill array with random numbers in PythonUsing the numpy.random.randint() function to fill array with random numbers in PythonUsing the numpy.random.Generator.integers() function to fill array with random numbers in PythonUsing the random.randint() function to fill array with random numbers in PythonConclusionWas this post helpful? Fill array […]

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.