473,699 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: storing references instead of copies in a dictionary

mk
Calvin Spealman wrote:
To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?
Well, basically nothing except I need to remember I have to do that.

Suppose one does that frequently in a program. It becomes tedious. I
think I will define some helper function then:
>>def helper(fundict, newfun):
.... fundict[newfun.func_nam e] = newfun
....

_If_ there were some shorter and still "proper" way to do it, I'd use
it. If not, no big deal.
For completeness:

def new_f1(arg):
return "NEW f1 " + arg
f1.func_code = new_f1.func_cod e

Don't use that unless you really have to and I nearly promise that you don't.
I promise I won't use it. :-) It seems like a 'wrong thing to do'.
Jul 17 '08 #1
10 1495
mk wrote:
Calvin Spealman wrote:
>To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?

Well, basically nothing except I need to remember I have to do that.

Suppose one does that frequently in a program. It becomes tedious. I
think I will define some helper function then:
>>def helper(fundict, newfun):
... fundict[newfun.func_nam e] = newfun
...

_If_ there were some shorter and still "proper" way to do it, I'd use
it. If not, no big deal.
>For completeness:

def new_f1(arg):
return "NEW f1 " + arg
f1.func_code = new_f1.func_cod e

Don't use that unless you really have to and I nearly promise that you
don't.

I promise I won't use it. :-) It seems like a 'wrong thing to do'.

Well it's probably totally "non pythonic" but this does what you want:

def f2(arg):
return "f2 "+arg

def f1(arg):
return "f1 "+arg

a={"1":"f1","2" :"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]

Don't know if this is any use to you..

Jul 17 '08 #2
mk
def f2(arg):
return "f2 "+arg

def f1(arg):
return "f1 "+arg

a={"1":"f1","2" :"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]
Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
I didn't think of that.
Don't know if this is any use to you..
At least I learned something. :-)


Jul 17 '08 #3
On Jul 17, 10:05*am, mk <mrk...@gmail.c omwrote:
def f2(arg):
* * return "f2 "+arg
def f1(arg):
* * return "f1 "+arg
a={"1":"f1","2" :"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
* * return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]

Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
I didn't think of that.
Don't know if this is any use to you..

At least I learned something. :-)
You want consistent access to a changing variable. Wrap it in an
object:
>>a= Blank( )
a.ref= 'X'
a.ref
'X'
>>b= a
b.ref
'X'
>>a.ref= 'Y'
b.ref
'Y'
>>>
Jul 17 '08 #4
castironpi wrote:
On Jul 17, 10:05 am, mk <mrk...@gmail.c omwrote:
>>def f2(arg):
return "f2 "+arg
def f1(arg):
return "f1 "+arg
a={"1":"f1"," 2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]
Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
I didn't think of that.
>>Don't know if this is any use to you..
At least I learned something. :-)

You want consistent access to a changing variable. Wrap it in an
object:
>>>a= Blank( )
a.ref= 'X'
a.ref
'X'
>>>b= a
b.ref
'X'
>>>a.ref= 'Y'
b.ref
'Y'
My "old fashioned" programing paradigms think of this in terms of
"pointers", a throw back to my schooling in 'C'. I find this general
form of problem to be common across languages and in some ways hard to
express in python. The whole idea of labels bound to objects is quite
alien to traditional terminology. I find one of the main attractions of
python is this new mindset that the language makes you adopt - a
different set of tools are at hand for the old school programmer.

castironpi - please give an example of what you are thinking as I find
this interesting. preferably post some brief example code.
Jul 18 '08 #5
bgeddy wrote:
castironpi wrote:
>On Jul 17, 10:05 am, mk <mrk...@gmail.c omwrote:
>>>def f2(arg):
return "f2 "+arg
def f1(arg):
return "f1 "+arg
a={"1":"f1", "2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]
Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
I didn't think of that.

Don't know if this is any use to you..
At least I learned something. :-)

You want consistent access to a changing variable. Wrap it in an
object:
>>>>a= Blank( )
a.ref= 'X'
a.ref
'X'
>>>>b= a
b.ref
'X'
>>>>a.ref= 'Y'
b.ref
'Y'
My "old fashioned" programing paradigms think of this in terms of
"pointers", a throw back to my schooling in 'C'. I find this general
form of problem to be common across languages and in some ways hard to
express in python. The whole idea of labels bound to objects is quite
alien to traditional terminology. I find one of the main attractions of
python is this new mindset that the language makes you adopt - a
different set of tools are at hand for the old school programmer.

castironpi - please give an example of what you are thinking as I find
this interesting. preferably post some brief example code.
castironpi - please forgive the double post but my newsreader didn't
display your code correctly.. Doh !! Anyway - a nice way of addressing
the problem. However the OP's post revolved around having a rewritable
set of "labels" - which could be recorded at one time and when re
referenced the new definitions of those labels would be used. For
example a "collection " (list,dictionar y,tuple) could be made of these
"labels" and then the underlying code accessed by the labels changed. If
the code was now ran indirectly by referencing the list then the new
code would be ran. These building blocks are how parsers are built and
the basis of language.
I can see how you form two ways of addressing the variable but can't
figure how this fits the original problem. Please elaborate for my
ignorance.

EdH.
Jul 18 '08 #6
On Jul 18, 10:36 am, bgeddy <bge...@home.ha vin.a.breakwrot e:
[snip]
the OP's post revolved around having a rewritable
set of "labels" - which could be recorded at one time and when re
referenced the new definitions of those labels would be used. For
example a "collection " (list,dictionar y,tuple) could be made of these
"labels" and then the underlying code accessed by the labels changed. If
the code was now ran indirectly by referencing the list then the new
code would be ran.
This notion is as dangerous and ludicrous as the COBOL ALTER verb.
These building blocks are how parsers are built and
the basis of language.
Huh?
Jul 18 '08 #7
On Jul 17, 7:36*pm, bgeddy <bge...@home.ha vin.a.breakwrot e:
bgeddy wrote:
castironpi wrote:
On Jul 17, 10:05 am, mk <mrk...@gmail.c omwrote:
def f2(arg):
* * return "f2 "+arg
def f1(arg):
* * return "f1 "+arg
a={"1":"f1"," 2":"f2"}
print [eval(x[1])(x[0]) for x in a.items()]
def f2(arg):
* * return "New f2 "+arg
print [eval(x[1])(x[0]) for x in a.items()]
Neat trick, if probably dangerous in some circumstances. Anyway, thanks,
I didn't think of that.
>>Don't know if this is any use to you..
At least I learned something. :-)
You want consistent access to a changing variable. *Wrap it in an
object:
>>>a= Blank( )
a.ref= 'X'
a.ref
'X'
b= a
b.ref
'X'
a.ref= 'Y'
b.ref
'Y'
My "old fashioned" programing paradigms think of this in terms of
"pointers", a throw back to my schooling in 'C'. I find this general
form of problem to be common across languages and in some ways hard to
express in python. The whole idea of labels bound to objects is quite
alien to traditional terminology. I find one of the main attractions of
python is this new mindset that the language makes you adopt - a
different set of tools are at hand for the old school programmer.
castironpi - please give an example of what you are thinking as I find
this interesting. preferably post some brief example code.

castironpi *- please forgive the double post but my newsreader didn't
display your code correctly.. Doh !! Anyway - a nice way of addressing
the problem. However the OP's post revolved around having a rewritable
set of "labels" - which could be recorded at one time and when re
referenced the new definitions of those labels would be used. For
example a "collection " (list,dictionar y,tuple) could be made of these
"labels" and then the underlying code accessed by the labels changed. If
the code was now ran indirectly by referencing the list then the new
code would be ran. These building blocks are how parsers are built and
the basis of language.
I can see how you form two ways of addressing the variable but can't
figure how this fits the original problem. Please elaborate for my
ignorance.

EdH.
In the OP's post, we have:

def f1(): print 'f1'
def f2(): print 'f2'
funs= [ f1, f2 ]
def f1(): print 'new f1'

They wanted funs[ 0 ] to contain this new function / new definition
too.

Another language might permit:
def funs[ 0 ](): print 'new f1'

Python allows:

def f1(): print 'new f1'
funs[ 0 ]= f1

and

@rebind( funs, 0 )
def f1(): print 'new f1'

and

@rebind_named( funs, 'funA' )
def f1(): print 'new f1'

in the case funs was a dictionary or class or class instance.
Functions remain to be first class objects; their definition syntax is
merely restricted over normal assignments.

To access "whatever 'f1' is pointing to right now", the only way is
with eval, which you showed.

Spealman's solution can accomplish redefinition, but only provided
calling signature and closure, among others, don't change. If they
do, you have to reassign those, too, and possibly more:
>>dir( f )
[snip]
'func_closure', 'func_code', 'func_defaults' , 'func_dict', 'func_doc',
'func_globals', 'func_name'

Roughly the same in 3.0. It's an option.
These building blocks are how parsers are built and
the basis of language.
To address this, I observe altered references are easy for computers.
Suppose:

#--NOT PYTHON--
def f1(): print 'f1'
008902 f1: 0x008934
def f1(): print 'new f1'
008902 f1: 0x008938

'f1()' calls the function the address of which is stored at 008902 in
each case: f1 (at 008934) in the first case, and new f1 (at 008938) in
the second.

Python eliminates that combination from the syntax, which strengthens
object-name identity, at the cost of a slightly longer workaround
(a.ref= f1) for keeping names but changing objects. In this sense,
the only 'pointer' per se is the string name of an object, scoped by a
namespace-- eval( 'f1', spaceA ).

I delicately ask for an example in natural language and daily life in
which we change what object a name refers to, or hold that Python
conforms to natural language better than computer-native mutable
pointers and references.
Jul 18 '08 #8
On Jul 18, 4:26*pm, castironpi <castiro...@gma il.comwrote:
I delicately ask for an example in natural language and daily life in
which we change what object a name refers to,
her, him, it, ... i.e. any pronoun
Jul 18 '08 #9
On 17 juil, 15:56, mk <mrk...@gmail.c omwrote:
Calvin Spealman wrote:
To your actual problem... Why do you wanna do this anyway? If you want
to change the function in the dictionary, why don't you simply define
the functions you'll want to use, and change the one you have bound to
the key in the dictionary when you want to change it? In other words,
define them all at once, and then just d['1'] = new_f1. What is wrong
with that?

Well, basically nothing except I need to remember I have to do that.

Suppose one does that frequently in a program. It becomes tedious. I
think I will define some helper function then:
>>def helper(fundict, newfun):
... fundict[newfun.func_nam e] = newfun
...

_If_ there were some shorter and still "proper" way to do it, I'd use
it.
You're halfway there.

from functools import partial

callbacks = {}
register_callba ck = partial(helper, callbacks)

@register_callb ack
def f1(arg):
print "f1", arg

callbacks['f1']('ok')

@register_callb ack
def f1(arg):
print "new f1", arg

callbacks['f1']('ok')

Jul 18 '08 #10

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

Similar topics

0
1563
by: Feghhi, Jalil | last post by:
I get an error storing an object in a dictionary. The dictionary and the object are both provided by mod_python. One is the session object (which is just a dictionary) and one is a FieldStorage object (I think it is a class but displays as a dictionary). My question is what is the requirement for an object to be able to store it in a dictionary? I am sure there is documentaion somewehre but I couldn't find it. Regards, -Jalil
6
2572
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
12
3941
by: Alfonso Morra | last post by:
I have the ff code for testing the concept of storing objects: #include <vector> #include <iostream> using namespace std ; class MyClass { public: MyClass(){
5
1225
by: lkrubner | last post by:
Is it true that Javascript has no clone() method, to pass an object by copy of value instead of reference? If I have an object and want to make an array out of all of its instance variables, I can loop through it and pass its values to a new array, and the class instances will be passed by copy and not by reference?
6
3042
by: bissatch | last post by:
Hi, I am currently writing a news admin system. I would like to add the ability to add images to each article. What I have always done in the past is uploaded (using a form) the image to a folder on the server and then in the database table that I INSERT the news article, I'll store the path of the uploaded image. To me this seems a bad idea as if the image paths were changed on the
3
2019
by: Brian | last post by:
I know this is the wrong way to do it, but maybe someone can tell me the right way to do it... I have two different databases that I need to synchronize. The database doesn't have keys exactly, but it does provide a rowid function. So, I am storing a dictionary of <string, long>, string being the rowid and long being a sum of the hash code for each column in the row. With this dictionary, it is very easy to determine if a row is...
7
5134
by: Ian Boyd | last post by:
Customer wanted us to figure out why their database was growing at an astronomical rate. We broke down the various fields making up a table, and we found that the ..LB file was using about 1k per row, where the average length of the two combined CLOB fields in the table was 12 bytes (4 bytes standard deviation). So i hex edited the .lb file and found the problem, each clob value is taking 0x400 bytes i.e. 1024 bytes.
2
3289
by: Calvin Spealman | last post by:
In the internal API when a C function is called and passed a kwarg dictionary, is there any case where anything else has a reference to it? I checked with the following code and it looks like even if you explicitly pass a dictionary with **kwargs, it still copies the dictionary anyway. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/
3
1491
by: mk | last post by:
Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): .... return "f2 " + arg .... .... return "f1" + arg ....
0
187
by: Calvin Spealman | last post by:
On Thu, Jul 17, 2008 at 7:45 AM, mk <mrkafk@gmail.comwrote: As was pointed out already, this is a basic misunderstanding of assignment, which is common with people learning Python. To your actual problem... Why do you wanna do this anyway? If you want to change the function in the dictionary, why don't you simply define the functions you'll want to use, and change the one you have bound to the key in the dictionary when you want to...
0
9184
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...
1
8930
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,...
0
8892
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
7761
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
6538
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
5878
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
4381
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
4634
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.