Redefining name 'GroupDetails' from outer scope (line 9)
31
32 def validate(self, data):
33 email = data["email"]
34 GroupDetails = GroupDetails.objects.filter(group=data["group"]) 35
36 if GroupDetails.filter(email=email).exists():
37 raise ValidationError({"msg": "email already exists in this group"})
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()