Python args doesn't work if it doesn't have a position reference

def test_stats(team, *args): if not args: [do some stuff] else: team_fixtures = (Fixtures.objects.filter(home_team=team_details.id) | Fixtures.objects.filter(away_team=team_details.id))/ .filter(fixture_datetime__lt=datetime.now()).filter(fixture_datetime__year=args[0]) 

And for reference - args:

 date_year = datetime.now().year 

for this request to work, I need to reference args as

 .filter(fixture_datetime__year=args[0]) 

because if i use

 .filter(fixture_datetime__year=args) 

I get an error message:

Argument

int () should be a string, a byte object, or a number, not a 'Tuple'

I understand that he considers it a tuple, although this is only one value, but when I do the following in the terminal

 type(date_year) 

I'm coming back.

Why do I need to reference a position here when it looks like a single return value?

+5
source share
2 answers

The * -prefixed argument is always a tuple. It captures 0 or more additional positional arguments. You can call the test_stats() function with 3 or 20 or 100 additional arguments (outside of the explicit team argument), and they will all be part of the args tuple in the function:

 >>> def foo(*args): return args ... >>> foo() () >>> foo(42) (42,) >>> foo(1, 2, 3) (1, 2, 3) 

If you need one optional argument, make it the default keyword argument, for example None :

 def test_stats(team, optional=None): if optional is None: # ... else: team_fixtures = ( Fixtures.objects.filter(home_team=team_details.id) | Fixtures.objects.filter(away_team=team_details.id)) .filter(fixture_datetime__lt=datetime.now()) .filter(fixture_datetime__year=optional) ) 
+4
source

If you know that you are receiving the date as the second argument, then explicitly define it in the signature

 def test_stats(team, date): 

If you can pass both there and then, use the keyword arguments

 def test_stats(team, date=None, something_else=None): 

*args should be used only if you want to pass a sequence of arguments without creating a sequence in advance

 def get_integers(*args): return args >>> get_integers(1, 3, 4, 8, 9, 11) (1, 3, 4, 8, 9, 11) 

*args is a tuple, and **kwargs is a dictionary.

+1
source

Source: https://habr.com/ru/post/1238137/


All Articles