How to get through Python args and kwargs?

Although I have a general understanding (I think) of Python * args and ** kwargs, I am having trouble understanding how to pass them from one function to another. Here is my model:

from pdb import set_trace as debug
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return u'%s' % self.name

    def save_name_for(self, *args, **kwargs):
        self.name = 'Alex'
        return self

    def save_name(self, *args, **kwargs):
        debug()
        self.save_name_for(self, args, kwargs)
        self.save()

I divided the name preservation into two functions above. That way, I can test the logic that I would normally set everything in the save_name method, instead checking the save_name_for method.

When I run this in the interpreter and stop in the save_name method, as expected, I see the following:

(Pdb) args
self =
args = (1, 2)
kwargs = {'last': 'Doe', 'first': 'John'}

If I then go to the save_name_for method, I see the following:

(Pdb) args
self =
args = (<Person: >, (1, 2), {'last': 'Doe', 'first': 'John'})
kwargs = 

Is there a way to pass the kwargs received by the save_name method directly to the save_name_for method so that they appear in the latest kwargs? I would like to see something like this in the save_name_for method namespace:

(Pdb) args
self =
args = (1, 2)
kwargs = {'last': 'Doe', 'first': 'John'}   # <= I want this

, save_name, save_name_for, . , , args - ...

kwargs = args[2]

... . args [2] - ( ). Pythonic ?

+4
2

, :

self.save_name_for(*args, **kwargs)

, self; save_name_for .

+5

* ** .

  • ,

    def save_name_for(self, *args, **kwargs):
    

    , . , args , kwargs .

  • ,

    args = (1, 2)
    kwargs = {'last': 'Doe', 'first': 'John'}
    self.save_name_for(*args, **kwargs)
    

    * ** . args iterable, kwargs dict-like. args , / kwargs . ,

    self.save_name_for(*args, **kwargs)
    

    self.save_name_for(1, 2, last='Doe', first='John')
    

. saltycrane .

+7

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


All Articles