The Wayback Machine - https://web.archive.org/web/20241127013351/https://www.geeksforgeeks.org/call-a-function-by-a-string-name-python/
Open In App

Call a function by a String name – Python

Last Updated : 05 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let’s say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between start(inclusive) and end(inclusive). Here, we will discuss 2 methods to solve this:

  • Python Getattr() Method
  • Python exec() Method

What is Getattr() Method

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.

Syntax of getattr() method

Syntax: getattr(obj, key, def)

  • obj: The object whose attributes need to be processed.
  • key: The attribute of object
  • def: The default value that needs to be printed in case the attribute is not found.

Returns: Object value if the value is available, the default value in case attribute is not present, and returns AttributeError in case attribute is not present and the default value is not specified.

Example 1

Importing a module random and using getattr() method to access randint method of random.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    import random
  
    # Using randint function of random
    # module as r
    r = getattr(random, 'randint')
  
    # calling the function and storing
    # the value in res
    res = r(1, 9)
  
    # Printing the result
    print(res)


Output:

9

Example 2

Here, we are using randint function of the random module as func.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    Module = __import__('random')
  
    func = getattr(Module, 'randint')
  
    # calling the function and storing
    # the value in res
    res = func(1, 9)
  
    # Printing the result
    print(res)


Output:

6

What is exec() method

The exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be careful that the return statements may not be used outside of function definitions not even within the context of code passed to the exec() function. It doesn’t return any value, hence returns None.

Syntax of exec() method

Syntax: exec(object[, globals[, locals]])

  • object: As already said this can be a string or object code
  • globals: This can be a dictionary and the parameter is optional
  • locals: This can be a mapping object and is also optional

Return:  None.

Example 1

Using the random function of the random module and calling it using exec() method. The random module generates a decimal number between 0 and 1.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    import random
  
    # Using random function of random
    # module as func
    func = "random.random"
  
    # calling the function and storing
    # the value in res
    exec(f"x = {func}")
    res = x()
  
    # Printing the result
    print(res)


Output:

0.640045711797753

Example 2

Here also we are generating a decimal number between 0 and 1.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    import random
  
    # Using random function of random
    # module as func
    func = "random"
  
    # calling the function and storing
    # the value in res
  
    exec(f"x = random.{func}")
    res = x()
  
    res1 = round(res, 4)
  
    # Printing the result
    print(res1)


Output:

0.6221


Previous Article
Next Article

Similar Reads

Is Python call by reference or call by value
Python utilizes a system, which is known as "Call by Object Reference" or "Call by assignment". If you pass arguments like whole numbers, strings, or tuples to a function, the passing is like a call-by-value because you can not change the value of the immutable objects being passed to the function. Passing mutable objects can be considered as call
5 min read
Call column name when it is a timestamp in Python
Handling timestamp columns efficiently is crucial for many data science and engineering tasks. Timestamp columns often require specific operations like parsing, formatting, and time-based filtering. In this article, we will explore three good code examples of how to call and manipulate timestamp columns using different methods and libraries. Callin
3 min read
Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Decorator to print Function call details in Python
Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. Example: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the a
3 min read
How to Call a C function in Python
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let's write one simple function using C and generate a shared library of the file. Let's say file name is
2 min read
How to call a function in Python
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them. In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "def" we give the name of the function which could b
5 min read
Python - Call function from another file
Given a Python file, we need to call a function in it defined in any other Python file. Example: Suppose there is a file test.py which contains the definition of the function displayText(). #test.py>def displayText(): print( "Geeks 4 Geeks!")We need to call the function displayText() in any other Python file such that wherever we call displayTex
5 min read
call() decorator in Python
Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modified code in functions or classes. The decorators all
3 min read
Python: Call Parent class method
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Example: # Python program to demonstrate # classes class cls: # Constructor def __init__(self, fname,
4 min read
Define and Call Methods in a Python Class
In object-oriented programming, a class is a blueprint for creating objects, and methods are functions associated with those objects. Methods in a class allow you to define behavior and functionality for the objects created from that class. Python, being an object-oriented programming language, provides a straightforward syntax for defining and cal
3 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Fix: "SyntaxError: Missing Parentheses in Call to 'print'" in Python
In Python, if we see the "SyntaxError: Missing Parentheses in Call to 'print'" error, it means we forgot to use parentheses around what we want to print. This is the most common error that we encounter when transitioning from Python 2 to Python 3. This error occurs due to a significant change in how the print statement works between Python2 and Pyt
3 min read
How to Make API Call Using Python
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see how to make API calls in Python. Make API Call in Py
3 min read
Convert String into Variable Name in Python
There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert a string into a variable name, these examples dem
3 min read
Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods to obtain the variable name as a string in Python
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to know certain hacks of functions. This article disc
3 min read
Change Object Display Name using __str__ function - Django Models | Python
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Object Display Name in Django Models Consider a proj
2 min read
How to get list of parameters name from a function in Python?
In this article, we are going to discuss how to get list parameters from a function in Python. The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Python | Pandas TimedeltaIndex.name
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.name attribute return the name of the TimedeltaIndex object if it is set. If no name is set for the object under c
2 min read
Python | Pandas tseries.offsets.DateOffset.name
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessDay.name
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessHour.name
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessDay.name
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessHour.name
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Create Archives and Find Files by Name
In this article, we will learn how to create or unpack archives in common formats (e.g., .tar, .tgz, or .zip) using shutil module. The shutil module has two functions — make_archive() and unpack_archive() — that can exactly be the solution. Code #1 : import shutil shutil.unpack_archive('Python-3.3.0.tgz') shutil.make_archive('py33', 'zip', 'Python-
3 min read
Practice Tags :
three90RightbarBannerImg