#!/usr/bin/env python3.9 # -*- coding: utf-8 -*- """ JFinal RandomDirective - Random Directive """ import random from ...Directive import Directive from ...Env import Env from ...stat.Scope import Scope class RandomDirective(Directive): """Random directive for generating random numbers""" def exec(self, env: Env, scope: Scope, writer) -> None: """ Execute random directive Args: env: Template environment scope: Execution scope writer: Output writer """ if self.expr_list: # Get parameters values = self.expr_list.eval_expr_list(scope) if len(values) == 0: # No parameters, generate random float between 0 and 1 random_value = random.random() elif len(values) == 1: # One parameter, generate random int between 0 and max max_value = int(values[0]) random_value = random.randint(0, max_value - 1) elif len(values) == 2: # Two parameters, generate random int between min and max min_value = int(values[0]) max_value = int(values[1]) random_value = random.randint(min_value, max_value) else: # Too many parameters random_value = random.random() if hasattr(writer, 'write'): writer.write(str(random_value)) def __repr__(self) -> str: return "RandomDirective()"