Conventions for defining a tuple / list
Let's say I have a list x = ['a','b','c']
to conditionally add a term to it:
if conditional:
x.append('d')
But I cannot do it for tuple ( x = ('a','b','c')
)
In both cases, there is a "clean" way of contingent alimony in the definition. Pseudocode:
X = (
'a',
'b',
'c',
'd' if Y,
'e' if Z,
)
In this case, the Django INSTALLED_APPS list of tuples and the URL list are used.
source to share
One way to do this - useful if you're going to generate content a tuple
lot - with a generator:
def gen_X():
yield 'a'
yield 'b'
yield 'c'
if Y:
yield 'd'
if Z:
yield 'e'
Then make tuple
from the generator results:
X = tuple(gen_X())
With a slightly modified version, you can also specify arguments that determine what the generator generates:
def gen_X(Y = True, Z = True):
yield 'a'
yield 'b'
yield 'c'
if Y:
yield 'd'
if Z:
yield 'e'
The nicest thing to do with a generator is that you don't need to store multiple sets of tuples in memory - the content and logic is contained in the generator. This way, you can iterate through many different versions of the same data at the same time, but it's all contained in only one place and generated on the fly as needed.
source to share
You can do something like this using a generator expression:
truth_table = {'a': True, 'b': True, 'c': True, 'd': Y, 'e': Z}
X = tuple(k for k,v in sorted(truth_table.items()) if v)
... or in one line:
X = tuple(k for k,v in sorted({'a': True, 'b': True, 'c': True, 'd': Y, 'e': Z}.items()) if v)
source to share