2

I have defined a series of python objects of class dofiles which have a name and some empty lists.

class dofile:
    name = ""
    lines = []
    inputs = []
    outputs = []
    intermediates = []

I am using the following code to loop through a list of these dofile objects called dofiles (after I have run code which fills up the lines list for each object which I know works correctly). The problematic code detects the phrase using and the word after it, then should append the word to the inputs list for each object.

for dofile in dofiles:
    for line in dofile.lines:
        # using
        using_tups = re.findall(r'(using)\s([^\s,]+)', line)
        for tuple in using_tups:
            dofile.inputs.append(tuple[1])

However, I am ending up with the word appended to the inputs list of all of the dofile objects in dofiles. (ex: print(dofiles[0].inputs) and print(dofiles[1].inputs) return the same thing although they scan different files).

Am I missing something about how objects, lists, or loops work in Python?

I've tried (dofile.inputs).append(tuple[1]) but it doesn't seem to make a difference.

Thanks.

1
  • 1
    A perhaps useful tip: if you want to check if two variables are merely identical, or if they in fact refer to the same object, you can use "is". For instance, dofiles[0].inputs is dofiles[1].inputs will evaluate as True in your case, signalling that those are the same list. Commented Aug 31, 2020 at 18:25

1 Answer 1

5

You're creating static vars, variables that are consistent across all dofile class instances. Essentially what is going on is that instead of having an "inputs" list for all dofile instances, you have one list that each one points to. To make them specific to a single instance, initialize them inside the __init__ class:

class dofile:
    def __init__(self):
        self.name = ""
        self.lines = []
        self.inputs = []
        self.outputs = []
        self.intermediates = []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.