1

I'm trying to make figlet text in my terminal in python, as per one of the practice problems in week 6 of CS50. I'm trying to have a font picked randomly from pyfiglet's list of fonts, and I'm trying to implement this as follows:

import random
from pyfiglet import Figlet

figlet = Figlet()
figfonts = figlet.getFonts()

# ...

random.seed()
figlet.setFont(random.choice(figfonts)) # error here

However, when I run this in my terminal, I get the following error:

TypeError: Figlet.setFont() takes 1 positional argument but 2 were given

I'm confused. I'm only providing figlet.setFont() 1 argument, why is it saying that there are two? I just can't piece together what the error message is trying to tell me is wrong.

Mailbox
  • 115
  • 1
  • 5
  • Every example I can find online of the `.setFont()` method shows the font being specified by a `font=` keyword parameter, rather than a positional parameter. – jasonharper Apr 17 '23 at 02:34

1 Answers1

2

The method setFont has the signature:

def setFont(self, **kwargs)

So passing font as a keyword argument (vs. a positional argument like you tried to) should fix the issue (as suggested by @jasonharper in the comments).

For example:

figlet.setFont(font=random.choice(figfonts))

I'm confused. I'm only providing figlet.setFont() 1 argument, why is it saying that there are two?

As you can see from the signature above, the first positional argument is self. Python automatically passes the instance (in this case figlet) as the first argument because setFont is "bound" to the instance figlet when called as figlet.setFont(). It's also possible (but unconventional) to call instance methods like so: Figlet.setFont(figlet)

pomelozest
  • 146
  • 5
  • I tried this, but got a different error: `TypeError: Random.choice() got an unexpected keyword argument 'font'`. – Mailbox Apr 17 '23 at 13:55
  • @Mailbox please post the line of code that's causing the error. – pomelozest Apr 17 '23 at 15:38
  • 1
    Excuse me. In the original code I posted, I replaced `figlet.setFont(random.choice(figfonts))` with `figlet.setFont(font=random.choice(figfonts))`. – Mailbox Apr 17 '23 at 16:40
  • 2
    It works fine for me. Are you sure you're not doing this? `figlet.setFont(random.choice(font=figfonts))` – pomelozest Apr 17 '23 at 19:19
  • 1
    Lmao, that's exactly the mistake I made. I fixed it and it works now, thank you! How did you predict that mistake? – Mailbox Apr 18 '23 at 00:07