0

So I get an error when running this recurring function, and I can't figure out what am I doing wrong.

The script is just trying to fit a text inside an image by scaling the size of the font until it's small enough. The first runs are correct, enters the if tSize, but when it has the correct size for the font, it crashes.

def calculateFontSize(scale, width, height, quoteL, fontsPath):

    fontSize = int(height*scale)

    if fonts:
        fnt = ImageFont.truetype(os.path.join(fontsPath,fonts[randint(0,len(fonts)-1)]),fontSize)
    else:
        fnt = ImageFont.truetype(wd+'\\fonts\\IndieFlower.ttf',fontSize) # Selected font

    tSize = [d.textsize(quoteL[0],font = fnt),d.textsize(quoteL[1],font = fnt)]

    if tSize[0][0] > width or tSize[1][0] > width:
        scale = scale - 0.005
        calculateFontSize(scale, width, height, quoteL, fontsPath)
    else:
        return tSize, int(fontSize), fnt

tSize, fontSize, fnt = calculateFontSize(scale, width, height, quoteL, fontsPath)

This is the error that i get:

    Traceback (most recent call last):
  File "C:\script.py", line 286, in <m
odule>
    main()
  File "C:\script.py", line 275, in ma
in
    image = writeOnImage(picture,quoteL)
  File "C:\script.py", line 188, in wr
iteOnImage
    tSize, fontSize, fnt = calculateFontSize(scale, width, height, quoteL, fonts
Path)
TypeError: 'NoneType' object is not iterable

What am I doing wrong?

SOLVED: I should have been returning the function when I call it inside itself.

rnavarro
  • 11
  • 1
  • 4
  • Note that the fix is not to return the function, but the value of the recursive function call. – timgeb Jun 09 '18 at 17:22

1 Answers1

0

calculateFontSize is not returning anything (so it will implicitly return None) in the second if branch of your function.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • But I am returning inside the else? Where should I return? – rnavarro Jun 09 '18 at 15:54
  • @mavano Wouldn't you agree that if you do not return something in every conditional branch, then your function won't return anything (`None`) in some cases? – timgeb Jun 09 '18 at 17:22