Is there a Python equivalent to Perl's Data::Dumper for inspecting data structures?

前端 未结 11 1361
小鲜肉
小鲜肉 2020-12-10 00:19

Is there a Python module that can be used in the same way as Perl\'s Data::Dumper module?

Edit: Sorry, I should have been clearer. I was mainly afte

11条回答
  •  长情又很酷
    2020-12-10 01:03

    I needed to return Perl-like dump for API request so I came up with this which doesn't format the output to be pretty, but makes perfect job for me.

    from decimal import Decimal
    from datetime import datetime, date
    
    def dump(self, obj):
    
        if obj is None:
            return "undef"
    
        if isinstance(obj, dict):
            return self.dump_dict(obj)
    
        if isinstance(obj, (list, tuple)):
            return self.dump_list(obj)
    
        if isinstance(obj, Decimal):
            return "'{:.05f}'".format(obj)
            # ... or handle it your way
    
        if isinstance(obj, (datetime, date)):
            return "'{}'".format(obj.isoformat(
                sep=' ',
                timespec='milliseconds'))
            # ... or handle it your way
    
        return "'{}'".format(obj)
    
    def dump_dict(self, obj):
        result = []
        for key, val in obj.items():
            result.append(' => '.join((self.dump(key), self.dump(val))))
    
        return ' '.join(('{', ', '.join(result), '}'))
    
    def dump_list(self, obj):
        result = []
        for val in obj:
            result.append(self.dump(val))
    
        return ' '.join(('[', ', '.join(result), ']'))
    
    
    
    Using the above:
    
        example_dict = {'a': 'example1', 'b': 'example2', 'c': [1, 2, 3, 'asd'], 'd': [{'g': 'something1', 'e': 'something2'}, {'z': 'something1'}]}
    
        print(dump(example_dict))
    
    will ouput:
    
        { 'b' => 'example2', 'a' => 'example1', 'd' => [ { 'g' => 'something1', 'e' => 'something2' }, { 'z' => 'something1' } ], 'c' => [ '1', '2', '3', 'asd' ] }
    

提交回复
热议问题