473,659 Members | 3,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Signals/Slots support in Python

I don't know if any such support is already built in, so I ended up
making my own simple signals/slots like mechanism. If anyone is
interested then here it is, along with a simple test. It can connect to
normal functions as well as instance methods. It also supports weak
connections where when an object is gone, the slot is gone as well, the
slot just holds a weak reference to the object.

Brian Vanderburg II

# Begin Signal
import weakref
import random

class Signal:
class Slot:
def __init__(self, fn):
self.__fn = fn

def __call__(self, accum, *args, **kwargs):
result = self.__fn(*args , **kwargs)
return accum(result)

class WeakSlot:
def __init__(self, conn, parent, fn, obj):
self.__conn = conn
# Avoid circular references so deleting a signal will
# allow deletion of the signal since the slot doesn't ref
# back to it but only weakefs back to it
self.__parent = weakref.ref(par ent)

self.__fn = fn
self.__obj = weakref.ref(obj , self.Cleanup)

def __call__(self, accum, *args, **kwargs):
obj = self.__obj()
if obj is None:
return True

result = self.__fn(obj, *args, **kwargs)
return accum(result)

def Cleanup(self, ref):
parent = self.__parent()
if parent is not None:
parent.Disconne ct(self.__conn)

class Accumulator:
def __call__(self, *args, **kwargs):
return True

def Finalize(self):
return None

def __init__(self):
self.__slots = [ ]

# This connects a signal to a slot, but stores a strong reference so
# The object will not be deleted as long as the signal is connected
def Connect(self, fn):
conn = self.NewConn()
self.__slots.ap pend([conn, Signal.Slot(fn)])
return conn

# This connects a signal to a slot, but store a weak reference so
# when the object is gone the slot will not be called. Because of
# the implemenations, it is not possible to do WeakConnect(obj .Fn),
# since obj.Fn is a new object and would go to 0 refcount soon after
# the call to WeakConnect completes. Instead we must do a call as
# WeakConnect(Obj Class.Fn, obj)
# Only the object is weak-referenced. The function object is still
# a normal reference, this ensures that as long as the object exists
# the function will also exist. When the object dies, the slot will
# be removed
def WeakConnect(sel f, fn, obj):
conn = self.NewConn()
self.__slots.ap pend([conn, Signal.WeakSlot (conn, self, fn, obj)])
return conn

# Disconnect a slot
def Disconnect(self , conn):
result = self.Find(conn)
if result >= 0:
del self.__slots[result]

# Disconnect all slots
def DisconnectAll(s elf):
self.__slots = [ ]

# Create an accumulator. Accumulator will be called as a callable
# for each return value of the executed slots. Execution of slots
# continues as long as the reutrn value of the accumulator call is
# True. The 'Finalize'funct ion will be called to get the result
# A custom accumulator can be created by deriving from Signal and
# Creating a custom 'Accumulator' class, or by deriving from Singal
# and creating CreateAccumulat or
def CreateAccumulat or(self):
return self.Accumulato r()

# Execute the slots
def __call__(self, *args, **kwargs):
accum = self.CreateAccu mulator()
for conn in xrange(len(self .__slots)):
if not self.__slots[conn][1](accum, *args, **kwargs):
break
return accum.Finalize( )

# Create a connection name
def NewConn(self):
value = 0
while self.Find(value ) >= 0:
value = random.randint( 1, 100000000)
return value

def Find(self, conn):
for i in xrange(len(self .__slots)):
if self.__slots[i][0] == conn:
return i

return -1

# End Signal

def fn1():
print "Hello World"

def fn2():
print "Goodbye Space"

class O:
def __init__(self, value):
self.value = value

def Action(self):
print "O %d" % self.value

a = Signal()

a.Connect(fn1)
a.Connect(fn2)

print "Part 1"
a()

a.DisconnectAll ()

o1 = O(4)
o2 = O(12)

a.WeakConnect(O .Action, o1)
a.Connect(o2.Ac tion)

print "Part 2"
a()

print "Part 3"
o1 = None
a()

print "Part 4"
o2 = None
a()

a.DisconnectAll ()

def f1():
print "Hello Neighbor"

def f2():
print "Back to Work"

c1 = a.Connect(f1)
c2 = a.Connect(f2)

print "Part 5"
a()

print "Part 6"
a.Disconnect(c2 )
a()

a.DisconnectAll ()

def f1(name):
print "Hello %s" % name

def f2(name):
print "Goodbye %s" % name

a.Connect(f1)
a.Connect(f2)

print "Part 7"
#a() # Error
a("Sarah")

a.DisconnectAll ()

class MySignal(Signal ):
class Accumulator:
def __init__(self):
self.value = 0
def __call__(self, value):
self.value += value
return bool(value != 0)
def Finalize(self):
return self.value
def f1(x):
return x * x

def f2(x):
return x + x

def f3(x):
return 0

a = MySignal()
a.Connect(f1)
a.Connect(f2)
a.Connect(f3)

print "Part 8"
print a(5)
Jun 27 '08 #1
0 1002

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1801
by: Boris Boutillier | last post by:
Hi all, Of what I heard Python 2.3 now allow creation of new types in C with slots. Is there somewhere some documentation on this, or at least an example ? Thanks a lot Boris
2
2050
by: Holger Joukl | last post by:
Hi, migrating from good old python 1.5.2 to python 2.3, I have a problem running a program that features some threads which execute calls to an extension module. Problem is that all of a sudden, I cannot stop the program with a keyboard interrupt any more; the installed signal handler does not seem to receive the signal at all. This happens both if I rebuild this extension using python 2.3 headers/library and if I simply use the old...
1
5968
by: Frank Bossy | last post by:
Dear group :) I don't quite understand the meaning of this paragraph in the qt docu (http://doc.trolltech.com/3.1/threads.html): ***SNIP The Signals and Slots mechanism can be used in separate threads, as long as the rules for QObject based classes are followed. The Signals and Slots mechanism is synchronous: when a signal is emitted, all slots are called immediately. The slots are executed in the thread
2
1566
by: tin gherdanarra | last post by:
Dear pythonista, what is a "slot" in python? I stumbled over it in several meta-reflection discussions and hard-core developer talk, but found no mention of it in the language reference. Google coughs up more interesting banter about it, but no specifics. Is it a feature that was once planned (for 2.2 or so) and
5
2225
by: Christian Bruckhoff | last post by:
Hi. I got a problem with Signals and Slots of QT. The program i am speaking of u can find here: http://www.uni-koblenz.de/~brchrist/address/ If u look at gui.cpp u find a connect command at line 27. I would read this command like this: "If pushButtonAddPerson got clicked call the function addPerson() of this GUI-Object" So this connect should call the function starting on line 50. But if i start
11
1825
by: vippstar | last post by:
What is the purpose of signals and why do they exist in C? thanks in advance
1
1783
by: Scott SA | last post by:
On 5/1/08, Brian Vanderburg II (BrianVanderburg2@aim.com) wrote: Did you review this? <http://pydispatcher.sourceforge.net/> from what I understand is originally based upon this: <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87056> and subsequently integrated into this:
3
3502
by: alan | last post by:
This ignores CTRL-C on every platform I've tested: python -c "import threading; threading.Event().wait()" ^C^C^C^C It looks to me like all signals are masked before entering wait(). Can someone familiar with the internals explain and/or justify this behavior? Thanks, -Alan
1
1313
by: Jekzer | last post by:
Hi all ! Well, I am working for my first time in life with Qt libs and I have a few problems. First, I want to make a QApplication very simple to practise signal/slots functionality. The idea is: A QFrame with 1 Qlabel, 1QPushbutton and 1 QLineEdit. When you write something in the line edit, it is printed ( char by char) on the label. The button is used to exit ( close()). Quite easy. Second exercise: the same thing but now, if you...
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8337
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8748
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2754
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.