PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] how to turn a list item (string type) into a module function in python 3.10

 August 24, 2022     module, python-3.x, type-conversion     No comments   

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

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?


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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing