right usage of __repr__() in python?
Question
I have a container class which I would like to use to print all the elements in it.
I'd like to print them to file or console.
I've laid out the element (Patch
) and container class as below and __repr__(self)
.
I'm not sure I understood the purpose of __repr__()
and am wondering whether the usage here is OK.
class Patch:
def __init__(self, folder_name, file_name):
self.folder_name = folder_name
self.file_name = file_name
self.full_path = os.path.join(self.folder_name, self.file_name)
self.file_hash = md5_for_file(open(self.full_path, 'r'))
self.file_size = os.path.getsize(self.full_path)
def __repr__(self):
return "%s %s %s" % (self.file_name, self.file_hash, self.file_size)
class PatchContainer:
def __init__(self):
self.patch_folder_dict = collections.OrderedDict()
self.patch_file_set = set()
def addPatch(self, patch):
if patch.file_name in self.patch_file_set:
print '*** Delete the file ', patch.full_path, ' ***'
return
self.patch_file_set.add(patch.file_name)
if not patch.folder_name in self.patch_folder_dict:
self.patch_folder_dict[patch.folder_name] = [patch]
else:
self.patch_folder_dict[patch.folder_name].append(patch)
def prettyPrint(self, writeable_object=PATCH_META_FILE):
sys.stdout = writeable_object
for patch_folder in self.patch_folder_dict.keys():
print patch_folder
patch_list = self.patch_folder_dict[patch_folder]
for patch in patch_list:
print patch
sys.stdout = sys.__stdout__
It works as intended but please comment on whether the style/usage are fine.
Solution
This looks like you probably want __str__
. They are similar, but __str__
returns something intended for human consumption; __repr__
should return something intended for Python consumption - it should either be a Python expression that will evaluate to an equal object, or something in angle brackets like the default <classname object at id>
. See the documentation for the builtin repr(object)
, which ends up calling object.__repr__()
:
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information