Python Forum
Help with variable in between modules
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with variable in between modules
#1
Hi All,
first apologizes for my poor scripting - I am a beginner.
I have found lots of information about my doubt but none could actually solve my problem:

About my code: the function generator() will provide me a str number and the function Validator() will run thru a txt file to confirm if such number was already given. If yes, it will increment and return a value into a "control" variable loop_valve, and if no, it will change the w_loop variable to 2 and break the WHILE loop in the main function.

What is my problem: Because of the WHILE condition I need to be able to increment =+1 on both variables w_loop and w_loop, so that I will be able to (1) break the while loop and/or (2) stop the script after a certain condition is met.
Regardless of where I declare the global variables, both underlying variables' values are always changing to the initial value after the MAIN <> FUNCTION iteration. I need to be able to increment those variables freely so that I can control the number of runs of each time it passes thru a function.


def Validator(res_01,f,loop_valve):
    with open('input.txt') as f:
        if str(res_01) in f.read():
            loop_valve =+1
            return loop_valve
        ielse:
            w_loop = 1
    
    #

if __name__ == "__main__":
    for z in range(50):
        res01 = generator() ### string number function
        global loop_valve
        loop_valve =1
        w_loop == 0

        while w_loop == 0: ### Repeat until a certain condition is met
                if loop_valve == 100:
                    break
                    print("[VALVE-BREAK]")
                else:
                    Validator(res_01,f,loop_valve)
    print("[INFO]: end")
thank you in advance :)
Reply
#2
You are using global wrong. You do not need to use "global loop_valve" in the for loop. The for loop is running in the global context, and any variables created in the for loop are global. You don't declare any variables in Validate() as global, so all the variables are local. w_loop in Validate is not the same variable as w_loop outside Validate().

loop_value has a different problem. loop_value inside Validate() is a local variable. Any changes to loop_valve inside Validate have no effect on loop_valve outoside Validate(). Validate() returns a value, but you don't use the return value anywhere.

And there is another problem that this code:
loop_valve =+1
Is the same as
loop_valve = 1
Did you mean this:
loop_valve += 1
Which is the same as:
loop_valve = loop_valve + 1
Why does Validator open a file every time? Does input.txt change? If input.txt changes, why does it change? Are you using a file to communicate between the generator and the validator? Why? Are they different processes?
llxxzz likes this post
Reply
#3
Why do you need to check 100 times whether the same res01 is in input.txt ?
llxxzz likes this post
Reply
#4
(Jul-31-2023, 03:17 PM)deanhystad Wrote: You are using global wrong. Validator needs to declare loop_valve as global so "loop_valve =+1" doesn't create a local variable named "loop_valve" and assign it the value "loop_valve + 1". You do not need to use "global loop_valve" in the for loop. The for loop is running in the global context, and any variables created in the for loop are global.

Why does Validator open a file every time? Does input.txt change? If input.txt changes, why does it change? Are you using a file to communicate between the generator and the validator? Why? Are they different processes?

Thanks for your reply.
  • Input.txt changes.. Once I am able to workaround this issue, if the generated token/number isn't in the input.txt, another function will append the number into the input.txt.

  • Input.txt is the only file. The idea is to generate an unique token on each run.

  • The 100 times loop is meant to be the number of unique generated tokens written in the input.txt (from function generator)
Reply
#5
Like this?
from string import ascii_lowercase
import random


class Validator:
    """Validate word.  A wordis valid if we haven't used it before."""
    def __init__(self, history_file):
        """Load previous words from history file.
        Only use history file if you need to remember words from previous program runs.
        """
        self.history_file = history_file
        try:
            with open(history_file, "r") as f:
                self.history = [word.strip() for word in f.readlines()]
        except IOError:
            self.history = []

    def __enter__(self):
        """For use as a context manager."""
        return self

    def __exit__(self, *args):
        """For use as a context manager."""
        if self.history_file:
            self.save()

    def valid(self, word):
        """Return True if word is valid."""
        if word in self.history:
            return False
        self.history.append(word)
        return True

    def save(self, filename=None):
        """Save list of words to file."""
        filename = filename or self.history_file
        if filename:
            with open(self.history_file, "w") as f:
                f.write("\n".join(self.history))


def generator():
    """Something that makes random strings."""
    return "".join(random.choices(ascii_lowercase, k=random.randint(3, 20)))


with Validator("input.txt") as v:
    things = []
    while len(things) < 50:
        thing = generator()
        if v.valid(thing):
            things.append(thing)
Reply
#6
I'm afraid it's an XY problem. You are asking about your attempted solution rather than your actual problem. Do you really need a file? Why? etc
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  change value of a global variable across all modules aster 5 5,040 Jan-01-2019, 06:42 PM
Last Post: aster
  Modules issue, pip3 download modules only to pyhton3.5.2 not the latest 3.6.1 bmohanraj91 6 8,474 May-25-2017, 08:15 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020