PyCall: How can I make a python class with static attributes?


#1

I want to be able to capture key-press events in a Julia powered PyQtGraph GUI using the amazing PyCall package, but have been unable to because I can’t make python classes with static attributes using the @pydef macro in PyCall.

Moreover, when I try to make any class with a static attribute using @pydef, I get the following error:

julia> @pydef mutable struct Foo
           class_attr = 1
           function __init__(self)
               println(self[:class_attr])
           end
       end

ERROR: AssertionError: Not a function definition: class_attr = 1

which is equivalent (I hope) to the following python code:

class Foo(object):
    class_attr= 1
    def __init__(self):
        print(self.class_attr)

Looking at the source code responsible for parsing the contents of a @pydef macro call makes me think that this capability is simply not yet implemented.

I have already opened an issue in PyCall, but was wondering if there is some other way to make a python class with a static attribute that I’m missing?


#2

Hopefully there is a more direct answer, but if not, are you sure you need a class? qobject.connect should take a function handle. If you wanted to use a class as a closure, there’s a slightly ugly hack to do that in the function’s properties.


#3

Thanks I’ll try something along those lines! I think I do need a class at some point but you’re absolutely right that I don’t need to connect the class itself to the signal, nor do I really need to have the signal be a static attribute of the class.

I was going to subclass a window (GraphicsLayoutWidget), add a custom signal as a static attribute, then reimplement the keyPressEvent method to emit the signal on a key press (basically this), but I could figure out some other way of doing it that woudn’t require a static attribute.