Auto __repr__ method

前端 未结 6 843
囚心锁ツ
囚心锁ツ 2020-12-30 00:30

I want to have simple representation of any class, like { property = value }, is there auto __repr__?

6条回答
  •  北海茫月
    2020-12-30 01:03

    I use this helper function to generate repr s for my classes. It is easy to run in a unittest function, ie.

    def test_makeRepr(self):
        makeRepr(Foo, Foo(), "anOptional space delimitedString ToProvideCustom Fields")
    

    this should output a number of potential repr to the console, that you can then copy/paste into your class.

    def makeRepr(classObj, instance = None, customFields = None):
        """Code writing helper function that will generate a __repr__ function that can be copy/pasted into a class definition.
    
        Args:
            classObj (class):
            instance (class):
            customFields (string):
    
        Returns:
            None:
    
        Always call the __repr__ function afterwards to ensure expected output.
        ie. print(foo)
    
        def __repr__(self):
            msg = ""
            attributes = [self.var1, self.var2]
            return msg.format(*attributes)
        """ 
        if isinstance(instance, classObj):
            className = instance.__class__.__name__
        else:
            className=classObj.__name__
    
        print('Generating a __repr__ function for: ', className,"\n")
        print("\tClass Type: "+classObj.__name__, "has the following fields:")
        print("\t"+" ".join(classObj.__dict__.keys()),"\n")
        if instance:
            print("\tInstance of: "+instance.__class__.__name__, "has the following fields:")
            print("\t"+" ".join(instance.__dict__.keys()),"\n")
        else:
            print('\tInstance of: Instance not provided.\n')
    
        if customFields:
            print("\t"+"These fields were provided to makeRepr:")
            print("\t"+customFields,"\n")
        else:
            print("\t"+"These fields were provided to makeRepr: None\n")
        print("Edit the list of fields, and rerun makeRepr with the new list if necessary.\n\n")
    
        print("repr with class type:\n")
        classResult = buildRepr( classObj.__name__, " ".join(classObj.__dict__.keys()))
        print(classResult,"\n\n")
    
        if isinstance(instance, classObj):
            instanceResult = buildRepr( instance.__class__.__name__, " ".join(instance.__dict__.keys()))
        else:
            instanceResult = "\t-----Instance not provided."
        print("repr with instance of class:\n")
        print(instanceResult,"\n\n") 
    
        if customFields:
            customResult = buildRepr( classObj.__name__, customFields)
        else:
            customResult = '\t-----Custom fields not provided'
        print("repr with custom fields and class name:\n")
        print(customResult,"\n\n")    
    
        print('Current __repr__')
        print("Class Object: ",classObj)
        if instance:
            print("Instance: ",instance.__repr__())
        else:
            print("Instance: ", "None")
    
    
    def buildRepr(typeName,fields):
        funcDefLine = "def __repr__(self):"
        msgLineBase  = '    msg = "<{typename}({attribute})>"'
        attributeListLineBase = '    attributes = [{attributeList}]'
        returnLine = '    return msg.format(*attributes)'
        x = ['self.' + x for x in fields.split()]
        xResult = ", ".join(x)
        y = [x + ' = {}' for x in fields.split()]
        yResult = ', '.join(y)
        msgLine = msgLineBase.format(typename = typeName, attribute = yResult)
        attributeListLine = attributeListLineBase.format(attributeList = xResult) 
        result = "{declaration}\n{message}\n{attributes}\n{returnLine}".format(declaration = funcDefLine,
                                                                           message = msgLine,
                                                                           attributes = attributeListLine,
                                                                           returnLine =returnLine )
        return result
    

提交回复
热议问题