{"id":18176,"date":"2021-11-06T16:04:32","date_gmt":"2021-11-06T10:34:32","guid":{"rendered":"https:\/\/java2blog.com\/?p=18176"},"modified":"2021-11-06T16:04:34","modified_gmt":"2021-11-06T10:34:34","slug":"python-string-to-function","status":"publish","type":"post","link":"https:\/\/java2blog.com\/python-string-to-function\/","title":{"rendered":"Convert String to function call in Python"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#String_To_Function_Using_The_eval_Function_In_Python\">String To Function Using The eval() Function In Python<\/a><\/li><li><a href=\"#String_To_Function_Using_The_getattr_Function_In_Python\">String To Function Using The getattr() Function In Python<\/a><\/li><li><a href=\"#String_To_Function_Using_The_getattr_Function_And_Module_Name\">String To Function Using The getattr() Function And Module Name<\/a><\/li><li><a href=\"#String_To_Function_Using_The_getattr_Function_And_Class_Name\">String To Function Using The getattr() Function And Class Name<\/a><\/li><li><a href=\"#String_To_Function_Using_The_getattr_Function_And_Class_Instance\">String To Function Using The getattr() Function And Class Instance<\/a><\/li><li><a href=\"#Conclusion\">Conclusion<\/a><\/li><\/ul><\/div>\n\n<p>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<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"String_To_Function_Using_The_eval_Function_In_Python\">String To Function Using The eval() Function In Python<\/span><\/h2>\n\n\n\n<p>The <code>eval()<\/code> 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 <code>eval()<\/code> function as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>num1 = 10\nnum2 = 5\nexpression = \"num1+num1*num2\"\nresult = eval(expression)\nprint(\"num1 and num2 are {} and {} respectively\".format(num1, num2))\nprint(\"expression is:\", expression)\nprint(\"result is:\", result)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>num1 and num2 are 10 and 5 respectively\nexpression is: num1+num1*num2\nresult is: 60<\/code><\/pre>\n\n\n\n<p>We can also use the <code>eval()<\/code> function to convert a string to a function. Here, the input string is the name of the function. In the <code>eval()<\/code> function, we will pass the name of the function and the \u2018<code>()<\/code>\u2019 separated by the addition symbol \u2018<code>+<\/code>\u2019. Upon execution, the <code>eval()<\/code> function will call the input function and will return the output of the function whose name was given as the input argument.<\/p>\n\n\n\n<p>For instance, look at the following example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def printTenNumbers():\n    for i in range(11):\n        print(i, end=\" \")\n\n\ninput_string = \"printTenNumbers\"\neval(input_string + \"()\")\n<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>0 1 2 3 4 5 6 7 8 9 10 <\/code><\/pre>\n\n\n\n<p>Here, we have declared a function named \u2018<code>printTenNumbers<\/code>\u2019 that prints the numbers from 1 to 10. We have passed the function name i.e. \u2018<code>printTenNumbers<\/code>\u2019 and \u2018<code>()<\/code>\u2019 separated by <code>+<\/code> sign to the <code>eval()<\/code> function. The <code>eval()<\/code> function first calculated the expression \u2018\u2018<code>printTenNumbers + \u201c()<\/code>\u201d\u2019 to \u2018<code>printTenNumbers()<\/code>\u2019. After that <code>printTenNumbers()<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"String_To_Function_Using_The_getattr_Function_In_Python\">String To Function Using The getattr() Function In Python<\/span><\/h2>\n\n\n\n<p>In python, the <code>getattr()<\/code> function is used to extract the value of an attribute from a class or a module using its name. The syntax for the <code>getattr()<\/code> function is as follows.<\/p>\n\n\n\n<p><code>getattr(object, attribute,default)<\/code><\/p>\n\n\n\n<p>Here,<\/p>\n\n\n\n<ul><li>The \u2018<code>object<\/code>\u2019 may be a class name, a module name, or an instance of a class.<\/li><li>\u2018<code>attribute<\/code>\u2019 is the name of the <code>field<\/code>, <code>function<\/code>, or <code>method<\/code> that we want to extract from the class or the module.<\/li><li>\u2018<code>default<\/code>\u2019 is the default value if the input&nbsp; \u2018<code>attribute<\/code>\u2019 name is not found in the object.&nbsp;<\/li><\/ul>\n\n\n\n<p>Let us understand the working of the <code>getattr()<\/code> function using the following example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Laptop:\n    def __init__(self, model, ram, processor):\n        self.model = model\n        self.RAM = ram\n        self.processor = processor\n\n\nmyLaptop = Laptop(\"Inspiron\", \"16GB\", \"Octa Core\")\nvar = \"processor\"\noutput = getattr(myLaptop, var)\nprint(output)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Octa Core<\/code><\/pre>\n\n\n\n<p>Here, we have defined a class <code>Laptop<\/code> with three attributes namely <code>model<\/code>, <code>RAM<\/code>, and <code>processor<\/code>. Then we have created a <code>Laptop<\/code> object named <code>myLaptop<\/code>. After that, we have extracted the value of the attribute <code>processor<\/code> using the <code>getattr() <\/code>function. We can obtain the value of any attribute of the <code>myLaptop<\/code> object. <\/p>\n\n\n\n<p>Hence, <code>getattr()<\/code> function can be used to obtain values of different attributes of a class, object, or module.<\/p>\n\n\n\n<p>Having understood the working of the <code>getattr()<\/code> function, let us now use the <code>getattr()<\/code> function to convert a string to function in python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"String_To_Function_Using_The_getattr_Function_And_Module_Name\">String To Function Using The getattr() Function And Module Name<\/span><\/h2>\n\n\n\n<p>If we have the name of a function defined in a different module, we can convert the string to function using the <code>getattr()<\/code> function. For this, we will pass the name of the function to the <code>getattr()<\/code> function as the first argument and the name of the module as the second argument. The <code>getattr() <\/code>function will return a function that will behave exactly the same as the function whose name is given as input.&nbsp;<\/p>\n\n\n\n<p>For instance, we can use the <code>factorial()<\/code> function defined in the math module using the string \u2018<code>factorial<\/code>\u2019 and the module name \u2018<code>math<\/code>\u2019 to define a function that behaves exactly like the <code>factorial()<\/code> function as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import math\n\nvar = \"factorial\"\noutput_function = getattr(math, var)\noutput = output_function(6)\nprint(output)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>720<\/code><\/pre>\n\n\n\n<p>Here,you can observe that <code>output_function works exactly the <\/code>same as the factorial function. Hence, we have converted the string <code>factorial<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"String_To_Function_Using_The_getattr_Function_And_Class_Name\">String To Function Using The getattr() Function And Class Name<\/span><\/h2>\n\n\n\n<p>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 <code>getattr()<\/code> function and the name of the class as the second input argument. The <code>getattr()<\/code> function will return a function that will behave in a similar manner to the method whose name we have passed to the <code>getattr()<\/code> function. You can execute the output function by passing an instance of the class as its first argument.&nbsp;<\/p>\n\n\n\n<p>For instance, look at the following example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Laptop:\n    def __init__(self, model, ram, processor):\n        self.model = model\n        self.RAM = ram\n        self.processor = processor\n\n    def print_details(self):\n        print(\"Hi! My details are as follows:\")\n        print(\"Model:\", self.model)\n        print(\"RAM:\", self.RAM)\n        print(\"Processor:\", self.processor)\n\n\nmyLaptop = Laptop(\"Inspiron\", \"16GB\", \"Octa Core\")\nvar = \"print_details\"\noutput_function = getattr(Laptop, var)\noutput_function(myLaptop)<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Hi! My details are as follows:\nModel: Inspiron\nRAM: 16GB\nProcessor: Octa Core<\/code><\/pre>\n\n\n\n<p>Here, we have also defined a <code>print_details()<\/code> method in the Laptop class. We have then converted the string <code>print_details<\/code> to function using the <code>getattr()<\/code> function and class name. You can observe that the <code>output_function<\/code> behaves the same ways as the <code>print_details()<\/code> method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"String_To_Function_Using_The_getattr_Function_And_Class_Instance\">String To Function Using The getattr() Function And Class Instance<\/span><\/h2>\n\n\n\n<p>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\u2019t 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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Laptop:\n    def __init__(self, model, ram, processor):\n        self.model = model\n        self.RAM = ram\n        self.processor = processor\n\n    def print_details(self):\n        print(\"Hi! My details are as follows:\")\n        print(\"Model:\", self.model)\n        print(\"RAM:\", self.RAM)\n        print(\"Processor:\", self.processor)\n\n\nmyLaptop = Laptop(\"Inspiron\", \"16GB\", \"Octa Core\")\nvar = \"print_details\"\noutput_function = getattr(myLaptop, var)\noutput_function()<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Hi! My details are as follows:\nModel: Inspiron\nRAM: 16GB\nProcessor: Octa Core<\/code><\/pre>\n\n\n\n<p>Here, you can observe that we have given the <code>myLaptop<\/code> instance to the <code>getattr()<\/code> function instead of <code>Laptop<\/code>. Due to this, we don&#8217;t need to pass <code>myLaptop<\/code> instance as an input argument to the <code>output_function()<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span id=\"Conclusion\">Conclusion<\/span><\/h2>\n\n\n\n<p>In this article, we have used different ways to convert a string to function in python. We used the <code>eval()<\/code> function and <code>getattr()<\/code> function for the same. You can use any approach to covert string to function in python as long as it works for you.<\/p>\n\n\n\n<p>I hope you found the discussion interesting. Stay tuned for more informative articles.<\/p>\n\n\n<p>That&#8217;s all about Python String to function.<\/p>\n\n\n<p>Happy Learning.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsString To Function Using The eval() Function In PythonString To Function Using The getattr() Function In PythonString To Function Using The getattr() Function And Module NameString To Function Using The getattr() Function And Class NameString To Function Using The getattr() Function And Class InstanceConclusion Strings are one of the most used data structures [&hellip;]<\/p>\n","protected":false},"author":33,"featured_media":18290,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[145],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18176"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=18176"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/18176\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/18290"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=18176"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=18176"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=18176"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}