python function passed into another function as argument - python-2.7

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()

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

how to use local variable to another function in python?

def runscan(self):
p = os.popen('LD_PRELOAD=/usr/libv4l/v4l1compat.so zbarcam
/dev/video0','r')
while True :
code = p.readline().split(':')[1]
print 'Got barcode:', code
def input(self):
self.entryc.insert(END, code)
how about this? i want use local 'code' to the next function to insert the result of barcode to my Tkinter entryBox.. Thanks
just pass it as a parameter. change the definition of input to def input(self, code) and then as the last line of runscan call input(code). A side note, you shouldn't use "input" as the name of a function, because it shadows the built-in input function, which is used for getting user input from the console.

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

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)

Is it possible to use the same arguments to both decorator and function

I need to understand how I can access the variable that was passed to the function in the decorator.
Let me explain with an example, is it possible to do something like this:
class test(object):
....
#DecoratorClass(myWrapper(self, x))
def myFunction(self, x):
print x
print self.y
At some point an instance of the test-class is created, and myFunction is called from somewhere. I need to path the same argument to myWrapper.
I hope that this is clear enough.
The decorator replaces the function with a callable that wraps it, so the callable will be passed the same parameters as the original function. So, for example:
def Decorator(original_function):
def replacement_function(x):
# You now have 'x' here... do what you want with it.
return replacement_function
#Decorator
def MyFunction(x):
# ...
Note that you will need to delay construction of "myWrapper" until the function is executed (because you will not have the function parameter until then).

Interrupting `while loop` with keyboard in Cython

I want to be able to interrupt a long function with cython, using the usual CTRL+C interrupt command.
My C++ long function is repeatedly called inside a while loop from Cython code, but I want to be able, during the loop, to send an "interrupt" and block the while loop.
The interrupt also should wait the longFunction() to finish, so that no data are lost or kept in unknown status.
This is one of my first implementation, which obviously doesn't work:
computed=0;
print "Computing long function..."
while ( computed==0 ):
try:
computed = self.thisptr.aLongFunction()
except (KeyboardInterrupt, SystemExit):
computed=1
print '\n! Received keyboard interrupt.\n'
break;
(p.s. self.thisptr is the pointer to the current class which implements aLongFunction() )
You should be able to do something like this:
import signal
class Test():
def __init__(self):
self.loop_finished = False
signal.signal(signal.SIGINT, self.abort_loop)
def abort_loop(self, signal, frame):
self.loop_finished = True
def go(self):
while not self.loop_finished:
print "Calculating"
# Do your calculations
# Once calcations are done, set self.loop_finished to True
print "Calculating over"
Test().go()
You can also use additional variables to keep track of whether the computation was manually aborted or not.
I am not a Python C-Api foo master, however this works, but maybe its not the best way:
cdef extern from "Python.h":
int PyErr_CheckSignals()
def test_interrupt():
cdef int i = 0
while i < 9999999999 and not PyErr_CheckSignals():
# do fancy stuff.
i += 1
Of course that is not asynchronous which is maybe possible but I do not know and this breaks the loop for any signal, not just Ctrl+C. Also maybe its better to not check signals every loop iteration, at least if what is done is very cheap.
You could call PyErr_Occurred, etc. if PyErr_CheckSignals did not return 0 and see what kind of Exception got raised to go specifically for KeybordInterrupt or certain kill signals. (Anyway, check the python C-Api for details there...)
If you are calling a cython cdef function inside the while loop you may be able to achieve this also if you add except *:
cdef function(...) except *:
pass
see also http://docs.cython.org/src/userguide/language_basics.html#error-return-values