5

I love named parameters in Python

Submitted by twovests in programming

say you got a function to draw a circle.

draw_circle(float x, float y, float r, string line_color, string fill_color)

In Python, you don't need to know the order of the arguments! You can do

draw_circle(r=16, x=32, y=32, line_color="#ff0000", fill_color = "#00ff00")

(Note that the order of arguments differ.)

I really like that, and just learned that it's not in most other languages :(

Comments

You must log in or register to comment.

2

flabberghaster wrote

I think my favorite feature along these lines is splatting.

def draw_circle(x, y, r, line_color="#ff0000", fill_color="#00ff00"):
    ...

args = [10, 20, 2]
kwargs = {"line_color": "#0000ff", "fill_color": "#ff0000"}
draw_circle(*args, **kwargs)

it works the other way too. It's such a useful feature!

2

twovests wrote

omg! i never knew you could do that! I knew about *args and **kwargs for variable-argument functions but I never saw this usage