473,729 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Weakrefs to classes that derive from str

Why doesn't this work?
from weakref import ref
class C(str): pass .... ref(C()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create weak reference to 'C' object
Note that this does work:
class D(int): pass .... ref(D()) <weakref at 0x53e10; dead>


Likewise for floats, lists, etc. Everything but strs.

rg
Jul 18 '05 #1
12 2727
Ron Garret wrote:
Why doesn't this work?
from weakref import ref
class C(str): pass ...ref(C())

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create weak reference to 'C' object


Note that you don't need the class redirection:

py> ref('')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: cannot create weak reference to 'str' object

But I don't know why strings aren't valid arguments to ref...

STeVe
Jul 18 '05 #2
In article <bv************ ********@comcas t.com>,
Steven Bethard <st************ @gmail.com> wrote:
Ron Garret wrote:
Why doesn't this work?
>from weakref import ref
>class C(str): pass

...
>ref(C())

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create weak reference to 'C' object


Note that you don't need the class redirection:

py> ref('')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: cannot create weak reference to 'str' object

But I don't know why strings aren't valid arguments to ref...


None of the native types (int, float, list, tuple, etc.) can have weak
references, but wrapping them in a class is supposed to get around that.
And it does -- for all classes except str.

rg
Jul 18 '05 #3
Ron Garret wrote:
Note that you don't need the class redirection:

py> ref('')
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: cannot create weak reference to 'str' object

But I don't know why strings aren't valid arguments to ref...


None of the native types (int, float, list, tuple, etc.) can have weak
references, but wrapping them in a class is supposed to get around that.
And it does -- for all classes except str.


Interesting. Is the wrapping thing documented somewhere? I didn't see
it in the documentation for weakref.ref (though I have been known to be
blind occasionally) ;)

STeVe
Jul 18 '05 #4
Steven Bethard wrote:
Ron Garret wrote:
None of the native types (int, float, list, tuple, etc.) can have weak
references, but wrapping them in a class is supposed to get around
that. And it does -- for all classes except str.


Interesting. Is the wrapping thing documented somewhere? I didn't see
it in the documentation for weakref.ref (though I have been known to be
blind occasionally) ;)


I believe it's here: http://docs.python.org/lib/module-weakref.html
if you search for the string "Not all" and read the next two
paragraphs.

On the other hand, it says (there) only that "several builtin
types such as list and dict ... can add support through
subclassing", and does not say anything about int, str, etc...

-Peter
Jul 18 '05 #5
Peter Hansen wrote:
I believe it's here: http://docs.python.org/lib/module-weakref.html
if you search for the string "Not all" and read the next two
paragraphs.

On the other hand, it says (there) only that "several builtin
types such as list and dict ... can add support through
subclassing", and does not say anything about int, str, etc...


Ahh, thanks for the help. I guess there are at least two solutions to
the OP's problem then:

(1) Document that str and subclasses of str can't be weakreffed (easy)
(2) Change str so that it (or at least its subclasses) can be weakreffed
(hard)

Probably either way a feature request should be filed.

STeVe
Jul 18 '05 #6
In article <tu************ ********@powerg ate.ca>,
Peter Hansen <pe***@engcorp. com> wrote:
Steven Bethard wrote:
Ron Garret wrote:
None of the native types (int, float, list, tuple, etc.) can have weak
references, but wrapping them in a class is supposed to get around
that. And it does -- for all classes except str.


Interesting. Is the wrapping thing documented somewhere? I didn't see
it in the documentation for weakref.ref (though I have been known to be
blind occasionally) ;)


I believe it's here: http://docs.python.org/lib/module-weakref.html
if you search for the string "Not all" and read the next two
paragraphs.

On the other hand, it says (there) only that "several builtin
types such as list and dict ... can add support through
subclassing", and does not say anything about int, str, etc...


Empirically:
from weakref import ref
def foo(c): .... class C(c): pass
.... ref(C())
.... foo(int)
foo(float)
foo(dict)
foo(list)
foo(str) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object foo(tuple) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object foo(long) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
TypeError: cannot create weak reference to 'C' object


Ah, it appears that non-immediate immutable types don't support
weakrefs. Hm...

rg
Jul 18 '05 #7
Ron Garret wrote:
foo(int)
foo(float )
foo(dict)
foo(list)
foo(str) TypeError: cannot create weak reference to 'C' object
foo(tuple ) TypeError: cannot create weak reference to 'C' object
foo(long)

TypeError: cannot create weak reference to 'C' object

Ah, it appears that non-immediate immutable types don't support
weakrefs. Hm...


I see the same results you do, and yet I don't understand
the comment. Can you please explain what "immediate"
means in this context?

-Peter
Jul 18 '05 #8
[Ron Garret]
Why doesn't this work?
from weakref import ref
class C(str): pass ... ref(C())
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create weak reference to 'C' object

. . . Everything but strs.


Also subclasses of tuple are not weak referencable.

The issue is in the design of the C structure as a variable-sized immutable
object. Both strings and tuples allocate as a single unit of memory that holds
both the header information and the content information (the characters in a
string or the array of object pointers for a tuple). Since the size varies from
one string or tuple to the next, there is no straight-forward way for a subclass
to add an additional header field pointing to a list of weak references.

For lists and dicts, this is not a problem because the object is allocated in
two sections, a fixed size header component and a pointer to another area of
memory to hold the contents of the collection. This makes it possible for a
subclass to graft-on a weak reference pointer at a known, fixed offset from the
beginning of the header.

There are two ways to fix this. One is to add a weak reference pointer to every
string object -- that way you wouldn't even have to subclass it. Another way is
to break the object into two pieces as is done for mutable containers like dicts
and lists.

Both approaches consume time and space. In general, that is not a big deal, but
fast, memory efficient strings and tuples are at the center of all things
Python. The need to weak reference this objects is somewhat rare in comparison
to the frequency of their other uses. It did not make sense to always pay a
time/space penalty just to create the possibility of weak referencing.

While the design decision is unlikely to change, the docs could certainly be
improved. A doc patch would be welcome.

FWIW, the work-arounds are to weak-reference instances of UserString or to
create a custom class with a has-a relationship instead of an is-a relationship.
Raymond Hettinger
Jul 18 '05 #9
In article <-4************** ******@powergat e.ca>,
Peter Hansen <pe***@engcorp. com> wrote:
Ron Garret wrote:
>foo(int)
>foo(float )
>foo(dict)
>foo(list)
>foo(str)

TypeError: cannot create weak reference to 'C' object
>foo(tuple )

TypeError: cannot create weak reference to 'C' object
>foo(long)

TypeError: cannot create weak reference to 'C' object

Ah, it appears that non-immediate immutable types don't support
weakrefs. Hm...


I see the same results you do, and yet I don't understand
the comment. Can you please explain what "immediate"
means in this context?


"Immediate" means a data type that will fit entirely in a machine
register, and therefore doesn't need to actually be stored in memory.
Ints and floats are the only two immediate types in Python. They are
immutable, but you can still create weakrefs to classes that derive from
them.

rg
Jul 18 '05 #10

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

Similar topics

1
1766
by: William Trenker | last post by:
I'm trying to get a better grasp on the difference between weakref.ref and weakref.proxy. I've read PEP 205 and goolged for additional description information on weakrefs, but I'm not finding much. The docs for the weakref module includes the line "XXX -- need to say more here!". Can anyone point me to tutorials or examples that illustrate where and why one would use a proxy instead of a ref? Thanks, Bill
2
4885
by: | last post by:
I have this class ------------- class Component { /*class*/ Data *d; /*class*/ Draw *a; }; ------------- from "Component" derive classes like "TextBox", "Button", "Label", "ComboBox" etc from "Draw" derive classes like "TextBoxDraw", "ButtonDraw", "LabelDraw", "ComboBoxDraw" etc from "Data" derive classes like "TextBoxData", "ButtonData", "LabelData", "ComboBoxData" etc
11
1948
by: mem | last post by:
Concrete classes are ones that can be instantiated directly, as long as it doesn't have pure virtual function. However, people suggest that "Don't derive from concrete classes." Does this mean that either make it abstract base class for it to be derivable or keep them as "concrete" not to be derived at all? Then what's the purpose of "concrete classes" of ordinary virtual function(s)? Thanks!
2
3051
by: Indiana Epilepsy and Child Neurology | last post by:
Before asking this questions I've spent literally _years_ reading (Meyer, Stroustrup, Holub), googling, asking more general design questions, and just plain thinking about it. I am truly unable to figure out what would be a "proper" OO design (in C++) for this. There may be alternatives to writing my own ODBC handle classes, and I may be interested in them, but I'd like to pursue this particular problem, if for no other reason than to...
9
5199
by: Sean Kirkpatrick | last post by:
To my eye, there doesn't seem to be a whole lot of difference between the two of them from a functional point of view. Can someone give me a good explanation of why one vs the other? Sean
6
1769
by: Peter Oliphant | last post by:
I just discovered that the ImageList class can't be inherited. Why? What could go wrong? I can invision a case where someone would like to add, say, an ID field to an ImageList, possible so that the individual elements in an array of ImageList's could be identified by the ID, thereby allowing re-ordering the array without harm. A person could identify by index into the array, but that would not be preserved by re-ordering (and re-ordering...
0
2074
by: Kamilche | last post by:
''' event.py An event manager using publish/subscribe, and weakrefs. Any function can publish any event without registering it first, and any object can register interest in any event, even if it doesn't exist yet. The event manager uses weakrefs, so lists of listeners won't stop them
6
2943
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by calling Mesh class functions. Let's say they point to each other like this: class Vertex { HalfEdge *edge; }; class HalfEdge { Vertex* vert;
11
1469
by: Mathias Panzenboeck | last post by:
Hi. I have a problem with weak refs and bound methods. The best explanation for the problem is a short bit of code. I have the three classes Wrapper, Foo and Bar: import weakref class Wrapper(object): def __init__(self,x): self.x = weakref.ref(x)
0
8917
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
8761
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
9426
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
9142
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
8148
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
6722
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
4525
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...
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
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.