BanAckerman
BanAckerman

Reputation: 103

Trying to print directory system tree from scratch in Python (no imported modules)

So I am making a basic directory system in python from scratch. I am pretty new to coding and am doing python as a Uni module. So I have made the functions for creating the tree from scratch, but now I have been tasked with actually just printing out the object as it is (not visually to see each step of the directory tree). So this is my code currently

class File:
    pass

class Directory(File):
    def __init__(self, name, left=None, right=None):
        self.name = name
        self.left = left
        self.right = right
        
    
    def __repr__(self):
        return f"{self.name}, {self.left}, {self.right}"
        

class PlainFile(File):
    def __init__(self, name):
        self.name = name
    
    def __str__(self):
        return self.name

When I try to print root, I want to essentially see the whole thing. But it gives me the <main.blahblah when printing the names of the classes and other parts too. I think my def__repr__ needs to be recursive in nature but for the life of me I have no clue how to do it:( Please help!

Upvotes: 3

Views: 225

Answers (1)

rchome
rchome

Reputation: 2723

If you make your PlainFile class implement __repr__(self) instead of __str__(self), it should work. See What is the difference between __str__ and __repr__? for more details. The good thing about your Directory class's __repr__ is that it's already recursive, since it would call the inner File's __repr__ functions when evaluating the f-string.

Edit: Adding a full solution to match the expected output.

class File:
    pass

class Directory(File):
    def __init__(self, name, left=None, right=None):
        self.name = name
        self.left = left
        self.right = right

    def __repr__(self):
        arg_str = ", ".join(
            str(arg)
            for arg in (self.name, self.left, self.right)
            if arg is not None
        )
        return f"Directory({arg_str})"


class PlainFile(File):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"PlainFile({self.name})"

I use str() in the Directory implementation because it doesn't add quotes to the self.name since it's a string. By default, __str__ is implemented as __repr__, so it would also work on the File objects in left or right, and calling str() on a list will make it call repr() on its items.

Upvotes: 1

Related Questions