Redefining name 'user_status' from outer scope (line 236)
238 match request.method:
239 case "GET":
240 try:
241 user_status = UserStatus.objects.get(user=request.user)242 except UserStatus.DoesNotExist:
243 return Response(
244 {"error": "User does not have a UserStatus"}, status=404
Redefining name 'profile' from outer scope (line 162)
214def profile_is_complete(request) -> Response:
215 """Determine if the user is authenticated and return their SocialProfile"""
216 try:
217 profile = Profile.objects.get(user=request.user)218 except Profile.DoesNotExist:
219 return Response({"error": "User does not have a Social Profile"}, status=404)
220 if request.method == "GET":
Redefining name 'profile' from outer scope (line 162)
195def user_profile(request, username) -> Response:
196 """Determine if profile for username exists"""
197 try:
198 profile = Profile.objects.get(user__username=username)199 except Profile.DoesNotExist:
200 return Response({"error": "User does not have a profile"}, status=404)
201
Redefining name 'profile' from outer scope (line 162)
162def profile(request) -> Response:
163 """Determine if the user is authenticated and return their profile"""
164 try:
165 profile = Profile.objects.get(user=request.user)166 except Profile.DoesNotExist:
167 return Response({"error": "User does not have a profile"}, status=404)
168
Description
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
Bad practice
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
Preferred:
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Bad practice
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
Preferred:
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()