473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Quesion about the proper use of __slots__

>>> class Fighter:
.... '''Small one man craft that can only harm other fighters on
their own.'''
.... def __init__(self,statsTuple=(50,5,0,(2,4),1)):
.... self.fuel = statsTuple[0]
.... self.life = statsTuple[1]
.... self.armor = statsTuple[2]
.... self.weapon = statsTuple[3]
.... self.bulk = statsTuple[4]
.... __slots__ =
[self.fuel,self.life,self.armor,self.weapon,self.bu lk]
....
ral = Fighter()
ral.rocks = 2
ral.rocks 2 ral.life

5

I was reading the special methods, got to slots
(http://docs.python.org/ref/slots.html) and decided that i should use
this to save memory in the program because it'll have to support very
large numbers of fighers at once. It says that once you define slots
then you can't add any variables not listed in slots, but from that
example section I just did, so am I doing something wrong or did I read
it wrong?

Feb 20 '06 #1
20 1160

Zefria wrote:
class Fighter: ... '''Small one man craft that can only harm other fighters on
their own.'''
... def __init__(self,statsTuple=(50,5,0,(2,4),1)):
... self.fuel = statsTuple[0]
... self.life = statsTuple[1]
... self.armor = statsTuple[2]
... self.weapon = statsTuple[3]
... self.bulk = statsTuple[4]
... __slots__ =
[self.fuel,self.life,self.armor,self.weapon,self.bu lk]
... ral = Fighter()
ral.rocks = 2
ral.rocks 2 ral.life

5

I was reading the special methods, got to slots
(http://docs.python.org/ref/slots.html) and decided that i should use
this to save memory in the program because it'll have to support very
large numbers of fighers at once. It says that once you define slots
then you can't add any variables not listed in slots, but from that
example section I just did, so am I doing something wrong or did I read
it wrong?


Seems that __slots__ in your case is nothing but a 'local variable' to
the function __init__. I think you need something like this :

class Test(object):
__slots__ = ['attr1','attr2']

Feb 20 '06 #2
Zefria wrote:
class Fighter:

Old-style classes are deprecated, use new-style class wherever possible:

class Fighter(object):
....
... '''Small one man craft that can only harm other fighters on
their own.'''
... def __init__(self,statsTuple=(50,5,0,(2,4),1)):
... self.fuel = statsTuple[0]
... self.life = statsTuple[1]
... self.armor = statsTuple[2]
... self.weapon = statsTuple[3]
... self.bulk = statsTuple[4]
... __slots__ =
[self.fuel,self.life,self.armor,self.weapon,self.bu lk]
...
(snip)

I was reading the special methods, got to slots
(http://docs.python.org/ref/slots.html) and decided that i should use
this to save memory in the program because it'll have to support very
large numbers of fighers at once.
"premature optimization is the root of all evil".
It says that once you define slots
then you can't add any variables not listed in slots, but from that
example section I just did, so am I doing something wrong or did I read
it wrong?


I think it's:

class Fighter(object):
__slots__ = ['fuel', 'life', 'armor', 'weapon', 'bulk',]
def __init__(self, ...):
# code here

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 20 '06 #3
>>> class Fighter(object):
.... '''Small one man craft that can only harm other fighters on
their own.'''
.... __slots__ = ["fuel","life","armor","weapon","bulk"]
.... def __init__(self,statsTuple=(50,5,0,(2,4),1)):
.... self.fuel = statsTuple[0]
.... self.life = statsTuple[1]
.... self.armor = statsTuple[2]
.... self.weapon = statsTuple[3]
.... self.bulk = statsTuple[4]
....
examp = Fighter()
examp.rock = 3 Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Fighter' object has no attribute 'rock'


Thank you both, I had tried making it a class variable and didn't see
anything. The trick must have been in making a class that inheriets
from object.

Also, I don't generally do any optimization at all yet (as a highschool
student projects get trashed often enough no to bother over), but in
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.

Additionally, this program's purpose was to experiment with as many of
the special methods as possible, so I suppose I'm on track so far.

Feb 20 '06 #4
Zefria wrote:
Also, I don't generally do any optimization at all yet (as a highschool
student projects get trashed often enough no to bother over), but in
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.


However, 'large numbers' are more likely to start (picture me looking out of
the window) at 100,000 than 10,000 in this context -- and you are at 750...

Peter

Feb 20 '06 #5

Peter Otten wrote:
Zefria wrote:
Also, I don't generally do any optimization at all yet (as a highschool
student projects get trashed often enough no to bother over), but in
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.


However, 'large numbers' are more likely to start (picture me looking out of
the window) at 100,000 than 10,000 in this context -- and you are at 750...

He could be working on a machine with < 1M RAM or some other
constraints.

Feb 20 '06 #6
In <11**********************@o13g2000cwo.googlegroups .com>, Zefria wrote:
Also, I don't generally do any optimization at all yet (as a highschool
student projects get trashed often enough no to bother over), but in
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.


That's 750 fighter objects. This is not a "large" amount of objects. So
I think it's premature optmization. Especially because you think of using
__slots__ without actually trying if the program uses too much memory.

Ciao,
Marc 'BlackJack' Rintsch
Feb 20 '06 #7
Well, my computer tends to run at about 497 to 501 out of 504 MB of RAM
used once I start up Gnome, XMMS, and a few Firefox tabs, and I'd
prefer not to see things slipping into Swap space if I can avoid it,
and the fighter data would be only part of a larger program.

And as I said, learning how to use __slots__ is important enough to
hazard a premature guess this time around. If I mess up, the worst that
happens is that I have to write down a new variable name in two places
instead of one now.

Feb 20 '06 #8

Zefria wrote:
Well, my computer tends to run at about 497 to 501 out of 504 MB of RAM
used once I start up Gnome, XMMS, and a few Firefox tabs, and I'd
prefer not to see things slipping into Swap space if I can avoid it,
and the fighter data would be only part of a larger program.

And as I said, learning how to use __slots__ is important enough to
hazard a premature guess this time around. If I mess up, the worst that
happens is that I have to write down a new variable name in two places
instead of one now.


For this particular setup, I don't think it would be a concern given
your mentioned size as you are very unlikely to be actively using all
the apps at the same time and linux is quite efficient in handling it.

However, I don't think attempting to use __slots__ in this case is bad
either. Afterall, one of the strength of python is allowing you to
quickly test out different approachs.

Feb 20 '06 #9
bo****@gmail.com wrote:

Zefria wrote:
Well, my computer tends to run at about 497 to 501 out of 504 MB of RAM
used once I start up Gnome, XMMS, and a few Firefox tabs, and I'd
prefer not to see things slipping into Swap space if I can avoid it,
and the fighter data would be only part of a larger program.

And as I said, learning how to use __slots__ is important enough to
hazard a premature guess this time around. If I mess up, the worst that
happens is that I have to write down a new variable name in two places
instead of one now.
For this particular setup, I don't think it would be a concern given
your mentioned size as you are very unlikely to be actively using all
the apps at the same time and linux is quite efficient in handling it.

However, I don't think attempting to use __slots__ in this case is bad
either. Afterall, one of the strength of python is allowing you to
quickly test out different approachs.


Yes, something like

import sys

class Fighter(object):
if "--use-slots" in sys.argv:
__slots__ = [...]
and then comparing

$ python fighters.py

with

$ python fighters.py --use-slots

might be instructive. I don't think the OP will perceive a difference.
He could be working on a machine with < 1M RAM or some other
constraints.


I have 256K, by the way.

Peter

Feb 20 '06 #10
On Mon, 20 Feb 2006 01:14:20 -0800, Zefria wrote:
class Fighter(object): ... '''Small one man craft that can only harm other fighters on
their own.'''
... __slots__ = ["fuel","life","armor","weapon","bulk"]
... def __init__(self,statsTuple=(50,5,0,(2,4),1)):
... self.fuel = statsTuple[0]
... self.life = statsTuple[1]
... self.armor = statsTuple[2]
... self.weapon = statsTuple[3]
... self.bulk = statsTuple[4]
... examp = Fighter()
examp.rock = 3 Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Fighter' object has no attribute 'rock'

Thank you both, I had tried making it a class variable and didn't see
anything. The trick must have been in making a class that inheriets
from object.


For technical reasons, __slots__ don't work as expected for old-style
classes, and never will. You have to inherit from object to make them work
correctly.

Also, I don't generally do any optimization at all yet (as a highschool
student projects get trashed often enough no to bother over), but in
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.


750 objects is not very many, not unless they are carrying around large
chunks of data. And even then, using __slots__ saves only a small
amount of memory per object.

Write your code the slot-less way, see how it performs, and if it is slow,
change your class definition.

--
Steven.

Feb 20 '06 #11

Peter Otten wrote:
He could be working on a machine with < 1M RAM or some other
constraints.


I have 256K, by the way.

Impressive, curious to know what kind of environment it is as it has
been a long time I have seen such limited spec. My first x86(IBM PC)
had more than that.

Feb 20 '06 #12
bo****@gmail.com wrote:

Peter Otten wrote:
> He could be working on a machine with < 1M RAM or some other
> constraints.


I have 256K, by the way.

Impressive, curious to know what kind of environment it is as it has
been a long time I have seen such limited spec. My first x86(IBM PC)
had more than that.


Touché
Feb 20 '06 #13
Zefria wrote:
Well, my computer tends to run at about 497 to 501 out of 504 MB of RAM
used once I start up Gnome, XMMS, and a few Firefox tabs, and I'd
prefer not to see things slipping into Swap space if I can avoid it,
and the fighter data would be only part of a larger program.

And as I said, learning how to use __slots__ is important enough to
hazard a premature guess this time around. If I mess up, the worst that
happens is that I have to write down a new variable name in two places
instead of one now.


Ok, but don't forget that using slots prevents you from attaching new
attributes on the fly on a given instance - which can be quite handy for
some use cases.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 20 '06 #14
bo****@gmail.com wrote:
Peter Otten wrote:
He could be working on a machine with < 1M RAM or some other
constraints.


I have 256K, by the way.


Impressive, curious to know what kind of environment it is as it has
been a long time I have seen such limited spec. My first x86(IBM PC)
had more than that.

Yeas, but that's because you are a kid who doesn't remember the
magnificent day when Digital equipment announced their first disk drive
for the PDP-8 series, with aa amazing 64 Kword (96 KB) capacity.

Sheesh, youngsters nowadays ... ;-)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Feb 20 '06 #15
Zefria <ze****@gmail.com> wrote:
...
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.
The problem with the spread of email is that it reduces the number of
envelopes laying around, and thus makes it harder to do "back of the
envelopes" calculations (the key skill in engineering...).

With 10 carriers between the two teams, and 150 fighters/carrier, you're
dealing with 1500 fighters. If you save 64 bytes per fighter (and I
don't think __slots__ will save quite that much), we're still talking
about less than 100,000 bytes -- peanuts. __slots__ is unwarranted.

Additionally, this program's purpose was to experiment with as many of
the special methods as possible, so I suppose I'm on track so far.


__slots__ is not a method, so it falls outside that purpose as stated.
Alex
Feb 20 '06 #16
<bo****@gmail.com> wrote:
Peter Otten wrote:
He could be working on a machine with < 1M RAM or some other
constraints.


I have 256K, by the way.

Impressive, curious to know what kind of environment it is as it has
been a long time I have seen such limited spec. My first x86(IBM PC)
had more than that.


I believe some cellphones and similarly limited devices may go as low as
256k, but I don't think anybody's running Python today on any device
with less than a MB (and more likely more).

The first PC _I_ owned had 4K of RAM (the cheaper model only had 1K, but
I splurged for the big one) -- Sinclair ZX80. But I didn't run Python
on it (indeed I soon swapped it for one with very similar HW but Forth
instead of Basic, called the "Jupiter Ace": Forth's force has always
been the ability to run with incredibly-little memory).
Alex
Feb 20 '06 #17
Dennis Lee Bieber wrote:
On Mon, 20 Feb 2006 12:44:49 +0100, Peter Otten <__*******@web.de>
declaimed the following in comp.lang.python:


I have 256K, by the way.

Ouch... I pray it is not running some variation of Windows... (My
TRS-80 Model III/4 [upgraded motherboard, same case] had 128K of RAM is
a 32K fixed, and three 32K bank-swapped segment -- in 1982). And I had
512K in my Amiga A-1000.

W98SE was just usable on 256M (of highly expensive RDRAM at the time
-- going from 128M to 256M was $800). On a cold boot I'd have 135K free
(and that was with the vcache limited!)... A little PhotoShop work would
suck up the rest easily. And then... the 64K GDI space would get
trashed...


OK, you all had your laugh now, move on.

Peter, who can't count to 2**you-name-it
Feb 20 '06 #18
Alex Martelli wrote:
Zefria <ze****@gmail.com> wrote:
...
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.


The problem with the spread of email is that it reduces the number of
envelopes laying around, and thus makes it harder to do "back of the
envelopes" calculations (the key skill in engineering...).


Actually, a properly performed "engineering approximation" is done
entirely in one's head, preferably without resorting to calculation at
all.

The "back of the envelope" ploy is reserved for cases where one is
trying to impress a waitress (which effort is inevitably doomed to fail
of course), or to make it easier to submit the dinner receipt as a
business expense...

;-)
-Peter

Feb 20 '06 #19
Peter Hansen <pe***@engcorp.com> wrote:
Alex Martelli wrote:
Zefria <ze****@gmail.com> wrote:
...
this special case I'm expecting each "carrier" to have up to 150
fighters, and 3 to 5 carriers for each of the two teams, which comes
out to be quite large.
The problem with the spread of email is that it reduces the number of
envelopes laying around, and thus makes it harder to do "back of the
envelopes" calculations (the key skill in engineering...).


Actually, a properly performed "engineering approximation" is done
entirely in one's head, preferably without resorting to calculation at
all.


Of course, but you still need an envelope on whose back to scribble.
Tradition and historical continuity demand it.
The "back of the envelope" ploy is reserved for cases where one is
trying to impress a waitress (which effort is inevitably doomed to fail
of course), or to make it easier to submit the dinner receipt as a
business expense...


That's "back of the restaurant bill", a different though related
technique. Since most restaurants don't print bills on envelopes, the
two are not really comparable.
Alex
Feb 20 '06 #20
I am aware of this; but with too much Java still running through my
brain I've never bothered with the idea yet because that's simply not
the way I learned and I've never had a chance to need new attributes
for singular instances.

"__slots__ is not a method, so it falls outside that purpose as stated.
" -Alex Martelli

It's listed within the special methods section of the Python Refrence,
was what I ment.

Feb 20 '06 #21

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

Similar topics

1
by: anabell | last post by:
I have a code like this: sqlString = 'INSERT INTO ' + self.TableName + ' VALUES (' + self.TableFields + ')' self.cursor.execute(sqlString, self.__dict__) This works correctly. However, I'm...
9
by: flori | last post by:
i try to greate somthing like this class ca(object): __slots__ = ("a",) class cb(ca): __slots__ = ("a","b") class cc(ca): __slots__ = ("a","c") class cd(cb,cc): __slots__ = ("a","b","c","d") ...
5
by: Jean Brouwers | last post by:
Classes using __slots__ seem to be quite a bit smaller and faster to instantiate than regular Python classes using __dict__. Below are the results for the __slots__ and __dict__ version of a...
3
by: Nick Jacobson | last post by:
The __slots__ attribute of new-style classes can reduce memory usage when there are millions of instantiations of a class. So would a __slots__ attribute for functions/methods have a similar...
7
by: Porky Pig Jr | last post by:
Hello, I"m still learning Python, but going through the Ch 5 OOP of Nutshell book. There is discussion on __slots__, and my understanding from reading this section is that if I have a class...
2
by: Ewald R. de Wit | last post by:
I'm running into a something unexpected for a new-style class that has both a class attribute and __slots__ defined. If the name of the class attribute also exists in __slots__, Python throws an...
3
by: Schüle Daniel | last post by:
Hello, consider this code >>> class A(object): .... def __init__(self): .... self.a = 1 .... self.b = 2 .... >>> class B(A):
1
by: pascal.parent | last post by:
Hi, I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes, - return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute...
27
by: Licheng Fang | last post by:
Python is supposed to be readable, but after programming in Python for a while I find my Python programs can be more obfuscated than their C/C ++ counterparts sometimes. Part of the reason is that...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...

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.