Question

Could someone explain me this behaviour:

REQUIRED_USER_FIELDS = ["email"]
for field in REQUIRED_USER_FIELDS:
    # field = 'email' -> OK for me, expected behaviour

REQUIRED_USER_FIELDS = ("email")
for field in REQUIRED_USER_FIELDS:
    # field = 'e' -> Why???

Thanks

Was it helpful?

Solution

("email") is not a tuple. It is just a string in parenthesis.

You need to place a comma to make it a tuple:

REQUIRED_USER_FIELDS = ("email",)
#                        here--^

Otherwise, your for-loop will iterate through the string "email" itself.


You should remember that it is the comma that creates a tuple, not the parenthesis (if any):

>>> ("email")
'email'
>>> "email"
'email'
>>> ("email",)
('email',)
>>> "email",
('email',)
>>>

The reason why you see parenthesis so often though is that:

  1. They make it clearer that you are creating a tuple.

  2. You need them in some places, such as when calling a function:

    >>> def func(arg):
    ...     return arg
    ...
    >>> # This fails because "a", "b" is treated as 2 separate arguments
    >>> func("a", "b")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func() takes 1 positional argument but 2 were given
    >>>
    >>> # This works because ("a", "b") is treated as 1 argument (a tuple)
    >>> func(("a", "b"))
    ('a', 'b')
    >>>
    

OTHER TIPS

Tuple which contains just one element is need to be write as below.

(something,)

You can ensure it by doing:

>>> tuple(["email"])
('email',)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top