selenium python: what is 'lambda' in webdriverwait.until statements - python-2.7

I'm learning selenium webdriver with python and came across 'lambda' in following line of code. The author did not explain the use of lambda here:
search_button = WebDriverWait(self.driver, 10).until(lambda s:s.find_element_by_name("btnG"))
search_button.click()
I've read about lambda and it says lambda creates functions on the fly and some say its used to return expression. So now I'm confused and not sure exactly what difference does it make here.

In python functions are objects so you can pass them as parameters to other functions. The only thing is if you pass a function with () you call that function at the same time. So it's possible to pass functions which do not take any arguments so it can be called inside the function you passing it to later on. But if you need to pass parameters to the function while you are passing function itself you need to wrap it up in lambda so that it's called only when it's needed.
Edit
To answer the question how it gets s value. If you look into the source here doctoring explains it all:
"""Calls the method provided with the driver as an argument until the
return value is not False."""
Actual code is self explanatory as well:
def until(self, method, message=''):
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace)

Related

What is a def __call__(self,in_data) function used for in python and where is the in_data getting its value

I am actually a student and my teacher gave me this code to understand and use this code so i can continue to learn machine learning etc. I get that it is an AND function and i get what it is printing , the thing i cant understan is the def call(self,in_data): function and where does the "in_data" gets its value from? Because in my point of view all i see it's a blank variable that somehow helps me to complete the code. Also changing the value of the weights in the init part didnt actually change anything in this code and i am wondering why. Here is the whole code i was given to study. Thanks for helping!
import numpy as np
class Perceptron:
def __init__(self,input_length,weights=None):
if weights is None:
self.weights= np.ones(input_length)*0.5
else:
self.weights=weights
#staticmethod
def unit_step_function(x):
if x>0.5:
return 1
return 0
def __call__(self,in_data):
weighted_input=self.weights*in_data
weighted_sum=weighted_input.sum()
return Perceptron.unit_step_function(weighted_sum)
p = Perceptron(2,np.array([0.5,0.5]))
for x in [np.array([0,0]),np.array([0,1]),np.array([1,0]),np.array([1,1])]:
y=p(np.array(x))
print(x,y)
__call__ is called when you try to invoke the object as though it were a function. You can see that being done at the bottom. p is a Perceptron object, but it's being treated as a function when you write
y = p(np.array(x))
So where is the data coming from? It's the np.array(x) that's being passed in.
You can read more about the "dunder"/"magic" methods here.
I'd actually argue that this is an abuse of __call__ though. I wouldn't consider a Perceptron to be inherently function-like. I think using a normal method would be clearer:
class Perceptron:
. . .
def give_input(self, in_data): # Instead of __call__
weighted_input = self.weights*in_data
weighted_sum = weighted_input.sum()
return Perceptron.unit_step_function(weighted_sum)
for x in [np.array([0,0]),np.array([0,1]),np.array([1,0]),np.array([1,1])]:
y = p.give_input(np.array(x)) # Just a typical method call now

forcing keyword arguments in python 2.7

I know I can use * to force all keyword arguments to a function/method to be "named".
If I have
def abc(a, *, x=10, z=30):
pass
then the following all work
abc(5)
abc(8, x=12)
abc(9, z=31)
abc(x=17, a=4)
even if I change the function signature to def abc(a, *, x=10, y=20, z=30),
and
abc(7, 13)
throws an error.
This is extremely important because, I can use the logical place, which will help maintenance over time, without being forced to use the end position based on history.
But * is not valid in Python 2.7, and abc(a, *args, x=10, z=30) (which I tried) doesn't work either.
Is there a way to force the use of x=12 in Python 2.7? Or another way of saying: make abc(7, 13) be invalid on Python 2.7.
One way of doing this is by adding a dummy keyword argument that never gets a valid positional value (so don't check for None):
_dummy = object()
def abc(a, dummy_kw=_dummy, x=10, z=30):
if dummy_kw is not _dummy:
raise TypeError("abc() takes 1 positional argument but at least 2 were given")
That will prohibit abc(7, 13) and allow all the others. It works on Python 2 and Python 3, so it is useful when you have code that needs to run on both.
Originally I used:
def _dummy():
pass
but as #mata pointed out _dummy=object() works as well, and cleaner. Essentially any unique memory location that is not used in another way will work.
What about the following:
def abc(a, **kwargs):
# Get arguments from kwargs otherwise use default values
x = kwargs.pop('x', 10)
z = kwargs.pop('z', 30)
if not kwargs: # if kwargs is not empty
print 'extra parameters passed'
pass
This allows to force the use of kwargs and still have default values.
pop removes the key from kwargs, once you use it.
This is potentially very useful as you can check if the user gave extra parameters that do not belong to the function and in this case you can throw an error (for example).

python function passed into another function as argument

I am new to pragramming and python. This is something like what I have.
Def some_function():
Print "stuff"
Def another_function(x):
running = True
While running:
x
another_function(some_function())
Why does it only print "stuff" the first time going through the loop?
I read some stuff that talked about late binding but not sure if that is what this is or how to fix it in my example.
You didn't pass the function, you called the function and passed its value. So it printed stuff before you ever got into the loop.
To refer to a function without calling it, you leave off the (). So it should be:
another_function(some_function);
Then in another_function, you have to call the function:
def another_function(x):
running = True
while running:
x()

Can you assign more than one command to a Tkinter OptionMenu?

I have the following OptionMenu:
self.wcartsn = StringVar(self.frame1)
self.e1 = OptionMenu(self.frame1, self.wcartsn, *watercarts, command=(self.wcart, lambda selection:self.other_entry(selection,'wcartsn',10,6)))
self.e1.grid(row=10, column=5, stick=E+W)
This doesn't actually work, but it makes my question clear. How (if possible) do you call multiple functions from one OptionMenu? This function gives the error TypeError: 'tuple' object is not callable
You could create a function that calls each of your multiple functions in turn:
def compose(functions):
"""
returns a single function composed from multiple functions.
calling the returned function will execute each of the functions in the order you gave them.
"""
def f(*args, **kargs):
for function in functions:
function(*args, **kargs)
return f
self.e1 = OptionMenu(self.frame1, self.wcartsn, *watercarts, command=compose(self.wcart, lambda selection:self.other_entry(selection,'wcartsn',10,6)))
The simplest solution -- and the one that is easiest to maintain -- is to create a single function that calls the other functions:
def __init__(self):
...
self.wcartsn = StringVar(self.frame1)
self.e1 = OptionMenu(self.frame1, self.wcartsn, *watercarts, command=self.wcartsnCallback)
...
def wcartsnCallback(self, selection):
self.wcart()
self.other_entry(selection,'wcartsn',10,6)

can django view function override each other?

I'm going through the django tutorials and I was wondering what happens when you have 2 functions with the same name in views.py?
for example:
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll': p})
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
when i ran the code, the bottom function was the one that was called. How does this work?
In Python, methods and functions can take any number of arguments; which negates the need to have different function "signatures" to support different types of arguments passed; which is the common use case for function overloading. See 4.7.3. Arbitrary Argument Lists in the python documentation.
The reason the second method gets called is because you simply overwrite the method definition when you define it with the same name (and same argument list). For python, it is the same as:
>>> x = 1
>>> x = 'Hello'
>>> print x
Hello
You just re-defined the same method again, so it uses the last definition.
If I'm not mistaking, you need to use classes if you need extend or override the view method ... Or use "if" statement :)
https://docs.djangoproject.com/en/dev/topics/class-based-views/
In you're example, thats just python's normal behaviour ... reads the file from the top left .. then it compiles it and use it ...