Python Forum
Being explicit about the items inside a tuple argument - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Being explicit about the items inside a tuple argument (/thread-22940.html)



Being explicit about the items inside a tuple argument - rudihammad - Dec-04-2019

Hello, this might be a strange question but I was wondering if I can give a hint about
the tuple argument items. For isntance, in the example bellow:

# I don't want 2 arguments
def matchObjects(source=None, target=None):
    pass

# I want one argument like this
def matchObjects(objects=(None, None)):
    pass
The thing that I don't like in the tuple argument "objects=(None, None)" is that unless you read the docstring
you don't know which item is the source and which one is the target.
Is it possible to make that tuple more explicit about what it represents?

I am using python 2.7.

thanks
R


RE: Being explicit about the items inside a tuple argument - Gribouillis - Dec-04-2019

You could use a collections.namedtuple
>>> from collections import namedtuple
>>> Pair = namedtuple('Pair', 'source target')
>>>
>>> def matchObjects(pair=Pair(source=None, target=None)):
...     print(pair)
... 



RE: Being explicit about the items inside a tuple argument - rudihammad - Dec-04-2019

thanks, that might be an option, I'll think about it.


RE: Being explicit about the items inside a tuple argument - perfringo - Dec-04-2019

As you don't enforce keyword arguments anyone can call function without keyword arguments (and without arguments at all) and not be any wiser. Maybe you should use *,?

>>> matchObjects(None, None):      # user: hmmm.... is source first or second
>>> matchObjects()                 # ursr: hmmm.... what is this function doing?