0

I want to create a list of all functions in .py file and then use these functions randomly. I've already created some list using dir(), but cannot run.

file with functions file.py:

def f1:
   # some code
def f2:
   # some code
def f3:
   # some code

another script:

functions = dir(file)
random.choice(functions)()

It shows this error

TypeError: 'str' object is not callable
mkrana
  • 422
  • 4
  • 10
Radek
  • 1
  • 2
    Maybe this can help you --> https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string – Kevin Müller May 03 '19 at 13:55
  • Possible duplicate of [Syntax to call random function from a list](https://stackoverflow.com/questions/5465455/syntax-to-call-random-function-from-a-list) – sykezlol May 03 '19 at 13:56
  • Possible duplicate of [Choosing a function randomly](https://stackoverflow.com/questions/14150561/choosing-a-function-randomly) – ruohola May 03 '19 at 13:57

1 Answers1

0

Assuming all the functions in file1.py contain only functions with either no arguments or functions with only default value arguments, then

if file1.py is

def f1():
    print ("f1")

def f2():
    print ("f2")

def f3():
    print ("f3")

def f4(i=0):
    print ("f4")

Another script will be:

import file1
from inspect import getmembers, isfunction
import random

functions_list = [o for o in getmembers(file1) if isfunction(o[1])]
random.shuffle(functions_list)

for f in functions_list:
    f[1]()
mujjiga
  • 16,186
  • 2
  • 33
  • 51