caesar0301 / treelib

An efficient implementation of tree data structure in python 2/3.
http://treelib.readthedocs.io/en/latest/
Other
801 stars 185 forks source link

`show` method printing to `stdout` prevents user to control `stdout` #141

Open leonardbinet opened 4 years ago

leonardbinet commented 4 years ago

IMO it would make more sense that the show method returns self._reader value, and that user then choose what to do with it (ie print to stdout, write in a file, store somewhere etc)

https://timber.io/blog/the-pythonic-guide-to-logging/

It's also bad practice to ship a package that prints directly to stdout because it removes the user's ability to control the messages.

leonardbinet commented 4 years ago

In my use case, here is why it is painful. I have a class, let's call it NiceReprTree inheriting from treelib.tree.Tree, for which I want the repr to be the name of the class followed by the output of show method. The problem here with this print is that my stdout will be spammed..

Example:

class NiceReprTree(Tree):

    def __str__(self):
        return '<{class_}>\n{tree}'.format(
            class_=text(self.__class__.__name__),
            tree=text(self.show())
        )

    def __repr__(self):
        return self.__str__()
vallsv commented 3 years ago

Did you see that you can use t = tree.show(stdout=False)? I feel like this issue is already fixed on the master at least.