Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20543

Re: question about function pointer

From Nobody <nobody@nowhere.com>
Subject Re: question about function pointer
Date 2012-02-17 09:55 +0000
Message-Id <pan.2012.02.17.09.55.11.504000@nowhere.com>
Newsgroups comp.lang.python
References <mailman.5911.1329465188.27778.python-list@python.org>
Organization Zen Internet

Show all headers | View raw


On Fri, 17 Feb 2012 16:53:00 +0900, Zheng Li wrote:

> def method1(a = None):
> 	print a
> 
> i can call it by
> method1(*(), **{'a' : 1})
> 
> I am just curious why it works and how it works?
> and what do *() and **{'a' : 1} mean?

In a function call, an argument consisting of * followed by an expression
of tuple type inserts the tuple's elements as individual positional
arguments. An argument consisting of ** followed by an expression of
dictionary type inserts the dictionary's elements as individual keyword
arguments.

So if you have:

	a = (1,2,3)
	b = {'a': 1, 'b': 2, 'c': 3}

then:

	func(*a, **b)

is equivalent to:

	func(1, 2, 3, a = 1, b = 2, c = 3)

> when I type *() in python shell, error below happens
> 
>   File "<stdin>", line 1
>     *()
>     ^
> SyntaxError: invalid syntax

The syntax described above is only valid within function calls.

There is a similar syntax for function declarations which does the reverse:

	> def func(*a, **b):
	    print a
	    print b

	> func(1, 2, 3, a = 1, b = 2, c = 3)
	(1, 2, 3)
	{'a': 1, 'c': 3, 'b': 2}

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

question about function pointer Zheng Li <dllizheng@gmail.com> - 2012-02-17 16:53 +0900
  Re: question about function pointer Nobody <nobody@nowhere.com> - 2012-02-17 09:55 +0000
    Re: question about function pointer 88888 Dihedral <dihedral88888@googlemail.com> - 2012-02-17 05:20 -0800

csiph-web