I am learning Python and I am doing a partial with the Django framework , and at the moment of modifying the data of settings.py
, I have found that either diccionarios
and tuplas
contains a comma ( , ) at the end and I cannot understand what its function is.
dictionary insidesettings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', #<-- esta coma
]
tuple insidesettings.py
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) #<-- esta coma
Without her I can't do amigrate
Why can't I do without it?
I have done
tuplas
anddiccionarios
without it at the end but it has never given me a syntax error. Why?What is the function of being at the end of a tuple or dictionary?
I am working with:
- Python 3.7.4
- Django 2.2.7
In general, it is recommended, as a good practice, to leave the comma at the end.
The next:
It allows a number of things:
If you add a new line it is usually a common problem to forget the comma of the previous element/line with which you will get an unwanted error that may jump or go unnoticed.
In the diffs you will see less noise since only one line changes, instead of two (the first line changes when you add the comma and the second is the new line you introduce).
You can see this more detailed and developed here .
In the case of the dictionary that you show you could omit the comma without problems (but don't). In the case of the tuple that you show, it is necessary that you add the comma. A tuple is defined by separating elements with commas. The parentheses are not necessary but are added to make it more readable. If you don't put that comma to a tuple an element won't be a tuple. The next:
is equal to
If you
STATIFILES_DIRS
are expecting a tuple the above will fail.Instead, the following:
It is equivalent to: