# How to get default values of a functions kwargs

**URL:** https://discourse.julialang.org/t/how-to-get-default-values-of-a-functions-kwargs/66158
**Category:** General Usage
**Tags:** kwargs
**Created:** [August 10, 2021, 11:28pm UTC](https://discourse.julialang.org/t/how-to-get-default-values-of-a-functions-kwargs/66158 "2021-08-10T23:28:18Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![NicoD](https://avatars.discourse-cdn.com/v4/letter/n/13edae/32.png) [@NicoD](https://discourse.julialang.org/u/NicoD)
#### Post date: [August 23, 2024, 10:03am UTC](https://discourse.julialang.org/t/how-to-get-default-values-of-a-functions-kwargs/66158/2 "2024-08-23T10:03:19Z")

</div>

I came across the same need, and wrote a function for that.

From [this stackoverflow similar question](https://stackoverflow.com/questions/56759266/how-to-get-the-default-value-of-an-optional-parameter-julia), it seems that `code_lowered` is the only function that holds the kwargs values, but in a confusing format if they are not “basic” types (Nothing or a custom type for example). Fortunately the values can be retrieved back!

```julia
"""
    get_kwargs(func_name::Function, args_types::Tuple)
Return a NamedTuple containing each supported kwarg and its default value for a given method.
# Arguments
- `func_name` is the name of the function
- `args_types` is a tuple of argument types for the desired method
"""
function get_kwargs(func_name::Function, args_types::Tuple)
    kwargs_names = Base.kwarg_decl(methods(func_name, args_types)[1])
    l = length(kwargs_names)
    if l==0
        # no kwargs
        return (;)
    else
        # lowered form of the method contains kwargs default values, but some are hidden
        code = code_lowered(func_name, args_types)[1].code
        str_code = ["$c" for c in code]
        # get index corresponding to the function
        index = findall(x -> occursin("$func_name", x), str_code)[1]
        # get lowered value of each kwarg
        values = code[index].args[2:2+l-1]
        # get back the original value according to the lowered value type
        kwargs_values = map(v -> 
            if v isa Core.SSAValue
                eval(code[v.id])
            elseif v isa GlobalRef
                eval(v)
            else 
                v
            end
            , values)
        # reconstruct kwargs
        NamedTuple(zip(kwargs_names, kwargs_values))
    end
end

```

Example function to test it:

```julia
struct MyType
    m::Int64
    t::String
end

myfunc(x::Float64; a=2, b=nothing, c="3", d=34.2, e=MyType(2,"two")) = println("test")

```

Retrieving kwargs:

```julia
get_kwargs(myfunc, (Float64,))

```

Result:

```julia
(a = 2, b = nothing, c = "3", d = 34.2, e = MyType(2, "two"))

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-get-default-values-of-a-functions-kwargs/66158)._
