altair
altair copied to clipboard
Introduce export methods like `Chart.to_***()`
Distilled from https://github.com/altair-viz/altair/pull/3081#issuecomment-1587291370:
Currently we can export Altair specifications as such:
.save(format=***).to_dict(format=***)# defaults tovega-liteoption forvega.to_json(format=***)# defaults tovega-liteoption forvega
Personally, I like it when there is a grouping using to_***().
Using the autocomplete I can discover what this object can be evaluated into (similar to autocomplete on .mark_***() and transform_***() to see what is possible).
For example:
to_svg()to_png()to_pdf(()to_df()to_pl()to_arrow()to_vgjson()to_vljson()to_json()# isvega-liteto_vgdict()to_vldict()to_dict()# isvega-lite
A convention we used in plotly that I still like is to use to_* for methods that return the converted object and write_* for methods that write the converted object to a file (or file-like object). So chart.write_png("chart.png") would write the png data to a file and chart.to_png() would return a bytes object with the encoded PNG data.
BTW, are you picturing that to_df/to_pl/to_arrow would use the transformed_data logic?
After re-reading my comment in the linked issue, I think that was indeed what I had in mind at that time. Not sure if it still make sense.
Regarding to_**()/write_**(). I think I prefer a single entrypoint using to_**(). And then use an argument check (eg. fp=None) to return a (byte)string in Python or write a file on disk.
Single entry, easy to remember, easy to maintain.
Personally, I too have a (weak) preference for keeping separate nomenclature for methods that write to files vs those that return an object. So my vote here would be to keep the current naming with .save for those that write to a file (but could be convinced otherwise).
When looking to the current code base it make sense to keep the .save() method to save chart definitions to different formats.
Also with the current code base we have introduced a new .to_url() method that returns a string and open_editor() function that opens a webbrowser.
Apparently we still have the to_html() that returns a string.
Based on the discussion above, I'm fine with the approach that the .to_**() methods returns the converted object and the .save() method, saves the converted object to file.