473,802 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I create customized classes that have similar properties as'str'?

I mean, all the class instances that equal to each other should be
reduced into only one instance, which means for instances of this
class there's no difference between a is b and a==b.

Thank you.
Nov 24 '07 #1
25 1579
I find myself frequently in need of classes like this for two reasons.
First, it's efficient in memory. Second, when two instances are
compared for equality only their pointers are compared. (I think
that's how Python compares 'str's.

On Nov 24, 6:31 pm, Licheng Fang <fanglich...@gm ail.comwrote:
I mean, all the class instances that equal to each other should be
reduced into only one instance, which means for instances of this
class there's no difference between a is b and a==b.

Thank you.
Nov 24 '07 #2
Licheng Fang wrote:
I mean, all the class instances that equal to each other should be
reduced into only one instance, which means for instances of this
class there's no difference between a is b and a==b.
If you only want that if "a == b" is True also "a is b" is True,
overload the is_ attribute of your class. Personally, I don't see
any advantage in this.

Regards,
Björn

--
BOFH excuse #352:

The cables are not the same length.

Nov 24 '07 #3
Licheng Fang wrote:
I find myself frequently in need of classes like this for two
reasons. First, it's efficient in memory.
Are you using millions of objects, or MB size objects? Otherwise,
this is no argument.

BTW, what happens if you, by some operation, make a == b, and
afterwards change b so another object instance must be created?
This instance management is quite a runtime overhead.
Second, when two instances are compared for equality only their
pointers are compared.
I state that the object management will often eat more performance
than equality testing. Except you have a huge number of equal
objects. If the latter was the case you should rethink your program
design.
(I think that's how Python compares 'str's.
Generally not. In CPython, just very short strings are created only
once.
>>a=" "
b=" "
a is b
True
>>a=" "
b=" "
a is b
False

Regards,
Björn

--
BOFH excuse #430:

Mouse has out-of-cheese-error

Nov 24 '07 #4
On Nov 24, 7:05 pm, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n.. .@spamgourmet.c omwrote:
Licheng Fang wrote:
I find myself frequently in need of classes like this for two
reasons. First, it's efficient in memory.

Are you using millions of objects, or MB size objects? Otherwise,
this is no argument.
Yes, millions. In my natural language processing tasks, I almost
always need to define patterns, identify their occurrences in a huge
data, and count them. Say, I have a big text file, consisting of
millions of words, and I want to count the frequency of trigrams:

trigrams([1,2,3,4,5]) == [(1,2,3),(2,3,4) ,(3,4,5)]

I can save the counts in a dict D1. Later, I may want to recount the
trigrams, with some minor modifications, say, doing it on every other
line of the input file, and the counts are saved in dict D2. Problem
is, D1 and D2 have almost the same set of keys (trigrams of the text),
yet the keys in D2 are new instances, even though these keys probably
have already been inserted into D1. So I end up with unnecessary
duplicates of keys. And this can be a great waste of memory with huge
input data.
>
BTW, what happens if you, by some operation, make a == b, and
afterwards change b so another object instance must be created?
This instance management is quite a runtime overhead.
I probably need this class to be immutable.
Second, when two instances are compared for equality only their
pointers are compared.

I state that the object management will often eat more performance
than equality testing. Except you have a huge number of equal
objects. If the latter was the case you should rethink your program
design.
Yeah, counting is all about equal or not.
(I think that's how Python compares 'str's.

Generally not. In CPython, just very short strings are created only
once.
>a=" "
b=" "
a is b
True
>a=" "
b=" "
a is b
Wow, I didn't know this. But exactly how Python manage these strings?
My interpretator gave me such results:
>>a = 'this'
b = 'this'
a is b
True
>>a = 'this is confusing'
b = 'this is confusing'
a is b
False

False

Regards,

Björn

--
BOFH excuse #430:

Mouse has out-of-cheese-error
Nov 24 '07 #5
Licheng Fang wrote:
On Nov 24, 7:05 pm, Bjoern Schliessmann <usenet-
>BTW, what happens if you, by some operation, make a == b, and
afterwards change b so another object instance must be created?
This instance management is quite a runtime overhead.

I probably need this class to be immutable.
IMHO you don't need a change of Python, but simply a special
implementation (probably using metaclasses/singletons).
Wow, I didn't know this. But exactly how Python manage these
strings?
I don't know (use the source, Luke). :) Or perhaps there is a Python
Elder here that knows?

Regards,
Björn

--
BOFH excuse #165:

Backbone Scoliosis

Nov 24 '07 #6
On Nov 24, 5:44 am, Licheng Fang <fanglich...@gm ail.comwrote:
Yes, millions. In my natural language processing tasks, I almost
always need to define patterns, identify their occurrences in a huge
data, and count them. [...] So I end up with unnecessary
duplicates of keys. And this can be a great waste of memory with huge
input data.
create a hash that maps your keys to themselves, then use the values
of that hash as your keys.
>>store = {}
def atom(str):
global store
if str not in store:
store[str] = str
return store[str]
>>a='this is confusing'
b='this is confusing'
a == b
True
>>a is b
False
>>atom(a) is atom(b)
True
Nov 24 '07 #7
On Sat, 24 Nov 2007 13:40:40 +0100, Bjoern Schliessmann wrote:
Licheng Fang wrote:
>On Nov 24, 7:05 pm, Bjoern Schliessmann <usenet-
>Wow, I didn't know this. But exactly how Python manage these
strings?

I don't know (use the source, Luke). :) Or perhaps there is a Python
Elder here that knows?
AFAIK strings of length 1 and strings that would be valid Python
identifiers are treated this way.

Ciao,
Marc 'BlackJack' Rintsch
Nov 24 '07 #8
On Nov 24, 9:42 pm, Marc 'BlackJack' Rintsch <bj_...@gmx.net wrote:
On Sat, 24 Nov 2007 13:40:40 +0100, Bjoern Schliessmann wrote:
Licheng Fang wrote:
On Nov 24, 7:05 pm, Bjoern Schliessmann <usenet-
Wow, I didn't know this. But exactly how Python manage these
strings?
I don't know (use the source, Luke). :) Or perhaps there is a Python
Elder here that knows?

AFAIK strings of length 1 and strings that would be valid Python
identifiers are treated this way.

Ciao,
Marc 'BlackJack' Rintsch
Thanks. Then, is there a way to make python treat all strings this
way, or any other kind of immutable objects?
Nov 24 '07 #9
Licheng Fang a écrit :
I mean, all the class instances that equal to each other should be
reduced into only one instance, which means for instances of this
class there's no difference between a is b and a==b.
Here's a Q&D attempt - without any garantee, and to be taylored to your
needs.

_values = {} #id(instance) =value mapping
_instances = {} #hash(value) =instance mapping

class Value(object):
def __new__(cls, value):
try:
return _instances[hash(value)]
except KeyError:
instance = object.__new__( cls)
_values[id(instance)] = value
_instances[hash(value)] = instance
return instance

@apply
def value():
def fget(self):
return _values[id(self)]
def fset(self, ignore):
raise AttributeError( "%s.value is read only" % type(self))
def fdel(self):
raise AttributeError( "%s.value is read only" % type(self))
return property(**loca ls())
HTH
Nov 24 '07 #10

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

Similar topics

46
2470
by: Leo Breebaart | last post by:
I've tried Googling for this, but practically all discussions on str.join() focus on the yuck-ugly-shouldn't-it-be-a-list-method? issue, which is not my problem/question at all. What I can't find an explanation for is why str.join() doesn't automatically call str() on its arguments, so that e.g. str.join() would yield "1245", and ditto for e.g. user-defined classes that have a __str__() defined. All I've been able to find is a 1999...
12
2737
by: Ron Garret | last post by:
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 >>>
2
2635
by: Neil Schemenauer | last post by:
python-dev@python.org.] The PEP has been rewritten based on a suggestion by Guido to change str() rather than adding a new built-in function. Based on my testing, I believe the idea is feasible. It would be helpful if people could test the patched Python with their own applications and report any incompatibilities. PEP: 349
7
8875
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and save it to the user's machine. I am using Adobe Acrobat (5.0 I think) and have Adobe Distiller as a
3
14966
by: Amjad | last post by:
Hi, I just wrote a test Windows Service that creates a text file on startup (please see my code below). The file is never created. Protected Overrides Sub OnStart(ByVal args() As String) Dim swLog As StreamWriter = File.CreateText("C:\myLog.txt") swLog.WriteLine("My Windows Service has just started.") swLog.Close() : swLog.Flush() End Sub
1
5691
by: peterggmss | last post by:
This is a slot machine game, 2 forms. One is the actual game (frmMachine) and the other is in the background and randomizes the images shown on frmMachine. I need to make frmMachine wait for frmRandom, i tried it with the Sleep API and a Do/Until Loop and neither worked, could you please help me, I have my code below. frmMachine 'Slot Machine, (c) 2006 Peter Browne, GPL Licensed ' 'Peter Browne 'Sheridan Corporate Centre '2155 Leanne...
0
820
by: Gabriel Genellina | last post by:
Hello Is this the intended behavior? Python 3.0a4+ (py3k, Apr 12 2008, 02:53:16) on win32 Type "help", "copyright", "credits" or "license" for more information. "b'abc'" 'abc' 'abc'
16
3036
by: Christian Heimes | last post by:
Gabriel Genellina schrieb: Yes, it's on purpose but it's a bug in your application to call str() on a bytes object or to compare bytes and unicode directly. Several months ago I added a bytes warning option to Python. Start Python as "python -bb" and try it again. ;) Christian
0
9699
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
9562
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
10538
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
10305
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
10063
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
5494
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
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3792
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2966
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.