django-rest-framework
django-rest-framework copied to clipboard
list in ListModelMixin could overwrite the builtins list method of python and causes error
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>
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.
Architecture Designer Apparel Manufacture
closing, as discussed in #9159
@tomchristie can you close this issue then?