Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pack a lot of constructor parameters into separate object in python?

For example this piece of code creates a label with some content
which can be text, bitmap etc

label1 = tk.Label(text="Hello", font=("Arial",32,"bold"), bg="grey", fg="red",width=200,height=200) #and so on...

I cannot really refactor how tk.Label constructor handle things nor change it.
In my case I would like to configure text / font in a separate object.
All styling in another object and width/height in again another object.

Like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

size_config = ElementSize(width=200,height=200)
styling_config = Style(bg="red",fg="blue")
text_config = ...

# then create label with this objects

And this is just an example. I very often get frustrated from how badly python libraries uses constructors and I don’t know what to do with this over 9000 parameters that have no structure in them at all.

Maybe there is something wrong with me?
There is a way to hide all of this stuff in some sort of scoped objects and then map them to all of this nightmare in constructors?

>Solution :

Use **kwargs unpacking.

label_args = dict(
    text="Hello",
    font=("Arial",32,"bold"),
    bg="grey",
    fg="red",
    width=200,
    height=200,
) #and so on...

label1 = tk.Label(**label_args)

If you want to apply static typing to these things, you can define TypedDicts for each function signature.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading