0

I have a dictionary, and a print statement as follows:

d = {'ar':4, 'ma':4, 'family':pf.Normal()}
print(d)

Which gives me

{'ar': 4, 'ma': 4, 'family': <pyflux.families.normal.Normal object at 0x11b6bc198>}

Is there any way to clean up the value of the 'family' key? It's important that the calls remains simply 'print(d)' because it used to print other dictionaries without this issue. Is this possible? Thanks for your time.

EDIT:

Thanks for the answer guys, I would mark one as right but I haven't tried them and can't confirm. I ended up creating another dictionary with the cleaned up string as a key, and the object as the value. It was a bit more work but I did it before reading/getting the responses so I just stuck to it. Thanks nonetheless!

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Dan
  • 41
  • 6
  • 8
    You don't want to chage what `print(dict)` outputs, you want to add a `__repr__()` function to `pf.Normal()` to change how _it_ is displayed. I'm not sure what exactly `pf.Normal()` is , but perhaps inherit from it and add a custom `__repr__()`? – Christian Dean Jun 29 '17 at 23:07

2 Answers2

5

You are mistaken. You don't want to change what print(dict) outputs. That would require changing the way builtin dictionaries are printed. You want to add a custom __repr__() to your pf.Normal() object.

I believe pf.Normal() comes from the pyflux package, so I suggest seeing what data the class is suppose to hold, and pretty printing it by inheriting from the class:

class CustomNormalObject(pf.Normal):
    def __repr__(self):
        # Add pretty printed data here
        pass

Or if you need to pass your own arguments into the custom class, you can use super():

class CustomNormalObject(pf.Normal):
    def __init__(self, myparm, *args, **kwargs):
        # If using Python 3, you can call super without
        # passing in any arguments. This is simply for Python 2
        # compatibility.
        super(CustomNormalObject, self).__init__(*args, **kwargs)
        self.myparm = myparm

    def __repr__(self):
        # Add pretty printed data here
        pass
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
2

as I think pyflux is an external library, I think you should not edit it directly. An easy way to do what you want is to overwrite the __str__ or __repr__ methods of the Normal class.

pyflux.families.normal.Normal.__str__ = lambda self: "Clean up value here."

Here I used a lambda function for illustration, but of course you can use a defined function.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99