starlette icon indicating copy to clipboard operation
starlette copied to clipboard

"url_for" signature prevents use of "name" in path arguments

Open dansan opened this issue 6 years ago • 4 comments

I'm implementing an API in Fastapi, using APIRouters for different resources. When I want to get the URL of an item in a resource, I use the starlette.requests.Request objects url_for() method. When I have a function with a path /resource/{name} I cannot use url_for() to get the URL, because it will result in:

TypeError: url_for() got multiple values for argument 'name'

Reproduce with:

def func(name, **path_params):
    pass
func("foo", name="bar")

As a workaround I have renamed the path variable in my API, but name was really fitting, and what I wanted to use, and not at all an uncommon variable name. From what I see, name in url_for() seems to be the name of the referenced method in APIRouter. Changing the signature of url_for() to use router_method instead of name, would make a collision with the key word arguments in path_params less likely. Result would be:

def url_path_for(self, router_method: str, **path_params: str) -> URLPath:

An inspection on the used arguments could be used to log a deprecation warning until the next release, when url_path_for() is used with a named name=... instead of positional.

If this proposal is acceptable, I'd create a PR.

dansan avatar Aug 21 '19 09:08 dansan

I’d suggest we change it to an unnamed argument. We could do this by changing the argument signature to *args, **kwargs, and ensuring that len(args) == 1

lovelydinosaur avatar Aug 21 '19 17:08 lovelydinosaur

PR: https://github.com/encode/starlette/pull/611

dansan avatar Aug 22 '19 16:08 dansan

Rebased on top of current master.

dansan avatar Jan 01 '22 13:01 dansan

I was hit by that issue just today and would like to see it merged.

chbndrhnns avatar Mar 07 '22 09:03 chbndrhnns

Had a problem here too and took me around 30mins to find out why. Looked if there is an issue: Yeah. It is. Since 2019.

tzmara avatar Mar 01 '23 11:03 tzmara