Python list/tuple pop return itself?

Viewed 32

This may be rudimentary, but after some searches I couldn't find a way, but pop(), del, remove().

I have the following python (django) code:

class PageSerializer(serializers.ModelSerializer):
    # ..
    class Meta:
        model = Page
        fields = ('id','user','created_at','title','url','og_image','desc','voters','is_public','updated_at', 'pagevote','pageidenticals',)
        read_only_fields = ('id','user','created_at','voters','is_public','updated_at','pagevote','pageidenticals')

Notice the redundancy on the fields and read_only_fields. The only difference of the two is title','url','og_image','desc.

So I just want to reduce the code in read_only_fields, like this pseudo code:

class PageSerializer(serializers.ModelSerializer):
    # ..
    class Meta:
        model = Page
        fields = ('id','user','created_at','title','url','og_image','desc','voters','is_public','updated_at', 'pagevote','pageidenticals',)
        read_only_fields = fields.chomps(['title','url','og_image','desc',])

Since it's on a class, adding an extra pop() like you do in a def method is not an option. So, is there a way?

2 Answers

Seems like a job for set and its difference operator:

fields = ('id','user','created_at','title','url','og_image','desc','voters','is_public','updated_at', 'pagevote','pageidenticals',)
read_only_fields = tuple(set(fields)-{'title','url','og_image','desc'}))
print(read_only_fields)

Result:

('id', 'created_at', 'updated_at', 'pagevote', 'user', 'is_public', 'pageidenticals', 'voters')

Just be careful that the order preservation is an implementation detail of CPython, it is not guaranteed to stay the same in the future. So the following alternative might be more appropriate if you absolutely need the order guarantee

tuple(x for x in fields if x not in {...})

Python set provides with a function symmetric_difference which basically returns all the items present in given sets, except the items in their intersections.

Try this :

fields = ('id','user','created_at','title','url','og_image','desc','voters','is_public','updated_at', 'pagevote','pageidenticals',)

read_only_fields = ('id','user','created_at','voters','is_public','updated_at','pagevote','pageidenticals')

final_output = set(fields).symmetric_difference(set(read_only_fields))

print(final_output)

OUTPUT :

{'og_image', 'url', 'desc', 'title'}
Related