I am in the middle of a development in Django and we got some doubts about if we should use or not constants in the project. Exactly the situation is to use constants everywhere or not (we know constants in Django are not really read-only).
There are 2 scenarios and I would like to get your opinion about which one is better for you and why:
class CONST():
def NAME(): return "name"
def SURNAME(): return "surname"
def ZIPCODE(): return "zipcode"
def CITY(): return "city"
def CREATED(): return "created"
from constants import CONST
class RegisterAdmin(admin.ModelAdmin):
list_display = (CONST.NAME(),CONST.SURNAME(),CONS.ZIPCODE())
list_filter = [CONST.ZIPCODE(),CONST.CITY()]
search_fields = [CONST.NAME(), CONST.SURNAME()]
date_hierarchy = CONST.CREATED()
from constants import CONST
class Register(models.Model):
name = models.CharField(CONST.NAME(), max_length=25)
surname = models.CharField(CONST.SURNAME(), max_length=25)
zipcode = models.IntegerField(CONST.ZIPCODE())
city = models.CharField(CONST.CITY(),max_length=20)
... and any view etc where you use text will be using contants ...
class RegisterAdmin(admin.ModelAdmin):
list_display = ("name","surname","zipcode")
list_filter = ["zipcode","city"]
search_fields = ["name","surname"]
class Register(models.Model):
name = models.CharField("name", max_length=25)
surname = models.CharField("surname", max_length=25)
zipcode = models.IntegerField("zipcode")
city = models.CharField("city",max_length=20)
I like the most the second scenario (I have been programming python from 2004), for me it looks more efficient, clear and easy to understand. The first scenario (proposed from Java/PHP programmers that now writes Python code) has the advantage that it helps the developer to detect that it made a mistake writing the "constant" so it is easier to detect errors and also it makes easier and quicker "massive changes" on this kind of texts without refactorizing the source code.
I would like to know which source code you would write or use and why.
Thank you,
Scenario 1 is awful. Unfortunately I know all too well the problems of working with Java/PHP developers who are learning python.
Perhaps you can compromise with those guys by proposing the use of python enums to address their concern. These are built-in in python 3.4+, and have been backported as far back as 2.4.
from enum import Enum
class Constant(Enum):
name = "name"
surname = "surname"
zipcode = "zipcode"
city = "city"
created = "created"
Now you can change the "values", say for example changing zipcode to be "potato" in the enum definition, whilst still using the name Constant.zipcode.value everywhere else in source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With