PyQt. TypeError - pyqt

I set filter on my QMainWindow with this:
keyPressFilter = keypressfilter.KeyPressFilter(self)
self.installEventFilter(keyPressFilter)
KeyPressFilter itself:
class KeyPressFilter(QObject):
def __init__(self, parent=None):
super(KeyPressFilter, self).__init__(parent)
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
print "key press %d" % event.key()
return True
else:
return QObject.eventFilter(obj, event) <- line NN
and i getting endless errors with every eventtype QEvent\QPaintEvent\QHoverEvent\etc:
line NN, in eventFilter:
TypeError: QObject.eventFilter(QObject, QEvent): argument 2 has unexpected type 'QPaintEvent'
How can i get rid of it?
Thx in advance,
Serge

eventFilter() is not a class method, so you need to pass self as well:
return QObject.eventFilter(self, obj, event)

Related

How could I create a docstring decorator in the presence of properties?

I have a collection of ever more specialized classes which correspond to collections of the same kind of data (temperature, density, etc) but for different drifts, for example, one subclass has dimensions (nx, ny) and a different suclass has dimensions (ncv), and I want to reflect that in the docstrings, for having a better documentation using Sphinx.
After reading many very useful threads here in Stack Overflow, I have arrived to this model:
import numpy as np
from functools import wraps
def class_decorator(cls):
import ipdb; ipdb.set_trace()
clsdict = {}
mro = cls.mro()
mro.reverse()
for tmp in mro[1:]: ##Ignore object class parent.
clsdict.update(tmp.__dict__)
for name, method in clsdict.items():
if hasattr(method, '__og_doc__'):
try:
method.__doc__ = method.__og_doc__.format(**clsdict)
except:
pass
else:
try:
method.__og_doc__ = method.__doc__
method.__doc__ = method.__doc__.format(**clsdict)
except:
pass
return cls
def mark_documentation(fn):
if not hasattr(fn, '__og_doc__'):
try:
fn.__og_doc__ = fn.__doc__
except:
pass
#wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
return wrapped
def documented_property(fn):
if not hasattr(fn, '__og_doc__'):
try:
fn.__og_doc__ = fn.__doc__
except:
pass
#wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
prp= property(wrapped)
prp.__og_doc__ = fn.__og_doc__
return prp
#class_decorator
class Base(object):
_GRID_DIM = 'nx, ny'
_TYPE = 'BaseData'
def __init__(self, name):
self.name = name
def shape(self):
""" This docstring contains the type '{_TYPE}' of class."""
print('Simple')
def operation(self, a, b, oper=np.sum, **kwargs):
""" Test for functions with args and kwargs in {_TYPE}"""
return oper([a,b])
#classmethod
def help(cls, var):
try:
print(get(cls, var).__doc__)
except:
print("No docstring yet.")
#class_decorator
class Advanced(Base):
_GRID_DIM = 'ncv'
_TYPE = 'AdvancedData'
def __init__(self,name):
super().__init__(name)
#property
#mark_documentation
# #documented_property
def arkansas(self):
"""({_GRID_DIM}, ns): Size of Arkansaw."""
return 'Yeah'
I am aiming to get the correctly formatted docstring when I call the help method or I use Sphinx, so that:
> adv = Advanced('ADV')
> adv.help("arkansas")
(ncv, ns): Size of Arkansaw.
> adv.help("operation")
Test for functions with args and kwargs in AdvancedData
I have managed to make it work so far, except for properties, because I assigned __og_doc__ to the function, but the property does not have that attribute. My last attempt at monkeypatching this, documented_property, fails because property is inmutable (as expected), and I cannot come up with any way to avoid this roadblock.
Is there any way around this problem?

How operator overloading can return a third class in Python?

I have the following classes in different files
class Fruit():
def __init__(self, value=0):
self.value = value
def __add__(self, other):
if type(self) == type(otro):
## PROBLEM AREA ##################################################
return type(self)(self.value + other.value)
else:
raise Exception.SumError(self, other) # Custom exception
def __repr__(self):
return f"{type(self).__name__}({self.value})"
The Fruit () class is the base class, from which the following two child classes inherit
class Pear(Fruit):
"""docs"""
def __init__(self, quantity=0):
super().__init__(quantity)
self.unit = "Pe"
class Apple(Fruit):
"""docs"""
def __init__(self, quantity=0):
super().__init__(quantity)
self.unit = "Ap"
The class required in the result is the following:
class Market_List():
"""docs"""
def __init__(self, value=0):
self.value = value
Currently I can add Pears() with Pears() and Apples() with Apples(), my question is how do I make adding Pears() with Apples() throw me a Market_List() object. I have already tried to use from market_list import Market_List at the beginning of the Fruit() class, but wanting to do the same in the Market_List() class to do the inverse operation then it enters a loop and gives me an error
Put the inports in the init methods, then the code will not run at module load time and you will not get the error

How can I trigger a function when any of the function under a class is called?

Is there a dunder method than triggered when any of the function under a specific class (including the function from its parents) is called?
Let's look at a small example:
class SpecialClass(ParentClass):
def NormalFunction1(self):
print('Function 1.')
def NormalFunction2(self):
print('Function 2')
def SpecialFunction(self):
print('Triggered.')
cls = SpecialClass()
cls.NormalFunction1()
cls.NormalFunction2()
The output I want is:
Triggered.
Function 1.
Triggered.
Function 2.
Thanks.
Problem solved! Thanks to #inspectorG4dget!
class SpecialClass():
class SubClass():
def NormalFunction1(self):
print('Function 1.')
def NormalFunction2(self):
print('Function 2')
def __getattribute__(self, item):
if item == 'SubClass':
return object.__getattribute__(self, item)
print('Triggered.')
return self.SubClass().__getattribute__(item)
cls = SpecialClass()
cls.NormalFunction1()
cls.NormalFunction2()

I am new to python i tried to run this fancy decorators code

class Square:
def _init_(self,side):
self._side = side
#property
def side(self):
return self._side
#side.setter
def side(self,value):
if value >= 0:
self._side = value
else:
print("error")
#property
def area(self):
return self._side **2
#classmethod
def unit_square(cls):
return cls(1)
s = Square(5)
print(s.side)
print(s.area)
but i am getting error ( s = Square(5) TypeError: Square() takes no arguments) i am not able to figure it out
The init method should have double underscores(__). Change the method to __init__
def __init__(self, side):
self._side = side
Reference: https://dbader.org/blog/python-dunder-methods

Apply decorator to all method of sub classes for timeit

I have a method decorator looking like
def debug_run(fn):
from functools import wraps
#wraps(fn)
def wrapper(self, *args, **kw):
# log some stuff
# timeit fn
res = fn(self, *args, **kw)
return wrapper
Right now I used to use it apply on each method that I want to debug. Now i'm trying to apply to all class method using a class decorator looking like.
Rather doing
class A():
#debug_run
def f(self):
pass
I do
#decallmethods(debug_run)
class A():
def f(self):
pass
def decallmethods(decorator):
def dectheclass(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
if name in getattr(cls, 'METHODS_TO_INSPECT', []):
setattr(cls, name, decorator(m))
return cls
return dectheclass
Trying to apply to decorator to the base class, not working as expected. no log to the console. Now i wonder if this approach is the good or I should used something else (apply the debug decorator to selected method from base class to all sub classes).
[EDIT]
Finally found why no logs were printed
Why is there a difference between inspect.ismethod and inspect.isfunction from python 2 -> 3?
Here a complete example reflecting my code
import inspect
import time
import logging as logger
from functools import wraps
logger.basicConfig(format='LOGGER - %(asctime)s %(message)s', level=logger.DEBUG)
def debug_run(fn):
#wraps(fn)
def wrapper(self, *args, **kw):
logger.debug(
"call method %s of instance %s with %r and %s "
% (fn.__name__, self, args, kw))
time1 = time.time()
res = fn(self, *args, **kw)
time2 = time.time()
logger.debug(
"%s function %0.3f ms" % (fn, (time2-time1)*1000.0))
return res
return wrapper
def decallmethods(decorator):
def dectheclass(cls):
for name, m in inspect.getmembers(
cls, predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
methods_to_inspect = getattr(cls, 'METHODS_TO_INSPECT', [])
if name in methods_to_inspect:
setattr(cls, name, decorator(m))
return cls
return dectheclass
class B(object):
METHODS_TO_INSPECT = ["bfoo1", "bfoo2", "foo"]
def __str__(self):
return "%s:%s" % (repr(self), id(self))
def bfoo1(self):
pass
def bfoo2(self):
pass
def foo(self):
pass
def run(self):
print("print - Base run doing nothing")
class C(object):
pass
#decallmethods(debug_run)
class A(B, C):
METHODS_TO_INSPECT = ["bfoo1", "bfoo2", "foo", "run"]
def foo(self):
print("print - A foo")
def run(self):
self.bfoo1()
self.bfoo2()
self.foo()
a = A()
b = B()
a.run()
b.run()
In this case applying decallmethods to B, will not affect the A so i must to apply to both A and B thus to all sub classes of B.
It is possible to have such mechanism that permit to apply decallmethods to all sub classes methods ?
look at this:
How can I decorate all functions of a class without typing it over and over for each method added? Python
delnan has a good answer,
only add this rule to his answer
if name in getattr(cls, 'METHODS_TO_INSPECT', []):

Resources