pythonprettytable

Python - PrettyTable - Nothing Works


I feel like a complete idiot at the moment. I'm trying to populate data from a dataframe into prettytable for display. The reason I don't want to use pandas directly, is that it seems like a giant PITA to get number formatting specific to each column... which I know is easy in prettytable.

While I've used this package before... it just straight up isn't working.

a = PrettyTable
a.add_column("test",[1, 2])

TypeError: add_column() missing 1 required positional argument: 'column'

I've tried adding by row

a = PrettyTable
a.add_row("test",[1, 2])

AttributeError: 'str' object has no attribute '_field_names'

And then adding the field names

a = PrettyTable
a.field_names = ["1","2","3"]
a.add_row("test",[1, 2])

AttributeError: 'str' object has no attribute '_field_names'

I'm using the latest version, installed via pip, v3.3.0. I'm running python v3.9.6 through Jupyter Notebook.


Solution

  • You need to use parentheses to get an instance of the class:

    a = PrettyTable()
    a.add_column("test",[1, 2])
    

    If you forget them, it references the class.

    See this example:

    class Foo:
        def method(self, *args):
            print(args)
    
    Foo.method(1, 2, 3) # (2, 3)
    Foo().method(1, 2, 3) # (1, 2, 3)
    

    If you use the class, the first parameter is passed as self.

    If you use the instance, the instance is automatically passed as self.