Home > database >  how to turn a list item (string type) into a module function in python 3.10
how to turn a list item (string type) into a module function in python 3.10

Time:07-17

I had a weird idea to grab a list item and call it as module function, here is what I'm trying to do:

if you used dir() on random module it would return a list of its attributes, and I want to grab a specific item which is, in this case, randint, then invoke it as a working function using a,b as arguments and become in this form randint(a, b) that's what I tried:

from random import randint  #to avoid the dot notation and make it simple
a = 10
b = 100
var = dir(random)
print(var)
# here is the result

enter image description here

 #randint index is 55
 print(var[55])
 >>> randint

I couldn't find out the type of the function randint() so I can convert the list item to it and try the following:

something(var[55]   "(a, b)")

is there a way I can achieve what I'm trying to do?

CodePudding user response:

you can use exec command that can execute any string.

updated your code, below answer should work

import random
from random import randint  #to avoid the dot notation and make it simple


a = 10
b = 100
var = dir(random)
print(var)

function_string = "random_number= "   var[52]   f"({a},{b})"

print(function_string)
exec(function_string)
print(random_number)
  • Related