I have several functions such as
def plot_lines(...):
def plot_setup():
def BP4_avg(...):
which all work fine but when I add a calling function main() it breaks
def main():
...
plot_setup()
BP4_avg(...)
plt.show()
if __name__ == "__main__":
main()
Any ideas?
If I remove main() and just have
plot_setup()
BP4_avg(...)
plt.show()
program works.
Thanks
In the first version you're just defining the functions but you are not calling them - so everything works fine.
On the second version (the one with main() ) you are actually executing these functions and one of them breaks...
Related
In the code below, self is a python object, as it is declared from def instead of cdef. Can a python object be referenced under a cdef function, just like how it is used under the c_function from my example below?
I am confused because cdef makes it sound like cdef is a C function, so I am not sure if it is able to take on a python object.
class A(self, int w):
def __init__():
self.a = w
cdef c_function (self, int b):
return self.a + b
Thank you,
I am the OP.
From "Cython: A Guide for Python Programmers":
Source: https://books.google.com.hk/books?id=H3JmBgAAQBAJ&pg=PA49&lpg=PA49&dq=python+object+cdef+function&source=bl&ots=QI9If_wiyR&sig=ACfU3U1CmEPBaEVmW0UN1_9m9G8B9a6oFQ&hl=en&sa=X&ved=2ahUKEwiBgs3Lw5vqAhXSZt4KHTs0DK0Q6AEwBHoECAoQAQ#v=onepage&q=python%20object%20cdef%20function&f=false
"[...] Nothing prevents us from declaring and using Python objects and dynamic variables in cdef functions, or accepting them as arguments"
So I take this as the book saying "yes" to my original question.
I have run the code as part of exception handling in python, during a session on Plural-sight but now even if a write a incorrect code the result is OK.
For example : hello world without print statement gives me exit code 0
Could you please advice on it?
code :
try:
import msvcrt
def getkey():
return msvcrt.getch()
except ImportError:
import sys
import tty
import termios
def getkey():
fd=sys.stdin.fileno()
original_attributes =termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
return ch
You need to make sure that the indentation of your code is correct first.
For example get_key function should be defined in both: the try case and in the catch, in the catch case you indented it correctly under the catch statement, but for the try case you made it on the same level of indentation as the try itself, for the interpreter it means that the function definition is not related to the try you wrote, therefore it throws an error as you should not add code after between the try and catch statement.
a rewrite of your program
try:
import msvcrt
def getkey():
return msvcrt.getch()
except ImportError:
import sys
import tty
import termios
def getkey():
fd=sys.stdin.fileno()
original_attributes =termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
return ch
This code says now, if we tried to import the library msvcrt and succeeded, then we will define a function get_key using the library, if failed; then we will define it again without using the library.
I have an async generator that I'm trying to pass into a keras model fit_generator, but the async generator returns an object, not a generator.
I've tried googling, but I haven't found a solution. This seems to be a pretty specific problem.
It's intention of asyncio to split async generator from regular generator, read answer here.
However if you decided that you won't run async generator concurrently elsewhere and your only intention is to avoid RAM overflow, you can cast async generator to regular one manually iterating async generator and awaiting each new item:
import asyncio
async def my_gen():
for i in range(10):
yield i
await asyncio.sleep(0.5)
def to_sync_generator(ait):
loop = asyncio.get_event_loop()
try:
while True:
try:
coro = ait.__anext__()
res = loop.run_until_complete(coro)
except StopAsyncIteration:
return
else:
yield res
finally:
coro = loop.shutdown_asyncgens()
loop.run_until_complete(coro)
# Check:
if __name__ == '__main__':
for i in to_sync_generator(my_gen()):
print(i)
P.S. Didn't test code much.
I've been playing with Cython recently for the speed ups, but when I was trying to use copy.deepcopy() some error occurred.Here is the code:
from copy import deepcopy
cdef class cy_child:
cdef public:
int move[2]
int Q
int N
def __init__(self, move):
self.move = move
self.Q = 0
self.N = 0
a = cy_child((1,2))
b = deepcopy(a)
This is the error:
can't pickle _cython_magic_001970156a2636e3189b2b84ebe80443.cy_child objects
How can I solve the problem for this code?
As hpaulj says in the comments, deepcopy looks to use pickle by default to do its work. Cython cdef classes didn't used to be pickleable. In recent versions of Cython they are where possible (see also http://blog.behnel.de/posts/whats-new-in-cython-026.html) but pickling the array looks to be a problem (and even without the array I didn't get it to work).
The solution is to implement the relevant functions yourself. I've done __deepcopy__ since it's simple but alternatively you could implement the pickle protocol
def __deepcopy__(self,memo_dictionary):
res = cy_child(self.move)
res.Q = self.Q
res.N = self.N
return res
I suspect that you won't need to do that in the future as Cython improves their pickle implementation.
A note on memo_dictionary: Suppose you have
a=[None]
b=[A]
a[0]=B
# i.e. A contains a link to B and B contains a link to A
c = deepcopy(a)
memo_dictionary is used by deepcopy to keep a note of what it's already copied so that it doesn't loop forever. You don't need to do much with it yourself. However, if your cdef class contains a Python object (including another cdef class) you should copy it like this:
cdef class C:
cdef object o
def __deepcopy__(self,memo_dictionary):
# ...
res.o = deepcopy(self.o,memo_dictionary)
# ...
(i.e. make sure it gets passed on to further calls of deepcopy)
so I'm amateur programmer, and I wanted to do something with functions for a little text-based hacking game. In it, a function would be called to allow the player to find the loot and so forth. So I was doing some 'small-scale testing';
And during my testing, I found that if I had a function (which called a different function inside of it), then some text being 'printed', the second function would be called first.
#Example using a sort of 'Decorator'.
def Decor(func):
print("================")
print("Hey there")
print("================")
print("")
func
def Hello():
print("And HELLO WORLD!")
decorated = Decor(Hello())
decorated
But the output is always something along the lines of:
And HELLO WORLD!
================
Hey there
================
Is there a way to make the function be called after the text is printed?
Or simply delay the function being called.
Or am I going about this the wrong way?
Thanks for you time.
The issue here is that you are passing the result of Hello() to Decor. This means that Hello() will be processed first and then the result will be passed to Decor as parameter. What you need is something like this
def Decor(func):
print("================")
print("Hey there")
print("================")
print("")
func()
def Hello():
print("And HELLO WORLD!")
decorated = Decor(Hello)
decorated
this is one of the usual approaches to decorate a function in python:
def Decor(func):
def new_func():
print("================")
print("Hey there")
print("================")
print("")
func()
return new_func
def Hello():
print("And HELLO WORLD!")
decorated = Decor(Hello)
decorated()
this way the statements in your Decor and Hello functions are not called until you call decorated().
you could use the decorator also this way:
#Decor
def Hello():
print("And HELLO WORLD!")
Hello() # is now the decorated version.
there is a primer on decorators on realpython.com that might help.