How do you create python methods (signature and content) in code?

I created a method that generates a new class and adds some methods to the class, but there is a strange error, and I'm not sure what happens:

def make_image_form(image_fields):
    ''' Takes a list of image_fields to generate images '''
    images = SortedDict()
    for image_name in image_fields:
        images[image_name] = forms.ImageField(required=False)
    new_form = type('ListingImagesForm2', (forms.BaseForm,), {'base_fields' : images})
    #now we add the validation methods to the class
    for image_name in image_fields:
       print "image name is: ", image_name
       setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))
    #Add the _clean_photo method to the class
    setattr(new_form, '_clean_photo', _clean_photo)
    return new_form

This is my method that takes a list of image_fields (I'm building a site in Django) and it creates a whole bunch of ImageField fields and creates a ListingImagesForm2 class and assigns image fields to the class.

The problem is the creation of methods and, more specifically, the content of the method.

In the loop:

for image_name in image_fields:
    print "image name is: ", image_name
    setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))

Method signatures are created correctly (for example, clean_pic_1, clean_pic_2 ...), but I think that there is a problem in the lambda expression, since the _clean_photo method is always called with the same image name (which turns out to be the last image name in the image_fields list) .

- (), -?

- _clean_photo _ for?

+3
1

Python , , . :

for image_name in image_fields:
    print "image name is: ", image_name
    setattr(new_form, 'clean_' + image_name, 
            lambda self, iname=image_name: self._clean_photo(iname))

Python -, ( ).

+4

Source: https://habr.com/ru/post/1702539/


All Articles