Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we extend Base.@kwdef to override default show() to print via keyword argument construction? #37518

Open
NHDaly opened this issue Sep 10, 2020 · 4 comments

Comments

@NHDaly
Copy link
Member

NHDaly commented Sep 10, 2020

julia> Base.@kwdef struct Statistics
           seen_count::Int = 0
           recomputed_count::Int = 0
           invalidated_count::Int = 0
       end
Statistics

julia> stats = Statistics(seen_count=3, recomputed_count=2)
Statistics(3, 2, 0)

People use Base.@kwdef for structs where they want users to set the fields by name. Can we extend this macro to also provide a definition for Base.show() that prints the struct with all of its args by name, something like this?:

julia> stats = Statistics(seen_count=3, recomputed_count=2)
Statistics(seen_count = 3, recomputed_count = 2, invalidated_count = 0)

EDIT: oh, duh, I guess this isn't possible because if the user then wants to provide their own Base.show, there would be a double-definition error. :/

Is there any clever way around that?

Or could we maybe have something like @kwdef_and_show? Or another macro @kwshow that could be composed with this macro? :)

@NHDaly
Copy link
Member Author

NHDaly commented Sep 10, 2020

Or maybe via a parameter, like @kwdef kwshow=true struct S ... end?

@yuyichao
Copy link
Contributor

A much cleaner way is to simply have a function that does the printing using keyword argument syntax and the user can simply use it with a single line of code.

@NHDaly
Copy link
Member Author

NHDaly commented Sep 10, 2020

Mm that's a good idea, @yuyichao.

Hehe I realized I could just do this instead of asking, so i've implemented the kwshow() argument based approach here:
#37519

But now that i'm here and see your comment, you're probably right.. Open to changing it per yours and others' feedback! :)

@nickrobinson251
Copy link
Contributor

I think Parameters.jl defines a show method when using @with_kw
e.g.

julia> using Parameters

julia> @with_kw struct Statistics
              seen_count::Int = 0
              recomputed_count::Int = 0
              invalidated_count::Int = 0
          end
Statistics

julia> stats = Statistics(seen_count=3, recomputed_count=2)
Statistics
  seen_count: Int64 3
  recomputed_count: Int64 2
  invalidated_count: Int64 0

Maybe other packages do too :)
I don't know how it differs from Base's @kwdef (I think PkgTemplates switched to this over @kwdef for supporting Julia v1.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants