Convert String to Function in Python

Recently, I worked on a project that required me to convert string inputs into executable Python functions. I was building a custom calculator app that would allow users to define their mathematical formulas as text and then use them for calculations.

The issue is, there isn’t just one way to do this in Python, and some methods are much safer than others.

In this article, I’ll cover five practical methods you can use to convert strings to functions in Python, along with real-world examples. So let’s get in!

Convert String to Function in Python

Now I will explain to you five important methods to convert string to function in Python, along with examples.

Read How to Count Characters in a String in Python?

Method 1: Use the eval() Function

The simplest way to convert a string to a function in Python is to use the built-in eval() function. This function evaluates a string as a Python expression.

# Basic string evaluation
result = eval("2 + 3")
print(result)

# Using variables in eval
x = 10
result = eval("x * 5")
print(result)

Output:

5
50

I executed the above example code and added the screenshot below.

Convert String to Function in Python

However, using eval() comes with significant security risks if you’re processing untrusted input. Never use eval() on user-provided strings without proper validation, as it can execute arbitrary code.

Create a Function from a String Using eval()

Sometimes, you might need to generate a function dynamically based on a formula or logic stored as a string.

def create_function_with_eval(func_str, param_names):
    """
    Create a function from a string using eval

    Args:
        func_str (str): String containing the function body
        param_names (list): List of parameter names
    """
    params = ", ".join(param_names)

    # Create the lambda function string
    lambda_str = f"lambda {params}: {func_str}"

    # Return the evaluated lambda function
    return eval(lambda_str)

# Example usage
multiply = create_function_with_eval("a * b", ["a", "b"])
print(multiply(5, 6))  # Output: 30

Using eval() to convert a string into a lambda function can be an efficient and flexible tool in Python.

Check out How to Split Strings with Multiple Delimiters in Python?

Method 2: Use exec() for More Complex Functions

If your function needs multiple lines of logic, loops, or conditionals, using exec() is a better fit than Python eval().

def create_function_with_exec(func_name, param_names, func_body):
    """
    Create a function using exec

    Args:
        func_name (str): Name of the function
        param_names (list): List of parameter names
        func_body (str): Function body as string
    """
    # Format the function definition
    params = ", ".join(param_names)
    function_definition = f"def {func_name}({params}):\n"

    # Indent each line of the function body
    indented_body = "\n".join(f"    {line}" for line in func_body.split("\n"))

    # Combine function definition and body
    full_function = function_definition + indented_body

    # Create a namespace for the function
    namespace = {}

    # Execute the function definition in the namespace
    exec(full_function, globals(), namespace)

    # Return the created function
    return namespace[func_name]

# Example usage
func_body = """
result = 0
for i in range(a, b+1):
    result += i
return result
"""

sum_range = create_function_with_exec("sum_range", ["a", "b"], func_body)
print(sum_range(1, 5))

Output:

15

I executed the above example code and added the screenshot below.

Python Convert String to Function

The exec() method offers more flexibility for defining complex functions dynamically. Just like eval() be cautious when using it, especially with untrusted input, to keep your code safe and secure.

Read Convert Hexadecimal String to Integer in Python

Method 3: Use compile() for Pre-compiled Functions

When performance matters and you’re working with string-based functions that need to be reused, Python’s compile() function is a great tool.

def create_function_with_compile(func_str, param_names):
    """
    Create a function using compile for better performance

    Args:
        func_str (str): String containing the function body
        param_names (list): List of parameter names
    """
    params = ", ".join(param_names)

    # Create the lambda function string
    lambda_str = f"lambda {params}: {func_str}"

    # Compile the lambda function
    compiled_lambda = compile(lambda_str, "<string>", "eval")

    # Return the evaluated compiled lambda function
    return eval(compiled_lambda)

# Example usage
square = create_function_with_compile("x**2", ["x"])
print(square(5))

Output:

25

I executed the above example code and added the screenshot below.

How to Convert String to Function in Python

Using compile() gives you a performance edge when executing string-based code repeatedly. It combines the flexibility of eval() with added speed, making it a smart choice for more optimized scenarios.

Read How to Pad Strings with Spaces in Python?

Method 4: Use Abstract Syntax Trees (AST)

For the safest approach when dealing with potentially untrusted inputs, using Python’s AST module allows you to analyze and transform the syntax tree before executing it:

import ast
import math

def safe_eval(expr, variables=None):
    """
    Safely evaluate a string expression using AST

    Args:
        expr (str): The expression to evaluate
        variables (dict): Dictionary of variables to use in evaluation
    """
    if variables is None:
        variables = {}

    # Add safe math functions
    variables.update({
        'sin': math.sin,
        'cos': math.cos,
        'tan': math.tan,
        'exp': math.exp,
        'sqrt': math.sqrt,
        'pi': math.pi,
        'e': math.e
    })

    # Parse the expression
    node = ast.parse(expr, mode='eval')

    # Define allowed node types
    allowed_nodes = {
        ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow,
        ast.UnaryOp, ast.USub, ast.UAdd,
        ast.Num, ast.Name, ast.Load, ast.Call
    }

    # Define allowed function names
    allowed_funcs = {
        'sin', 'cos', 'tan', 'exp', 'sqrt'
    }

    # Verify that the AST only contains allowed operations
    def verify_node(node):
        if not isinstance(node, ast.AST):
            return

        if not type(node) in allowed_nodes:
            raise ValueError(f"Disallowed operation: {type(node)}")

        if isinstance(node, ast.Call):
            if not isinstance(node.func, ast.Name):
                raise ValueError("Only direct function calls are allowed")
            if node.func.id not in allowed_funcs:
                raise ValueError(f"Function not allowed: {node.func.id}")

        for child in ast.iter_child_nodes(node):
            verify_node(child)

    verify_node(node)

    # Compile and evaluate the expression
    compiled_expr = compile(node, '<string>', 'eval')
    return eval(compiled_expr, {"__builtins__": {}}, variables)

# Create a function that uses safe_eval
def create_safe_math_function(expr, param_names):
    """
    Create a safe mathematical function from a string

    Args:
        expr (str): The mathematical expression
        param_names (list): List of parameter names
    """
    def func(*args):
        if len(args) != len(param_names):
            raise ValueError(f"Expected {len(param_names)} arguments, got {len(args)}")

        # Create variables dictionary from args
        variables = {param: arg for param, arg in zip(param_names, args)}

        # Evaluate the expression safely
        return safe_eval(expr, variables)

    return func

# Example usage
safe_func = create_safe_math_function("sin(x)**2 + cos(x)**2", ["x"])
print(safe_func(0.5))  # Output: 1.0

This approach converts a string to a mathematical function securely by limiting the operations allowed in the expression.

Check out remove specific words from a string in Python

Method 5: Use Third-Party Libraries

Several libraries exist specifically for evaluating mathematical expressions or creating functions from Python strings:

Using sympy for Mathematical Expressions

If you’re working with symbolic math or algebraic expressions, Python’s sympy library makes it easy to turn a string into a working math function.

import sympy

def create_sympy_function(expr_str, param_names):
    """
    Create a mathematical function using sympy

    Args:
        expr_str (str): Mathematical expression as string
        param_names (list): List of parameter names
    """
    # Convert parameter names to sympy symbols
    symbols = [sympy.Symbol(name) for name in param_names]

    # Parse the expression
    expr = sympy.sympify(expr_str)

    # Create a lambda function
    func = sympy.lambdify(symbols, expr)

    return func

# Example usage
f = create_sympy_function("x**2 + y**2", ["x", "y"])
print(f(3, 4))  # Output: 25

With just a few lines of code, sympy lets you convert a formula string into a callable function

Using numexpr for Fast Numerical Evaluation

When speed is important, especially with large arrays or numerical data numexpr comes to the rescue.

import numexpr as ne
import numpy as np

def create_numexpr_function(expr_str, param_names):
    """
    Create a function using numexpr for fast numerical evaluation

    Args:
        expr_str (str): Mathematical expression as string
        param_names (list): List of parameter names
    """
    def func(*args):
        if len(args) != len(param_names):
            raise ValueError(f"Expected {len(param_names)} arguments, got {len(args)}")

        # Create local variables for evaluation
        local_dict = {name: np.array(value) for name, value in zip(param_names, args)}

        # Evaluate the expression
        return ne.evaluate(expr_str, local_dict=local_dict)

    return func

# Example usage
f = create_numexpr_function("sin(x) + cos(y)", ["x", "y"])
print(f(0, 0))  # Output: 1.0

By combining the ease of string expressions with the speed of compiled operations, numexpr is a powerful choice for high-performance numerical computing.

Read Convert a String to an Integer in Python

Real-World Example: Dynamic Data Processing Pipeline

Here’s a practical example of how I have used string-to-function conversion in a data processing application:

class DataProcessor:
    def __init__(self):
        self.transformations = {}
    
    def add_transformation(self, name, formula, columns):
        """Add a transformation from string formula"""
        self.transformations[name] = str_to_func_compile(formula, columns)
    
    def process_row(self, row_data, transformation_name):
        """Apply transformation to a row of data"""
        if transformation_name not in self.transformations:
            raise ValueError(f"Unknown transformation: {transformation_name}")
        
        transform = self.transformations[transformation_name]
        
        # Extract column values
        args = [row_data.get(col) for col in 
                transform.__code__.co_varnames[:transform.__code__.co_argcount]]
        
        # Apply transformation
        return transform(*args)

# Usage example
processor = DataProcessor()

# Add transformations from configuration
processor.add_transformation(
    "calculate_discount",
    "price * discount_rate if total_spent > loyalty_threshold else 0",
    ["price", "discount_rate", "total_spent", "loyalty_threshold"]
)

# Process data
customer_purchase = {
    "customer_id": "C12345",
    "product": "Premium Headphones",
    "price": 199.99,
    "discount_rate": 0.15,
    "total_spent": 1500,
    "loyalty_threshold": 1000
}

discount = processor.process_row(customer_purchase, "calculate_discount")
print(f"Customer discount: ${discount:.2f}")  # Output: Customer discount: $30.00

This approach allows non-technical users to define business rules without touching the code.

Check out Convert a String to a Dictionary in Python

Security Considerations

When converting strings to functions, always consider these security best practices:

  • Use the ast module to verify code structure before execution
  • Never use eval() or exec() directly with user input
  • Validate and sanitize all input before processing
  • Use a whitelist approach for allowed operations rather than trying to block dangerous ones

When to Use String-to-Function Conversion in Python

In my decade of Python development, I’ve found these techniques most valuable in:

  1. Configuration-driven applications – where business rules or processing logic are stored in config files
  2. Calculator applications – allowing users to define custom formulas
  3. Data transformation pipelines – where transformations are defined dynamically
  4. Business rule engines – enabling non-developers to define logic
  5. Scientific computing – working with user-defined mathematical formulas

However, it’s not always the right approach. For critical applications or where security is important, consider alternatives like:

  • Domain-specific languages (DSLs) with proper parsers
  • Template-based code generation
  • Plugin architectures with proper isolation

Converting strings to functions in Python adds incredible flexibility to your applications. I’ve used these techniques to build systems that business users can configure without developer intervention, saving countless hours of development time.

Just remember to prioritize security when working with dynamic code execution, especially when handling user input.

Related tutorials, you may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.