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

Home Posts Topics Members FAQ

yield, curry, mix-in, new.function, global, closure, .... what will work?

Dear list,

maybe I'm overlooking something obvious or this is not possible at all
or I don't know. Please, consider the following code:

## insert here anything you like

def changer():
change_i('chang ed_i')
change_j('chang ed_j')

def run(i='', j=''):

## insert here anything you like

return i, j

run() == 'changed_i', 'changed_j'

Let me explain: First, changer() is kind of templating language so it
should be written down in this form - however, it can change during
run-time as you like. Basically, it is just ordinary python code which
changes (should change) the local variables of another function,
run(). Oh, and it has to be *thread-safe*.

Here's what I tried and didn't work (maybe I just haven't tried hard
enough):
- pass i, j around: changer(i, j) and change_i(i, arg) - easiest, most
obvious solution - can't do it, certainly not during writing of the
code - have to preserve changer()'s form
- global variable - not thread-safe
- in run(), create dummy closure for changer() and call it -
new.function(bl ah, blah, blah, dummy.func_clos ure) - not thread safe,
i guess, and besides change_i() and change_j() would also need a such
a trick - I am not sure how to alter the codeobject of changer()
- new.function(ne w.code(... - oh my, this won't work
- in run(), modify change_i() and change_j() so it actually yield-s
the changes, collect them here - something like: change_i.__call __ =
return yield ('changed_i', 'comes_from_cha nger_i()') - doesn't work,
of course
- update locals() - yes!! - no!! - doen't work, it's just a copy
- curry, mix-in, ... - hmm....
- eval(blah, blah, locals()) - not safe, ugly - maybe? what do you
think?
- find out which file changer() is written in, which line it starts
and ends, read that file's section, parse, edit, append the needed
local variable's declarations, compile to changer_new() and changer =
changer_new - there has to be something better! :)

So, to wrap up, the question is: how can I pass a variable from one
function to another, without writing down function's argument during
coding, and still be thread-safe?

I can only hope you are still with me and not very confused....

Thanks for any feedback!!

Apr 15 '07 #1
8 1895
ec*******@gmail .com writes:
Let me explain: First, changer() is kind of templating language so it
should be written down in this form - however, it can change during
run-time as you like. Basically, it is just ordinary python code which
changes (should change) the local variables of another function,
run(). Oh, and it has to be *thread-safe*.
That is total madness. Just use a normal object or dictionary with a lock.
Apr 15 '07 #2
On Apr 15, 8:07 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
That is total madness. Just use a normal object or dictionary with a lock.
Please, can you elaborate further, I'm not sure if I understood.
Should I lock global variables i, j during the execution of run()? In
that case I have to apologize, I showed rather simplified version of
the actual problem I have - in fact changer() and run() will be a bit
more complex thus executing a bit longer and perhaps causing a dead-
lock.

Apr 16 '07 #3
ec*******@gmail .com writes:
On Apr 15, 8:07 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
That is total madness. Just use a normal object or dictionary with a lock.

Please, can you elaborate further, I'm not sure if I understood.
Should I lock global variables i, j during the execution of run()? In
that case I have to apologize, I showed rather simplified version of
the actual problem I have - in fact changer() and run() will be a bit
more complex thus executing a bit longer and perhaps causing a dead-lock.
Put both variables into one shared object with a lock (see the docs for
threading.RLock ()). Acquire the lock before modifying or reading the
variables, and release it afterwards. That is the traditional way.
Another way popular in Python is to have separate threads for changer
and run, and have them communicate through Queue.Queue objects. In no
case should you attempt to write a function that messes with another
function's local variables. Local variables are called "local" for a
reason ;-).

Basically this stuff takes more understanding and getting used to than
I can really convey in a newsgroup post. You might look at some
Wikipedia articles or ASPN recipes about concurrent programming, or
get the Python Cookbook.
Apr 16 '07 #4
On Apr 16, 3:05 am, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
ecir.h...@gmail .com writes:
Please, can you elaborate further, I'm not sure if I understood.
Should I lock global variables i, j during the execution of run()? In
that case I have to apologize, I showed rather simplified version of
the actual problem I have - in fact changer() and run() will be a bit
more complex thus executing a bit longer and perhaps causing a dead-lock.

Put both variables into one shared object with a lock (see the docs for
threading.RLock ()). Acquire the lock before modifying or reading the
variables, and release it afterwards. That is the traditional way.
Thanks for the reply! And at the same time, please bear with me.

If I understand correctly: when one thread acquires the lock, every
other thread has to wait. If so, this is not exacly what I would like
to have since the thread might take a bit longer to finish.

The reason why I try so hard to use local variables is that they are
inherently thread-safe. So I don't even mind to copy changer() every
time run() is called - run() has it's own local variables i, j, no one
has to touch them except it's ("local") function changer(). But the
problem is, I don't know how to propagate run()'s variables into
changer() without declarating them as changer()'s arguments (it would
be ok to append the declaration during run-time, though, if I only
knew how).

Apr 16 '07 #5
On Apr 16, 7:28 am, ecir.h...@gmail .com wrote:
On Apr 16, 3:05 am, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
ecir.h...@gmail .com writes:
Please, can you elaborate further, I'm not sure if I understood.
Should I lock global variables i, j during the execution of run()? In
that case I have to apologize, I showed rather simplified version of
the actual problem I have - in fact changer() and run() will be a bit
more complex thus executing a bit longer and perhaps causing a dead-lock.
Put both variables into one shared object with a lock (see the docs for
threading.RLock ()). Acquire the lock before modifying or reading the
variables, and release it afterwards. That is the traditional way.

Thanks for the reply! And at the same time, please bear with me.

If I understand correctly: when one thread acquires the lock, every
other thread has to wait. If so, this is not exacly what I would like
to have since the thread might take a bit longer to finish.

The reason why I try so hard to use local variables is that they are
inherently thread-safe. So I don't even mind to copy changer() every
time run() is called - run() has it's own local variables i, j, no one
has to touch them except it's ("local") function changer(). But the
problem is, I don't know how to propagate run()'s variables into
changer() without declarating them as changer()'s arguments (it would
be ok to append the declaration during run-time, though, if I only
knew how).
In Python, names are bound to objects. The parameter names passed to
a function *are not inherently thread safe*! Python parameters are
not passed-by-value. To show you what I mean:
>>spam = ["delicious"]
def test(meal):
.... global spam
.... if spam is meal:
.... print "Spam is the same object as meal"
....
>>test(spam)
Spam is the same object as meal

(While the "global spam" statement is optional in this case, I wanted
to make it painfully obvious where the "spam" name in function test is
coming from.)

It is thread-safe to rebind the name "meal" in the function test (ie,
meal = "Green eggs"). It is not thread-safe to mutate or modify the
object that meal is bound to. In the example given above, appending
data to the list, removing data, changing elements, and other
operations will cause potential race conditions across multiple
threads.

Follow Paul's advice and get acquainted with the issues of concurrent
and threaded programming. Judicious locking will help avoid most race
conditions. If you don't want to keep other threads waiting, make a
copy of your data then release the data lock.

Depending on the data, you can usually have multiple threads "reading"
the data, as long as no other threads write to the data while there
are any readers. A writer can be allowed to change the data, but only
if there are no readers and no other writers. (This is commonly known
as a read/write lock.) I didn't see a read/write lock in the Python
documentation with some casual browsing, but one can be implemented
from the existing thread locking mechanisms.

Your description of what you want to do is rather vague, so I can't
get too specific. You've described how you want to do things, but I
don't know what you're trying to accomplish. Where possible, simplify
your design.

--Jason

Apr 16 '07 #6
On Apr 16, 5:36 pm, "Jason" <tenax.racc...@ gmail.comwrote:
On Apr 16, 7:28 am, ecir.h...@gmail .com wrote:
On Apr 16, 3:05 am, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
ecir.h...@gmail .com writes:
Please, can you elaborate further, I'm not sure if I understood.
Should I lock global variables i, j during the execution of run()? In
that case I have to apologize, I showed rather simplified version of
the actual problem I have - in fact changer() and run() will be a bit
more complex thus executing a bit longer and perhaps causing a dead-lock.
Put both variables into one shared object with a lock (see the docs for
threading.RLock ()). Acquire the lock before modifying or reading the
variables, and release it afterwards. That is the traditional way.
Thanks for the reply! And at the same time, please bear with me.
If I understand correctly: when one thread acquires the lock, every
other thread has to wait. If so, this is not exacly what I would like
to have since the thread might take a bit longer to finish.
The reason why I try so hard to use local variables is that they are
inherently thread-safe. So I don't even mind to copy changer() every
time run() is called - run() has it's own local variables i, j, no one
has to touch them except it's ("local") function changer(). But the
problem is, I don't know how to propagate run()'s variables into
changer() without declarating them as changer()'s arguments (it would
be ok to append the declaration during run-time, though, if I only
knew how).

In Python, names are bound to objects. The parameter names passed to
a function *are not inherently thread safe*! Python parameters are
not passed-by-value. To show you what I mean:
>spam = ["delicious"]
def test(meal):

... global spam
... if spam is meal:
... print "Spam is the same object as meal"
...>>test(spam)

Spam is the same object as meal

(While the "global spam" statement is optional in this case, I wanted
to make it painfully obvious where the "spam" name in function test is
coming from.)

It is thread-safe to rebind the name "meal" in the function test (ie,
meal = "Green eggs"). It is not thread-safe to mutate or modify the
object that meal is bound to. In the example given above, appending
data to the list, removing data, changing elements, and other
operations will cause potential race conditions across multiple
threads.

Follow Paul's advice and get acquainted with the issues of concurrent
and threaded programming. Judicious locking will help avoid most race
conditions. If you don't want to keep other threads waiting, make a
copy of your data then release the data lock.

Depending on the data, you can usually have multiple threads "reading"
the data, as long as no other threads write to the data while there
are any readers. A writer can be allowed to change the data, but only
if there are no readers and no other writers. (This is commonly known
as a read/write lock.) I didn't see a read/write lock in the Python
documentation with some casual browsing, but one can be implemented
from the existing thread locking mechanisms.

Your description of what you want to do is rather vague, so I can't
get too specific. You've described how you want to do things, but I
don't know what you're trying to accomplish. Where possible, simplify
your design.

--Jason
All I was trying to do, was to get rid of those 'k's in changer():

def change_i(k, arg):
k[0] = arg

def change_j(k, arg):
k[1] = arg

def changer(k):
change_i(k, 'changed_i')
change_j(k, 'changed_j')

def run(i='', j=''):
k = [i, j]
changer(k)
[i, j] = k
return i, j

print run() == ('changed_i', 'changed_j')

Maybe I made a mistake, I should have asked this first, sorry. If the
only way to accomplish this is through locks, then I guess I better
use those 'k's, what do you think?

Thanks Jason, thanks Paul!

Apr 16 '07 #7
I'm reading the docs now and I stumbled upon something:
section "15.3 threading -- Higher-level threading interface" mensions
a class "local", in which "... Thread-local data are data whose values
are thread specific. ..."

Does it mean, I can create global variables whose changing is thread-
safe?
More specific:

import threading

def change_i(arg):
global k
k.i = arg

def change_j(arg):
global k
k.j = arg

def changer():
change_i('chang ed_i')
change_j('chang ed_j')

def run(i='', j=''):
global k
k = threading.local ()
k.i = i
k.j = j
changer()
i = k.i
j = k.j
return i, j

print run() == ('changed_i', 'changed_j')

Is this ok?

Apr 17 '07 #8
On Apr 17, 3:51 am, ecir.h...@gmail .com wrote:
I'm reading the docs now and I stumbled upon something:
section "15.3 threading -- Higher-level threading interface" mensions
a class "local", in which "... Thread-local data are data whose values
are thread specific. ..."

Does it mean, I can create global variables whose changing is thread-
safe?
More specific:

import threading

def change_i(arg):
global k
k.i = arg

def change_j(arg):
global k
k.j = arg

def changer():
change_i('chang ed_i')
change_j('chang ed_j')

def run(i='', j=''):
global k
k = threading.local ()
k.i = i
k.j = j
changer()
i = k.i
j = k.j
return i, j

print run() == ('changed_i', 'changed_j')

Is this ok?
I was too quick, "k = threading.local ()" has to by outside of run(),
right?

Apr 17 '07 #9

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

Similar topics

5
2390
by: Peter | last post by:
My client wants to develop a web application using Java. I have several questions and seeking for MVP advise. 1. Does IIS support Sun Micro Java? 2. Is it possible for .NET to mix with Java, servlet, JSP etc? 3. Can I a ASP.NET call Java servlet? 4. Can I mix MS Web Service with Java? Many Thanks
5
260
by: Peter | last post by:
My client wants to develop a web application using Java. I have several questions and seeking for MVP advise. 1. Does IIS support Sun Micro Java? 2. Is it possible for .NET to mix with Java, servlet, JSP etc? 3. Can I a ASP.NET call Java servlet? 4. Can I mix MS Web Service with Java? Many Thanks
1
1079
by: castironpi | last post by:
What if I say oath= yield or other= yield ?
13
1823
by: Martin Sand Christensen | last post by:
Hi! First a bit of context. Yesterday I spent a lot of time debugging the following method in a rather slim database abstraction layer we've developed: ,---- | def selectColumn(self, table, column, where={}, order_by=, group_by=): | """Performs a SQL select query returning a single column
17
1887
by: castironpi | last post by:
Why can't I write this?
0
9690
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
10275
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
10033
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
7576
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
5471
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
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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

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.