django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

list in ListModelMixin could overwrite the builtins list method of python and causes error

Open ghostinthefingers opened this issue 2 years ago • 3 comments
trafficstars

Discussed in https://github.com/encode/django-rest-framework/discussions/9159

Originally posted by ghostinthefingers November 7, 2023 list in ListModelMixin could overwrite the builtins list method of python and causes error, isn't it better to change the name of list here?

class SomeViewSet(viewsets.ModelViewSet):
    def list(self, request, *args, **kwargs):
        return Response(
            {"message": "List function is not offered in this path"}, 
            status.HTTP_405_METHOD_NOT_ALLOWED
        )

then wanna use the builtins list function of python in my code and I get an error, because I already overwrote it:

    def create(...):
        return list('123')
```</div>

ghostinthefingers avatar Nov 20 '23 21:11 ghostinthefingers

SomeViewSet.list is a method of the SomeViewSet class. Another clue is that the first argument passed to the method is self which is an instance of a class. You can call your method in two ways, both that involve either referencing the SomeViewSet class or an instance of it and hence do not overwrite the builtin.

s = SomeViewSet()  # instance of your class called s
s.list(req, *args, **kwargs)  # this instance method is bound to the instance s

x = SomeViewSet()  # instance of your class x
SomeViewSet.list(x, req, *args, **kwargs)  # now list is just a regular function that expects an instance as first argument

The builtin list type constructor importantly does not get called like a user defined method. You call it by writing list([iterable]) with no reference to a class or instance. If you really wanted to override the builtin, you'd write a function at the top level of your script with the same name.

I believe you have an error that is to do with something else entirely. I would highly recommend providing a stacktrace and the entire error when you post your question so that someone can help.

MarkoM-dot avatar Nov 28 '23 10:11 MarkoM-dot

Architecture Designer Apparel Manufacture

ptsda avatar Nov 28 '23 10:11 ptsda

closing, as discussed in #9159

lovelydinosaur avatar Nov 28 '23 16:11 lovelydinosaur

@tomchristie can you close this issue then?

codespearhead avatar Mar 13 '24 11:03 codespearhead