473,800 Members | 2,930 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Signals/Slots support in Python

On 5/1/08, Brian Vanderburg II (Br************ **@aim.com) wrote:
>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.
Did you review this?
<http://pydispatcher.so urceforge.net/>

from what I understand is originally based upon this:
<http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/87056>

and subsequently integrated into this:
<http://djangoproject.c om>
>-----
# 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(fn 1)
a.Connect(fn 2)

print "Part 1"
a()

a.DisconnectAl l()

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

a.WeakConnect( O.Action, o1)
a.Connect(o2.A ction)

print "Part 2"
a()

print "Part 3"
o1 = None
a()

print "Part 4"
o2 = None
a()

a.DisconnectAl l()

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(c 2)
a()

a.DisconnectAl l()

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.DisconnectAl l()

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)
-----
--
http://mail.python.org/mailman/listinfo/python-list
Jun 27 '08 #1
1 1790
On Thu, 01 May 2008 08:44:27 -0600, Scott SA wrote:
Did you review this?
<http://pydispatcher.so urceforge.net/>

from what I understand is originally based upon this:
<http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/87056>

and subsequently integrated into this:
<http://djangoproject.c om>
AFAIK PyDispatcher evolved into Louie project [1]. Louie has more
features, but dispatch module inside Django is dramatically faster and is
going to be even faster.

[1] http://pylouie.org/

--
Ivan
Jun 27 '08 #2

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

Similar topics

7
1806
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
2056
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
5977
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
1571
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
2232
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
1841
by: vippstar | last post by:
What is the purpose of signals and why do they exist in C? thanks in advance
0
1014
by: Brian Vanderburg II | last post by:
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
3
3510
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
1321
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
9689
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
9550
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
10269
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...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7573
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
6811
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();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.