There are three py-files in one folder:

main.py module.py submodule.py 

Contents of the submodule.py file:

 import random def func(): x = random.randint(1, 100) return x 

Contents of the module.py file:

 from submodule import func data = [ ('number', func()), ('param', 'key'), ] 

The contents of the main.py file

 from module import data while True: response = requests.post(url='http://site.com', data=data) 

When you run the main.py file, the output is as follows:

 [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] [('number', 8), ('param', 'key')] 

Dear experts. How can I get the func() function to execute each time the while loop passes without transferring the function to another module?

  • in a normal way, make the data function, not an object ... if you want it to be an object, then you can make it mimic the list (maybe there is something ready) ... other options are possible, depending on what requests the requests.post () to parameters ... - Fat-Zer
  • What is the relationship between the title and the question body? You actually have a question: "how to initialize a variable from another module during each loop pass". (answer: replace data = [func()] with get_data = lambda: [func()] and then in a loop: data=get_data() ) - jfs

1 answer 1

See, you have one value from func in the data list and after that the module file will not access the submodule every time. Try this:

Package submodule:

 def func(numb): x = numb return x 

Package module:

 from submodule import func import random def data_func(): data = [ ('number', func(random.randint(0,100))), ('param', 'key')] return data 

main

 import module as mod while True: print(mod.data_func()) 
  • does not fit. the same conclusion - MIKS
  • @MIKS understood what you meant, corrected the answer, now it seems to be working - dedifferentiator