Issue
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
#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?
Solution
you can use the exec
command that can execute any string.
updated your code, the below answer should work
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[55] + f"({a},{b})"
#note that index number can be changed based on python version
print(function_string)
exec(function_string)
print(random_number)
Answered By - Deepak Dhaka Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.