Search code examples
pythonfunctionrandomnonetype

How to specify a random and None value of a boolean parameter


I have some function a which has boolean param b: bool. This parameter can take either a specified value, an empty value, or a random value.

def a(b: Optional[bool] = random_bool()) -> None
  print(b)

But if you specify random generation directly in the function declaration, it will always be the same

>>> a()
True  # Problem
>>> a()
True  # Problem
>>> a(False)
False
>>> a(True)
True
>>> a(None)
None

At first I thought I would assign it an None default value and generate a random one already in the function.

def a(b: Optional[bool] = None) -> None:
    b = random_bool() if b is None else b
    print(b)

But then I wouldn't be able to specify an None value

>>> a()
True
>>> a()
False
>>> a(False)
False
>>> a(True)
True
>>> a(None)
True # Problem

So how can I specify random/specified/empty value in a nice way?


Solution

  • At function definition (when python runs), random_bool() is called, and the default value defined. That's why it won't change.

    Typically, you would default to None, then if not defined perform a default value operation.

    I would prefer to allow None, but here's a workaround:

    def a(b: Optional[bool] = None, use_random: bool = False) -> None:
        result = b
        if use_random:
            result = random_bool()
        print(result)
    
    

    Or you could default to a value that is not True, False, or None.

    def a(b: Optional[Union[bool, str]] = "random") -> None:
        result = b
        if result == "random":
            result = random_bool()
        print(result)