Skip to content

Keyword arguments affect methods dispatch #9498

@yuyichao

Description

@yuyichao

So this is an issue that I find after figuring out how the keyword arguments are currently implemented in Julia. It will probably not be an issue anymore if #2773 is implemented.

The document on methods says

Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

However, method dispatch actually behaves differently when doing a function call with or without keyword arguments. i.e.

julia> function f(::Integer)
       2
       end
f (generic function with 1 method)

julia> function f(::Number; kw...)
       1
       end
f (generic function with 2 methods)

julia> f(1)
2

julia> f(1; a = 2)
1

What happens here is that f.env.kwsorter only has one method defined and therefore when calling with keyword argument, f(::Integer) does not participate in method dispatch.

IMHO, there are several possible ways to fix it,

  1. Fix the document to include this behavior. This should be the easiest fix but will probably make the whole keyword argument/optional argument/multiple dispatch more confusing especially for someone who does not know how it all works behind the scene. (It's already quite confusing/surprising that anonymous function does not support keyword argument for someone (like me) that expects python-like keyword argument implementation.)

  2. Having an entry (that just throw an error) in env.kwsorter even for methods that does not take keyword arguments. This can also avoid the following confusing abuse of overriding method

    julia> function f(::Number; kw...)
           1
           end
    f (generic function with 1 method)
    
    julia> function f(::Number)
           2
           end
    f (generic function with 1 method)
    
    julia> f(1)
    2
    
    julia> f(1; a = 2)
    1

    This is probably the easiest way to fix the code and is consistent with the best long term behavior.

  3. Fix Keyword arguments for anonymous functions #2773 and let the method themselves handle keyword argument dispatch. Since Keyword arguments for anonymous functions #2773 is on 1.0 milestone, hopefully this will be eventually be implemented.

Metadata

Metadata

Assignees

Labels

bugIndicates an unexpected problem or unintended behaviorcorrectness bug ⚠Bugs that are likely to lead to incorrect results in user code without throwingdocsThis change adds or pertains to documentationkeyword argumentsf(x; keyword=arguments)needs decisionA decision on this change is neededtypes and dispatchTypes, subtyping and method dispatch

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions