This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 6 months ago.
Here's the code:
def my_func(f, arg):
return f(arg)
print((lambda x: 2*x*x, (5)))
>>>(<function <lambda> at 0x10207b9d8>, 5)
How to solve the error, and can some please explain in a clear language what exactly that error means.
There is no error; you simply supplied two arguments to print, the lambda x: 2*x*x and 5. You're not calling your anonymous function rather, just passing it to print.
print will then call the objects __str__ method which returns what you see:
>>> str(lambda x: 2*x*x) # similarly for '5'
'<function <lambda> at 0x7fd4ec5f0048>'
Instead, fix your parenthesis to actually call the lambda with the 5 passed as the value for x:
print((lambda x: 2*x*x)(5))
which prints out 50.
What's the general meaning of <function at 0x ...>?
That's simply the way Python has chosen to represent function objects when printed. Their str takes the name of the function and the hex of the id of the function and prints it out. E.g:
def foo(): pass
print(foo) # <function foo at 0x7fd4ec5dfe18>
Is created by returning the string:
"<function {0} at {1}>".format(foo.__name__, hex(id(foo)))
Related
This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 3 years ago.
In this program the output is not what I would expect:
class example(object):
def __init__(self, foo,bar):
self.foo = foo
self.bar = bar
def what_are_you():
print(foo,bar)
print("This doesn't work either")
a = example("aaa","bbb")
a.what_are_you
#should return "aaa bbb"
print(a.what_are_you)
print(a.foo,a.bar)
Instead it outputs nothing. This is the whole output:
<bound method example.what_are_you of <__main__.example object at 0x000002A9574B4710>>
aaa bbb
Process returned 0 (0x0) execution time : 0.041 s
By not including parentheses, you're printing the function object, not calling the function. To call the function, put parentheses after it.
print(a.what_are_you())
will print the value of what_are_you() (whatever is in the return statement)
As I see now, you're printing stuff, not returning stuff, so you might need to use:
a.what_are_you()
And in your function, you need to use self to get the variable:
def what_are_you(self):
print(self.foo,self.bar)
print("This doesn't work either")
This question already has answers here:
What is the difference between calling function with parentheses and without in python? [duplicate]
(5 answers)
Closed 3 years ago.
def myfunc():
print("hello")
b=myfunc()
In the above code the output is "hello" just by assigning b to myfunc(). Why is this? I never asked for myfunc() to be executed, I just assigned name to it. I know classes are executed on import, but this isn't a class.
myfunc and myfunc() are not the same thing. In your code, myfunc is a function reference while myfunc() returns the results from calling myfunc.
You want this instead:
b=myfunc
myfunc() means you are making call to the function, since function is not returning b is not getting any value.
if you print b is showing nothing.
if you assign b=myfunc in this case you are passing the reference of function to variable b if you use b() it will execute function body it means b and myfunc will point to same reference.
As there is a difference between print a value or returning something from the function. You are just printing in the function and not returning any value from the function. So if the function is not returning anything, that can't be assigned to the variable... executing the function with myfunc() will only print the value to the terminal.. In case you want to store the value to a variable, you need to return it from the function. :)
def myfunc():
print("Helloo")
b = myfunc()
--> hellloo
b = myfunc
b
--> <function __main__.hello()>
b()
--> hellloo
def myfucn():
return("hellloo")
b = hello()
b
--> hellloo'
This question already has answers here:
How to use string value as a variable name in Python? [duplicate]
(3 answers)
How do I create variable variables?
(17 answers)
Closed 4 years ago.
let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string?
For example change the variable's value or call a method if it's an object?
Thanks in advance
Variables are available through dictionaries locals() and globals(). If you want to access a particular variable by it's spring name, you can do e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x]
'hello'
You can also assign back to the variable using this approach, e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x] = 'something else'
>>> my_var
'something else'
Since functions are objects in Python, you can access any locally available functions in the same manner to call them.
>>> def my_test_function(n):
>>> return n*8
Accessing the method and calling it.
>>> locals()['my_test_function'](4)
32
For accessing attributes of objects by their name you can use getattr(), and setattr() to set them. For example, creating an object with a single property called your_prop.
class Example:
your_prop = 2
a = Example()
The value is available via your_prop.
>>> a.your_prop
2
The property can be accessed via name using getattr
>>> getattr(a, 'your_prop')
2
The property can be set using setattr:
>>> setattr(a, 'your_prop', 5)
>>> a.your_prop
5
Ok, let's suppose that you have lots of different functions: Aoo(), Boo(), Coo()... and let's suppose that you want to specify which of them to call via command line argument.
Now, that argument will be a string, so you need to call a function through its name, but you do not know in advance the name of the function.
One possible solution is to use exec():
def boo():
print("boo function")
def coo():
print("coo function")
Now:
argument = "boo"
exec(argument + "()")
>>> boo function
and
argument = "coo"
exec(argument + "()")
>>> coo function
It depends what you're trying to do, but you can scoop up whatever x is pointing to with locals() or globals():
def x(k):
return k + 1
string1 = "x"
the_function_x = locals()[string1]
print(the_function_x(3))
outputs 4 (it called the x function by utilizing string1).
This question already has answers here:
Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?
(3 answers)
Closed 4 years ago.
Here I am trying to call a function using dictionary key value.
>>> def hello():
print('hello')
>>> a = {'+': hello()}
it just prints hello after executing this line.
>>> a['+']
If I call the dictionary using key value, it results nothing. What am I missing here?
Do not put () while you are using the function name as a value for the dictionary because as soon as python find () it will execute the function.
Instead just add the function name a = {'+': hello}
And then use the () while fetching the value from the dictionary
a["+"]()
You need a return call.
def hello():
return 'hello'
Or I think that is what you want
You should put your callable as the value into the dict and then call it.
>>> def hello():
print('hello')
>>> a = {'+': hello}
>>> a['+']()
hello
I'm curious about the difference between lambda function and a regular function (defined with def) - in the python level. (I know what is the difference for programmers and when to use each one.)
>>> def a():
return 1
>>> b = lambda: 1
>>> a
<function a at 0x0000000004036F98>
>>> b
<function <lambda> at 0x0000000004031588>
As we can see - python knows that b is a lambda function and a is a regular function. why is that? what is the difference between them to python?
They are the same type so they are treated the same way:
>>> type(a)
<type 'function'>
>>> type(b)
<type 'function'>
Python also knows that b was defined as a lambda function and it sets that as function name:
>>> a.func_name
'a'
>>> b.func_name
'<lambda>'
In other words, it influences the name that the function will get but as far as Python is concerned, both are functions which means they can be mostly used in the same way. See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.
The only difference is that (a) the body of a lambda can consist of only a single expression, the result of which is returned from the function created and (b) a lambda expression is an expression which evaluates to a function object, while a def statement has no value, and creates a function object and binds it to a name.
In all other material respects they result in identical objects - the same scope and capture rules apply. (Immaterial differences are that lambda-created functions have a default func_name of "<lambda>". This may affect operation in esoteric cases - e.g. attempts to pickle functions.).
Both lambda and def create the same kind of function – they have the same kind of metadata and capabilities. Their technical difference is syntactical:
A lambda is an expression producing a function.
A def is a statement producing a function.
This is everything that dictates how they can be used. Other apparent differences simply come from the information lambda/def can capture.
>>> def def_func(): pass
>>> lambda_func = lambda: None
>>> type(def_func) == type(lambda_func)
True
Usage: Expression vs. Statement
A lambda is more flexible as expressions can be part of more language constructs.
# v--------------v arguments must be expressions
sort(values, key=lambda x: abs(x))
In contrast, a def is more powerful as it can consist of more language constructs.
def encode(num, base):
while num: # statements must be inside statements
num, bit = divmod(num, base)
yield bit
These differences derive directly from one being an expression and the other being a statement. Python has no special rules to decide where a lambda/def may be used.
Where the wild <lambda>s grow
The primary reason to assume lambda and def correspond to different kinds of function is metadata: lambda is often referred to as an "anonymous function" and miraculously it always produces a function <lambda>. Other quirks include "lambda functions can't be pickled", and recently typing also does "not work" for lambda.
That is because compared to def syntax, the lambda syntax has no way of specifying name, type annotations and similar. As such, Python simply fills in sane defaults for either: the name becomes <lambda> and annotations are left empty.
>>> identity = lambda a: a
>>> identity.__qualname__
'<lambda>'
>>> identity.__annotations__
{}
Since <lambda> is not a valid identifier, everything using this metadata to find the function – most prominently pickle – fails.
However, that does not make the function an "anonymous function" type. The metadata can be patched up to insert what def would provide:
>>> identity.__qualname__ = identity.__name__ = 'identity'
>>> identity
<function __main__.identity(a)>
Of course at that one point one can just use def…
First consider the diff b/w the two.
Lambda functions: are operator can have any number of arguments, but it can have only one expression. It cannot contain any statements and it returns a function object which can be assigned to any variable. They can be used in the block they were created.
def functions: Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organised and manageable. They can be called and used anywhere we want.
Here you can get more clear difference by following example.
Defining a function
def add(a,b):
return a+b
print(add(4,5))
Defining a lambda
add = lambda x, y : x + y
print(add(4,5))
Lambda is an inline function where we can do any functionality without a function name.
It is helpful when we use it as an argument to a higher-order function.
Eg: A function that takes in other functions as arguments.
Example of Function definition:
>>> def func(a, b):
return a * b
>>> func(2,3)
6
>>> type(func)
<class 'function'>
>>> func
<function func at 0x034B6E88>
Example of Lambda expression:
>>> multiply = lambda a, b: a * b
>>> multiply(2, 3)
6
>>> type(multiply)
<class 'function'>
>>> multiply
<function <lambda> at 0x034B6ED0>
Both returns same output value. Only object returned are different. "func" name for Function and for Lambda.
lambda creates an anonymous function. This idea has been taken from functional programming languages. In this way you can create and pass the function to other functions like map and filter. (look here)
You can pass normal functions to these functions too, but since mostly they are simple and they are not used anywhere else, it's inconvenient to go through the whole process of definfing a new function.
As an example take a look at this:
>>> a = [1, 2, 3, 4]
>>> print map( lambda x : x*2 + 1, a )
[3, 5, 7, 9, 11]