Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I hard-code variables in a dynamically created function in python?

I have the following python3 code

class Test:
    pos = [0,0]
    actions = []
    def bar(self, target):
        for i in target:
            def _():
                print(i,end="")
            self.actions.append(_)
foo = Test()
foo.bar("abcd")
for i in foo.actions:
    i()

Which is meant to output:
abcd

but instead it outputs:
dddd

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m pretty sure the function is using the value of i when executing (the last value i had) and not i’s value the function _ is declared, which is what I want.

>Solution :

The general solution to this is to store the value as a default parameter value, like this:

class Test:
    pos = [0,0]
    actions = []
    def bar(self, target):
        for i in target:
            def _(i=i):  # This is the only changed line
                print(i,end="")
            self.actions.append(_)
foo = Test()
foo.bar("abcd")
for i in foo.actions:
    I()

>>> abcd
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading