0

I have a piece of code which I just cannot debug. Basically env is always the same object in every iteration (has the same reference).

I know it has something to do with references being copied over, but I do not know where this happens. Can you please point out the issue if you can find it?

I made a small runnable example which reproduces my issue:

import copy


class Params:
    def __init__(self, port):
        self.__port = port

    def set_port(self, port):
        self.__port = port

    def get_port(self):
        return self.__port


class Env:
    def __init__(self, params):
        self.params = params


def make(env_class, params, ports):
    env_fs = []
    for port in ports:
        params_ = copy.deepcopy(params)
        params_.set_port(port)
        env = env_class(params_)
        env_fs.append(lambda: env)
    return env_fs


if __name__ == "__main__":
    fs = make(Env, Params(0), ports=[0, 1, 2, 3])
    for f in fs:
        print(f().params.get_port(), id(f()))

This outputs:

3 139624063550224
3 139624063550224
3 139624063550224
3 139624063550224

Process finished with exit code 0

Every object has the same reference.

Philipp
  • 652
  • 2
  • 10
  • 28
  • 1
    TL;DR: Creating functions in a loop (or any other case where you're creating multiple functions that all rely on a changing variable in the enclosing scope) has this "issue". See the linked post for ways around this. – Carcigenicate May 05 '21 at 16:35
  • Thanks! This is really cool! If you want to write an answer, I would accept it. – Philipp May 05 '21 at 16:46
  • That's the purpose of the question I linked to. Instead of answering, I closed it as a dupe pointing to existing answers that explain this well. – Carcigenicate May 05 '21 at 16:55

0 Answers0