Dear Python developer community,
I'm quite new to Python, so perhaps my question is well known and the
answer too.
I need a variable alias ( what in other languages you would call "a
pointer" (c) or "a reference" (perl))
I read some older mail articles and I found that the offcial position
about that was that variable referencing wasn't implemented because
it's considered bad style.
There was also a suggestion to write a real problem where referencing
is really needed.
I have one...:
I'm trying to generate dynamically class methods which works on
predefined sets of object attributes.
one of these is the set of attributes identfying uniquely the object
(primary key).
A naïve attempt to do the job:
class ObjectClass:
""" Test primary Key assignment """
if __name__ == "__main__":
ObjectClassInst antiated=Object Class()
ObjectClassInst antiated.AnAttr ibute='First PK Elem'
ObjectClassInst antiated.Anothe rOne='Second PK Elem'
ObjectClassInst antiated.Identi fier=[]
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te)
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnotherOn e)
print ObjectClassInst antiated.Identi fier
ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed'
print ObjectClassInst antiated.Identi fier
leads a wrong result ./test.py
['First PK Elem', 'Second PK Elem']
['First PK Elem', 'Second PK Elem']
--> wrong! It should write ['First PK Elem Changed', 'Second PK Elem']
i.e. the assgnment
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te)
assigns only the attribute value, not the reference.
so my question is:
is it still true that there is no possibilty to get directly object
references?
Is there a solution for the problem above ?
Thank you for any feedback and sorry for the long mail
....and the reference to perl :-)
Regs,
Davide 9 1373
Em Sáb, 2006-03-25 Ã*s 21:33 -0800, DrConti escreveu:
[snip] There was also a suggestion to write a real problem where referencing is really needed. I have one...:
[snap]
There are loads of discussions about the code you wrote... but... isn't
bad practice to put the same data in two places? Or am I missing
something?
Cheers,
--
Felipe.
Felipe Almeida Lessa schrieb: Em Sáb, 2006-03-25 às 21:33 -0800, DrConti escreveu: [snip] There was also a suggestion to write a real problem where referencing is really needed. I have one...: [snap]
There are loads of discussions about the code you wrote... but... isn't bad practice to put the same data in two places? Or am I missing something?
Cheers,
-- Felipe.
Hi Felipe, surely it's bad practice to put the same data in two places.
However I don't want to put the data in the identifier list, but just
the reference to the attributes.
My general problem is to find a way to define subsets of instance
attributes (for example the identifier), so that at later time I can
just iterate over the subset.
In the meantime I found a 90% solution to the problem through lambdas..
See now the code below: maybe you'll understand my point better.
Thanks and Regs,
Davide
class ObjectClass:
""" Test primary Key assignment
"""
def alias(self,key) : return lambda: self.__dict__[key]
def __init__(self):
self.Identifier =[]
def getPK(self):
return [ GetPKValue() for GetPKValue in self.Identifier ]
if __name__ == "__main__":
ObjectClassInst antiated=Object Class()
ObjectClassInst antiated.AnAttr ibute='First PK Elem'
ObjectClassInst antiated.Anothe rOne='Second PK Elem'
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.alias('An Attribute'))
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.alias('An otherOne'))
print ObjectClassInst antiated.getPK( )
ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed'
print ObjectClassInst antiated.getPK( )
./test.py
['First PK Elem', 'Second PK Elem']
['First PK Elem Changed', 'Second PK Elem']
--> correct now!
DrConti wrote: class ObjectClass: """ Test primary Key assignment """
if __name__ == "__main__": ObjectClassInst antiated=Object Class() ObjectClassInst antiated.AnAttr ibute='First PK Elem' ObjectClassInst antiated.Anothe rOne='Second PK Elem' ObjectClassInst antiated.Identi fier=[] ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te) ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnotherOn e) print ObjectClassInst antiated.Identi fier ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed' print ObjectClassInst antiated.Identi fier
leads a wrong result ./test.py ['First PK Elem', 'Second PK Elem'] ['First PK Elem', 'Second PK Elem'] --> wrong! It should write ['First PK Elem Changed', 'Second PK Elem']
i.e. the assgnment ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te) assigns only the attribute value, not the reference.
Nono, it assigns the reference alright. In python, EVERYTHING gets assigned only a
reference, .AnAttribute as well. So when you do .AnAttribute = 'Changed', you make it a
reference to a NEW string 'Changed', while .Identifier[0] keeps referencing the 'First PK'
string object.
Strings are an unfortunate example, since they're immutable - once you create a string
object, you cant't modify it any more. But if you had a more complex object, you could do
..AnAttribute.c hangeYourself() , and .Identifier[0] would change accordingly as well,
because .AnAttribute would keep pointing to the same object (albeit changed).
In your case, try .AnAttribute = ['First']; .Identifier[0] = .AnAttribute; .AnAttribute[0]
= 'First changed'; - this will work the way you want it to, because .AnAttribute doesn't
get rebound (only the content of the object (list) it's pointing to change, but it's still
the same object).
DrConti a écrit : Dear Python developer community, I'm quite new to Python, so perhaps my question is well known and the answer too.
I need a variable alias ( what in other languages you would call "a pointer" (c) or "a reference" (perl))
Well, that's the only kind of "variable"[1] in Python.
[1] the correct name in Python is 'binding', since it's about 'binding'
a reference to a name, not labelling an in-memory address and storing
data there.
I read some older mail articles and I found that the offcial position about that was that variable referencing wasn't implemented because it's considered bad style. There was also a suggestion to write a real problem where referencing is really needed. I have one...:
You *think* you have one.
I'm trying to generate dynamically class methods which works on predefined sets of object attributes. one of these is the set of attributes identfying uniquely the object (primary key). A naïve attempt to do the job:
class ObjectClass: """ Test primary Key assignment """
if __name__ == "__main__":
ObjectClassInst antiated=Object Class() ObjectClassInst antiated.AnAttr ibute='First PK Elem' ObjectClassInst antiated.Anothe rOne='Second PK Elem' ObjectClassInst antiated.Identi fier=[] ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te) ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnotherOn e) print ObjectClassInst antiated.Identi fier ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed' print ObjectClassInst antiated.Identi fier
leads a wrong result
./test.py ['First PK Elem', 'Second PK Elem'] ['First PK Elem', 'Second PK Elem'] --> wrong! It should write ['First PK Elem Changed', 'Second PK Elem']
Nope, it's exactly what you asked for !-) i.e. the assgnment
ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te)
assigns only the attribute value, not the reference.
1/ it's not an assignement
2/ it does not store the attribute "value", it stores the reference to
the object the attribute is bound to. When you later rebind the
attribute, it only impact this binding - there's no reason it should
impact other bindings.
so my question is: is it still true that there is no possibilty to get directly object references?
But object references *are* what you have.
Is there a solution for the problem above ?
Yes : keep a reference to the attribute name, not to the value bound to
that name. There are many ways to do it, here's one:
ObjectClass.Ide ntifier = property(
fget=lambda self: [self.AnAttribut e, self.AnotherOne]
)
and here's another one:
ObjectClassInst antiated._ident ifier_parts = []
# note the use of strings, not symbols
ObjectClassInst antiated._ident ifier_parts.app end("AnAttribut e")
ObjectClassInst antiated._ident ifier_parts.app end("AnotherOne ")
ObjectClass.Ide ntifier = property(
fget=lambda self: [getattr(self, name) \
for name in self._identifie r_parts]
)
Thank you for any feedback
May I add some ? Your naming conventions are highly unpythonic. We
usually use CamelCase for classes names, and (in order of preference)
all_lower_with_ underscores or mixedCaps for
variables/attributes/functions etc.
HTH
On Sat, 25 Mar 2006 21:33:24 -0800, DrConti wrote: Dear Python developer community, I'm quite new to Python, so perhaps my question is well known and the answer too.
I need a variable alias ( what in other languages you would call "a pointer" (c) or "a reference" (perl))
Others have given you reasons why you can't do this, or shouldn't do this.
In general, I agree with them -- change your algorithm so you don't
need indirect references.
But if you can't get away from it, here is another work-around that might
help:
class ObjectClass: """ Test primary Key assignment """
if __name__ == "__main__":
ObjectClassInst antiated=Object Class() ObjectClassInst antiated.AnAttr ibute='First PK Elem' ObjectClassInst antiated.Anothe rOne='Second PK Elem' ObjectClassInst antiated.Identi fier=[] ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te) ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnotherOn e) print ObjectClassInst antiated.Identi fier ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed' print ObjectClassInst antiated.Identi fier
# helper class
class Indirect:
def __init__(self, value):
self.value = value
def mutate(self, newvalue):
self.value = newvalue
def __eq__(self, other):
return self.value == other
def __repr__(self):
return "-> %r" % self.value
instance = ObjectClass()
instance.attrib ute = Indirect('First PK Elem')
instance.anothe r_attribute = Indirect('Secon d PK Elem')
instance.identi fier = [instance.attrib ute, instance.anothe r_attribute]
print instance.identi fier
instance.attrib ute.mutate('Fir st PK Elem Changed')
print instance.identi fier
which prints
[-> 'First PK Elem', -> 'Second PK Elem']
[-> 'First PK Elem Changed', -> 'Second PK Elem']
as requested.
--
Steven.
Steven D'Aprano wrote: On Sat, 25 Mar 2006 21:33:24 -0800, DrConti wrote:
Dear Python developer community, I'm quite new to Python, so perhaps my question is well known and the answer too.
I need a variable alias ( what in other languages you would call "a pointer" (c) or "a reference" (perl))
Others have given you reasons why you can't do this, or shouldn't do this. In general, I agree with them -- change your algorithm so you don't need indirect references.
But if you can't get away from it, here is another work-around that might help:
(snip)
And another one, that mess less with attributes (but more with lookup
rules - use it at your own risks !-):
class CompoundAttribu te(object):
def __init__(self, *names):
self._names = names
def __get__(self, obj, objtype):
if obj is None:
return self
return [getattr(obj, name) for name in self._names]
def __set__(self, obj, value):
raise TypeError, "object '%s' does not support assignement" % self
import types
class ObjectClass(obj ect):
def __getattribute_ _(self, name):
v = object.__getatt ribute__(self, name)
if not isinstance(v, types.FunctionT ype) \
and hasattr(v, '__get__'):
return v.__get__(self, self.__class__)
return v
instance = ObjectClass()
instance.attrib ute = 'First PK Elem'
instance.anothe r_attribute = 'Second PK Elem'
instance.identi fier = CompoundAttribu te('attribute', 'another_attrib ute')
NB : Sorry, not tested.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
DrConti wrote: I need a variable alias ( what in other languages you would call "a pointer" (c) or "a reference" (perl))
Or, you think you need it.
I read some older mail articles and I found that the offcial position about that was that variable referencing wasn't implemented because it's considered bad style.
Generally, yes. The line goes, roughly, "You've decided on a solution
and are twisting your problem to fit it."
There was also a suggestion to write a real problem where referencing is really needed. I have one...:
I'm trying to generate dynamically class methods which works on predefined sets of object attributes. one of these is the set of attributes identfying uniquely the object (primary key).
First, this is _not_ a "real problem"; this is a bunch of code. The
"real problem" request is to provide an actual use case, not some code
where you want to write what you want to write.
A naïve attempt to do the job:
class ObjectClass: """ Test primary Key assignment """
if __name__ == "__main__":
ObjectClassInst antiated=Object Class() ObjectClassInst antiated.AnAttr ibute='First PK Elem' ObjectClassInst antiated.Anothe rOne='Second PK Elem' ObjectClassInst antiated.Identi fier=[] ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnAttribu te) ObjectClassInst antiated.Identi fier.append(Obj ectClassInstant iated.AnotherOn e) print ObjectClassInst antiated.Identi fier ObjectClassInst antiated.AnAttr ibute='First PK Elem Changed' print ObjectClassInst antiated.Identi fier
If you insist on this kind of approach, you could use a pair of
an object, and an attribute name as a "reference, " and use getattr
and setattr to access the identified attribute. _But__ I emphasize
that you are thinking about your problem from the point of view
of a solution, not from the point of view of the problem.
You'd probably like this:
class Example(object) :
""" Test primary Key assignment """
def __init__(self, one, two, other):
self.one = one
self.two = two
self.other = other
def __repr__(self):
return '%s(%r, %r, %r)' % (
type(self).__na me__, self.one, self.two, self.other)
if __name__ == "__main__":
eg = Example(3.1415, 3+4j, 'pi')
ref_attr = eg, 'one'
ref_other = eg, 'other'
print eg, getattr(*ref_at tr), getattr(*ref_ot her)
eg.one = 'First PK Elem'
print eg, getattr(*ref_at tr), getattr(*ref_ot her)
setattr(*ref_ot her + (u'Strangely',) )
print eg, getattr(*ref_at tr), getattr(*ref_ot her)
But you might consider this:
class Another(Example ):
""" Test primary Key assignment """
key = ('one', 'two')
def getkey(v):
return [getattr(v, part) for part in v.key]
if __name__ == "__main__":
eg2 = Another(3.1415, 3+4j, 'pi')
print eg2, getkey(eg2)
eg2.one = 'First PK Elem'
print eg2, getkey(eg2)
setattr(eg2, 'two', u'Strangely')
print eg2, getkey(eg2)
--
-Scott David Daniels sc***********@a cm.org
Hi Bruno, hi folks!
thank you very much for your advices.
I didn't know about the property function.
I learned also quite a lot now about "references ".
Ok everything is a reference but you can't get a reference of a
reference...
I saw a lot of variations on how to solve this problem, but I find
actually that the "property approach" is the most natural of all.
Basically the idea there is that you build up this list of class
attributes not by storing a reference
to a class attribute (which seem to be impossible), but you just store
on each element of the list one method (pardon a reference to..) to get
the associated class attribute.
Sorry for the UnPythonity. I used to be a CamelRider.
But not very longtime ago I left the Camel in the Desert, because I met
the Snake....
Regs,
Davide.
DrConti wrote: Hi Bruno, hi folks! thank you very much for your advices. I didn't know about the property function. I learned also quite a lot now about "references ". Ok everything is a reference but you can't get a reference of a reference...
I saw a lot of variations on how to solve this problem, but I find actually that the "property approach" is the most natural of all.
So I need to add a little correction to the code snippet (sorry, got
confused by your namings - ie 'ObjectClass' - and some recent
exploration I did about per-instance descriptors) : Actually, using a
property as an *instance* attribute won't work - unless the class
redefine __getattribute_ _ this way:
class ObjectClass(obj ect):
def __getattribute_ _(self, name):
v = object.__getatt ribute__(self, name)
if not isinstance(v, types.FunctionT ype) \
and hasattr(v, '__get__'):
return v.__get__(self, self.__class__)
return v
Basically the idea there is that you build up this list of class attributes
These are not *class* attributes, but *instance* attributes.
I think you should really take some time to learn more about Python's
object model, attribute lookup rules, descriptors and metaclasses.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])" This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Chris S. |
last post by:
I'm trying to make a graphical editor and browser for Pickled files. One
aspect I'm not sure about is how to detect multiple references to the
same data.
For instance, say I had the Pickled data:
a=
b=
c=
d=
|
by: Mark D. Anderson |
last post by:
About a month ago Richard Cornford did an interesting analysis of a
memory leak
in jscript (internet explorer) when there are "circular" references
between
DOM objects and (real) jscript objects:
http://groups.google.com/groups?selm=bcq6fn%24g53%241%248300dec7%40news.demon.co.uk
This message summarizes some testing I've done and their results.
These results somewhat contradict Cornford's conclusions; I haven't
|
by: Steven T. Hatton |
last post by:
This may seem like such a simple question, I should be embarrassed to ask
it. The FAQ says an object is "A region of storage with associated
semantics." OK, what exactly is meant by "associated semantics"? What, if
any, associated semantics are shared by all objects? That part seems to go
beyond the FAQ.
Does anybody know of a resource that discusses (focuses on) this topic?
--
p->m == (*p).m == p.m
|
by: RobG |
last post by:
I am playing with a script that will allow columns of a table to be
moved by dragging them left or right. To do this with functions is
fairly straight forward, however after looking at Richard Cornford's
version of Table Highlighter I decided to do it using an object.
Richard's basic code structure is:
var SomeObject = (function()
{
function someFn01(){
|
by: Robert Zurer |
last post by:
I have a large pool of business objects all referencing one another in
various ways.
In the client application I want to do something like
employee.Delete();
Behind the scenes, I want to remove all references to the object
allowing it to be garbage collected. I then want to remove the physical
representation of the object from persistance. Unless I have missed a
scenario, the references to the object can be deleted in two ways
| |
by: Michael Moreno |
last post by:
Hello,
In a class I have this code:
public object Obj;
If Obj is a COM object I would like to call in the Dispose() method the
following code:
System.Runtime.InteropServices.Marshal.ReleaseComObject(Obj);
|
by: anonymous.user0 |
last post by:
The way I understand it, if I have an object Listener that has
registered as a listener for some event Event that's produced by an
object Emitter, as long as Emitter is still allocated Listener will
stay alive. Is this correct?
If this is correct, I've got a problem. Let's say I've got an object
Customer that has an PurchaseList (Collection) of Purchase objects.
Now, these Purchase objects were pulled from a datasource Datasource.
The...
|
by: yb |
last post by:
Hi,
Is there a standard for the global 'window' object in browsers? For
example, it supports methods such as setInterval and clearInterval, and
several others.
I know that w3c standardized several parts of the DOM, but this does
not include the window object.
Thank you
|
by: Stef Mientki |
last post by:
hello,
I'm trying to build a simple functional simulator for JAL (a Pascal-like language for PICs).
My first action is to translate the JAL code into Python code.
The reason for this approach is that it simplifies the simulator very much.
In this translation I want to keep the JAL-syntax as much as possible intact,
so anyone who can read JAL, can also understand the Python syntax.
One of the problems is the alias statement, assigning a...
|
by: Astley Le Jasper |
last post by:
Sorry for the numpty question ...
How do you find the reference name of an object?
So if i have this
bob = modulename.objectname()
how do i find that the name is 'bob'
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
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...
| |
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: 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...
| |