Random Function Execution with Fire Library

  • Share this:

Code introduction


This code defines a main function `main` that randomly selects one of three functions and uses the Fire library to parse command-line arguments to call the function. These functions include calculating the area of a circle, generating a random number, and sorting a list.


Technology Stack : Python, Fire, math, random, argparse

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
import math
import fire

def calculate_circle_area(radius):
    """
    Calculate the area of a circle given its radius.
    """
    return math.pi * (radius ** 2)

def generate_random_number(min_val, max_val):
    """
    Generate a random number between min_val and max_val.
    """
    return random.uniform(min_val, max_val)

def sort_list(input_list):
    """
    Sort a list in ascending order.
    """
    return sorted(input_list)

# Generate a random function to be used with Fire
def random_function():
    functions = {
        "circle_area": calculate_circle_area,
        "random_number": generate_random_number,
        "sort_list": sort_list
    }
    return random.choice(list(functions.keys()))

def main():
    func_name = random_function()
    func = globals()[func_name]
    func(*fire.argparse_args(func))

if __name__ == "__main__":
    fire.Fire(main)