0

I've got following simple script, which gets text from some site:

from urllib.request import urlopen

def fetch_words():
    contentdownload = urlopen('https://wolnelektury.pl/media/book/txt/treny-tren-viii.txt')
    decluttered = []
    for line in contentdownload:
        decltr_line = line.decode('utf8').split("  ")
        for word in decltr_line:
            decluttered.append(word)
    contentdownload.close()
    return decluttered

When adding: print(fetch_words) at the end, the program returns: <function fetch_words at 0x7fa440feb200>, but on the other hand, when I replace it with: print(fetch_words()) it returns the content of the website, that a function downloads. I have following question: why it works like this, what's the difference: function with () or without... All help appreciated!

  • The () call the function and "replace" it in the evaluation by its return value. – Michael Butscher May 12 '20 at 16:23
  • Since `fetch_words()` is a function, when you do `print(fetch_words)`, it just prints technical information and doesn't call the function. When you do `print(fetch_words())`, it actually calls the function and runs it, and returns whatever you told it to. – BruceWayne May 12 '20 at 16:23
  • I think print(fech_word) just prints the signature of the function because it does not include the parenthesis. But the second one returns the contents which include in the function. – Dejene T. May 12 '20 at 16:25

1 Answers1

0

When you call print(fetch_words) you get the representation of the function as an object.

def fetch_words():
    pass

isinstance(fetch_words,object)

return True. Indeed, functions in Python are objects.

So when you type print(fetch_words) you actually get the result of fetch_words.__str__(), a special method which is called when you print object.

And when you type print(fetch_words()) you get the result of the function (the value the function returns). Because, the () execute the function

So fetch_words is an object and fetch_words() execute the function and its value is the value the function returns.

Antscloud
  • 33
  • 1
  • 5