Need help understanding Python code with @, * args and ** kwargs

I am new to Python and confused by this part of the code from the Boto project:

class SubdomainCallingFormat(_CallingFormat):
    @assert_case_insensitive
    def get_bucket_server(self, server, bucket):
        return '%s.%s' % (bucket, server)

def assert_case_insensitive(f):
    def wrapper(*args, **kwargs):
        if len(args) == 3 and not (args[2].islower() or args[2].isalnum()):
            raise BotoClientError("Bucket names cannot contain upper-case " \
            "characters when using either the sub-domain or virtual " \
        "hosting calling format.")
        return f(*args, **kwargs)
    return wrapper

Trying to understand what is happening here.

  • What does the @ at symbol mean @assert_case_sensitive?
  • What do args mean *args, **kwargs?
  • What does it mean f? ' '

Thank!

+3
source share
4 answers

In this particular case assert_case_sensitive, a function wrapping function, otherwise known as a decorator .

. , - . assert_case_insensitive wrapper, , assert_case_insensitive.

, . , , .

closure, Python , . .

assert_case_insensitive , . , . assert_case_insensitive , , . *args **kargs .

*something (aka positional), . **something , . *something **something .

, . *(iterable sequence) , **(dictionary) .

, wrapper , . , , - .

+4

@ decorator.

, / /.

"f" , . -

@decorate
def whizbang(): pass

def whizbang(): pass
whizbang = decorate(whizbang)

, - , , . .

+6

@ @assert_case_sensitive?

@- , :

@decor
def func(arg):
    pass

:

def func(arg):
    pass
func = decor(func)

args, ** kwargs?

* args ** kwargs - . C varargs, * args tuple, ** kwargs dict.

def foo(a, *arg, **kwarg):
    print a      # prints 1
    print arg    # prints (2, 3)
    print kwarg  # prints {'foo': 4}

foo(1, 2, 3, foo=4)

'f'?

python. python, , . , . C, .

+4

@assert_case_sensitive :

- Python, , . Python Java ; , @ :

@viking_chorus
def menu_item():
    print "spam"

def menu_item():
    print "spam"
menu_item = viking_chorus(menu_item)
+1

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


All Articles