This question already has answers here:
What is the difference between calling function with parentheses and without in python? [duplicate]
(5 answers)
Closed 2 years ago.
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!
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.
Related
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
This is a program to make the text print with each word beginning with a capital letter no matter how the input is.
So my question is why do we use return here :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"{formatted_f_name}{formatted_l_name}"
print(format_name("ABcDeF", "Xy"))
when I could just do this :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
print(f"{formatted_f_name}{formatted_l_name}")
format_name("ABcDeF", "Xy")
What scenarios would it be really useful in?
The main reason that the return keyword is used is so that the value of the function can be stored for later, rather than just printing it out and losing it.
e.g.
def someFunction(a,b):
return(a+b/3)
a=someFunction(1,2)
This means that what the function does can be stored for later.
For example:
print(a)
print(a/2)
print(a+3)
return statements don't just replace print, they allow you to do a load of other things by storing the end value (the value inside return) in a variable.
print()ing in a function, however, only allows us to print the variable to the console, not allowing us to do anything or use the value that it prints.
e.g.
def someFunction(a,b):
print(a+b/3)
a=someFunction(1,2)
print(a)
Although the function already prints the value off for you, the variable I assigned it to shows that the function is practically useless unless you run it a bunch of times. a will print off None in the case above.
Hope that was helpful.
This question already has answers here:
Map list item to function with arguments
(4 answers)
Closed 1 year ago.
I have a following function:
def calculate_frequent_itemset(fractional_data, support):
"""Function that calculated the frequent dataset parallely"""
return apriori(fractional_data, min_support=support, use_colnames=True)
I would like to call it in a map function using:
frequent_itemsets=p.map(calculate_frequent_itemset,(dataNew1,dataNew2,dataNew3,dataNew4,dataNew5), 200)
In other words I want to set 200 as support argument. But I got an error TypeError: calculate_frequent_itemset() missing 1 required positional argument: 'support'. How can I fix it please?
You could use a wrapper function (or a lambda):
support=200
def my_calculate_frequent_itemset(fractional_data):
return calculate_frequent_itemset(fractional_data, support)
frequent_itemsets=p.map(my_calculate_frequent_itemset,(dataNew1,dataNew2,dataNew3,dataNew4,dataNew5))
It's pretty horrible.
I rediscovered this - rather perhaps see https://stackoverflow.com/a/31995624/1021819 which gives the same answer
This question already has answers here:
Python Script returns unintended "None" after execution of a function [duplicate]
(3 answers)
Closed 4 years ago.
I'm practising with unit test module.
I have this simple code. It is a function that joins strings so that I can get this result: "City, Country"
def city_country(city_name, country_name):
"""Simple code that prints City, Country"""
print(city_name.title() + ", " country_name.title())
When I run it, the function works OK.
I wrote a class to test the code with unit tests, and I got an error.
I noticed that when I assign the function to a variable, like this :
city_country_var = city_country('Punto Fijo', 'Venezuela')
And then import it to the TestClass(or somewhere else), print it, this is the result :
Punto Fijo, Venezuela
None
I don't know how to handle it or why is it caused, since it's the same function that worked fine earlier by itself. But it only gives me that result if I import the function to another file. Can I get some advice about why does it happen and how to solve it?
your city_country function does not return any value. It just prints the result and returns None (by default).
Apply those changes and your variable should have the string value you desire:
def city_country(city_name, country_name):
"""Simple code that prints City, Country"""
result = (city_name.title() + ", " country_name.title())
print(result)
return result
This question already has answers here:
Is there a trick to break on the print builtin with pdb?
(2 answers)
Closed 5 years ago.
I am working on a python program which interacts with many external libraries and has some fairly complex logic. In this program I've found that it'll sometimes print NoneType: None to the console (with no context) whatsoever. I have no idea where this is being printed or why and this is causing errors in other places of the program.
So is it possible to find the source of a print/warn call?
You can always override the built-in print() function and then observe what's going on, for example:
import builtins
import inspect
builtin_print = builtins.print # store a reference to the built-in print() function
def tracing_print(*args, **kwargs):
c = inspect.getouterframes(inspect.currentframe())[1] # get the calling frame
# print the caller info (you can add a condition like `if args and args[0] is None`):
builtin_print("{}, line {}, caller `{}`, source: {}".format(c[1], c[2], c[3], c[4]))
builtin_print(*args, **kwargs) # call the built-in method and forward the params
builtins.print = tracing_print # override the built-in print
That will give you a ton of info preceding every call to print(). For example:
def foo():
print("Bar!")
foo()
Will yield something like:
/tmp/playground/test.py, line 13, caller `foo`, source: [' print("Bar!")\n']
Bar!
Needless to say, do not use this in production code, it's meant for forensics.
This question already has answers here:
Python Tkinter Return
(2 answers)
Closed 8 months ago.
I'm currently working on a GUI project on Python (3.6) using tkinter (8.6).
Following this question I'm wondering how to get back the result of someFunction :
def someFunction(event):
do stuff ..
return(otherStuff)
canvas.bind('<Button-1>',lambda event: someFunction(event))
Thank you in advance :) !
The return values of callback functions like your someFunction are ignored. Rather than using return, have the callback save the value somewhere (in a global variable or an attribute of some kind of object). Or have your function pass the computed value as an argument to some other function that will do something with it.