Best output type and encoding practices for __repr__() functions?

后端 未结 3 1446
你的背包
你的背包 2020-12-13 05:58

Lately, I\'ve had lots of trouble with __repr__(), format(), and encodings. Should the output of __repr__() be encoded or be

3条回答
  •  感情败类
    2020-12-13 06:26

    I think a decorator can manage __repr__ incompatibilities in a sane way. Here's what i use:

    from __future__ import unicode_literals, print_function
    import sys
    
    def force_encoded_string_output(func):
    
        if sys.version_info.major < 3:
    
            def _func(*args, **kwargs):
                return func(*args, **kwargs).encode(sys.stdout.encoding or 'utf-8')
    
            return _func
    
        else:
            return func
    
    
    class MyDummyClass(object):
    
        @force_encoded_string_output
        def __repr__(self):
            return 'My Dummy Class! \N{WHITE SMILING FACE}'
    

提交回复
热议问题