473,385 Members | 1,736 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,385 software developers and data experts.

Problem of Readability of Python

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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...

Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Any elegant solutions?

Oct 7 '07 #1
27 1691
Licheng Fang wrote:
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...

Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Any elegant solutions?
You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects that
need such performance tweaks should start like::

class A(object):
__slots__ = 'name', 'val'

The recipe below fills in the obvious __init__ method for such classes
so that the above is pretty much all you need to write:

http://aspn.activestate.com/ASPN/Coo.../Recipe/502237
STeVe
Oct 7 '07 #2
Licheng Fang a écrit :
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...
Use dicts, not lists or tuples:

a = dict(name='yadda', val=42)
print a['name']
print a['val']
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?
If you do worry about overhead, then C is your friend !-)

More seriously: what do you use this 'nameval' struct for ? If you
really have an overhead problem, you may want to use a real class using
__slots__ to minimize this problem, but chances are you don't need it.

Oct 7 '07 #3
Licheng Fang wrote:
struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...
?!

(1)
a = {}
a["name"] = ...
a["val"] = ...

(2)
NAME = 0
VAL = 1
a=[]
a[NAME] = ...
a[VAL] = ...
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much
overhead if one defines empty classes as such for some very
frequently used data structures of the program?
Measure first, optimize later. How many million of instances and/or
accesses per second do you have?

Regards,
Björn

--
BOFH excuse #20:

divide-by-zero error

Oct 7 '07 #4
On Oct 7, 2:14 pm, Steven Bethard <steven.beth...@gmail.comwrote:
Licheng Fang wrote:
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be
struct nameval {
char * name;
int val;
} a;
a.name = ...
a.val = ...
becomes cryptic
a[0] = ...
a[1] = ...
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?
Any elegant solutions?

You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects that
need such performance tweaks should start like::

class A(object):
__slots__ = 'name', 'val'

The recipe below fills in the obvious __init__ method for such classes
so that the above is pretty much all you need to write:

http://aspn.activestate.com/ASPN/Coo.../Recipe/502237

STeVe
For immutable records, you may also want to check out the named tuples
recipe: http://aspn.activestate.com/ASPN/Coo.../Recipe/500261

George

Oct 7 '07 #5
George Sakkis wrote:
On Oct 7, 2:14 pm, Steven Bethard <steven.beth...@gmail.comwrote:
>Licheng Fang wrote:
>>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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be
struct nameval {
char * name;
int val;
} a;
a.name = ...
a.val = ...
becomes cryptic
a[0] = ...
a[1] = ...
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?
Any elegant solutions?
You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects that
need such performance tweaks should start like::

class A(object):
__slots__ = 'name', 'val'

The recipe below fills in the obvious __init__ method for such classes
so that the above is pretty much all you need to write:

http://aspn.activestate.com/ASPN/Coo.../Recipe/502237

For immutable records, you may also want to check out the named tuples
recipe: http://aspn.activestate.com/ASPN/Coo.../Recipe/500261
Yep, it's linked in the description of the first recipe.

STeVe
Oct 7 '07 #6
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
writes:
Use dicts, not lists or tuples:

a = dict(name='yadda', val=42)
print a['name']
print a['val']
I guess you will then need a list or tuple to store the dicts?

I might have made it with a list of class instances:

class a:
def __init__(self,name,val):
self.name=name
self.val=val

l=list()
l.append(a('yadda',42))
print l[0].name
print l[0].val

Is the dict preferable to a list or tuple of class instances?
--
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
Oct 7 '07 #7
Licheng Fang <fa*********@gmail.comwrote:
...
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?
Just measure:

$ python -mtimeit -s'class A(object):pass' -s'a=A()' 'a.zop=23'
1000000 loops, best of 3: 0.241 usec per loop

$ python -mtimeit -s'a=[None]' 'a[0]=23'
10000000 loops, best of 3: 0.156 usec per loop

So, the difference, on my 18-months-old laptop, is about 85 nanoseconds
per write-access; if you have a million such accesses in a typical run
of your program, it will slow the program down by about 85 milliseconds.
Is that "much overhead"? If your program does nothing else except those
accesses, maybe, but then why are your writing that program AT ALL?-)

And yes, you CAN save about 1/3 of those 85 nanoseconds by having
'__slots__=["zop"]' in your class A(object)... but that's the kind of
thing one normally does only to tiny parts of one's program that have
been identified by profiling as dramatic bottlenecks, to shave off the
last few nanoseconds in the very last stages of micro-optimization of a
program that's ALMOST, but not QUITE, fast enough... knowing about such
"extreme last-ditch optimization tricks" is of very doubtful value (and
I think I'm qualified to say that, since I _do_ know many of them...:-).
There ARE important performance things to know about Python, but those
worth a few nanoseconds don't matter much.
Alex
Oct 7 '07 #8
On Oct 7, 1:07 pm, Licheng Fang <fanglich...@gmail.comwrote:
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;

} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...

Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Any elegant solutions?
"""Just use a single empty class (such as the AttributeContainer
below)
and then use different instances of the class for different sets
of name/value pairs. (This type of class also goes by the name
Bag,
but that name is too, um, nondescript for me.) You can see from
the
example that there is no requirement for names to be shared,
unshared,
common, or unique.

-- Paul"""

class AttributeContainer(object):
pass

a = AttributeContainer()
a.name = "Lancelot"
a.favorite_color = "blue"

b = AttributeContainer()
b.name = "European swallow"
b.laden = true
b.airspeed = 20

Oct 7 '07 #9
Licheng Fang wrote:
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs.
Comments might help.

It's common to use tuples that way, but slightly bad form to
use lists that way.

Of course, you can create a class and use "slots" to bind
the positions at compile time, so you don't pay for a dictionary
lookup on every feature.

(Someday I need to overhaul BeautifulSoup to use "slots".
That might speed it up.)

John Nagle
Oct 7 '07 #10
On 8/10/2007 4:14 AM, Steven Bethard wrote:
Licheng Fang wrote:
>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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...

Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Any elegant solutions?

You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects that
need such performance tweaks should start like::

class A(object):
__slots__ = 'name', 'val'

The recipe below fills in the obvious __init__ method for such classes
so that the above is pretty much all you need to write:

http://aspn.activestate.com/ASPN/Coo.../Recipe/502237

If not needing/wanting __slots__, something simpler (no metaclasses!)
like the following helps the legibility/utility:

<file record.py>

class BaseRecord(object):

def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)

def dump(self, text=''):
print '== dumping %s instance: %s' % (self.__class__.__name__,
text)
for k, v in sorted(self.__dict__.iteritems()):
print ' %s: %r' % (k, v)
</file record.py>
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>from record import BaseRecord
class A(BaseRecord):
.... pass
....
>>class B(BaseRecord):
.... pass
....
>>a1 = A(foo=1, bar='rab', zot=(1, 2))
a2 = A(foo=2, bar='xxx', zot=(42, 666))
a1.dump()
== dumping A instance:
bar: 'rab'
foo: 1
zot: (1, 2)
>>a2.dump('more of the same')
== dumping A instance: more of the same
bar: 'xxx'
foo: 2
zot: (42, 666)
>>a1.ugh = 'poked in'
a1.dump('after poking')
== dumping A instance: after poking
bar: 'rab'
foo: 1
ugh: 'poked in'
zot: (1, 2)
>>b1 = B()
b1.dump()
== dumping B instance:
>>b1.esrever = 'esrever'[::-1]
b1.dump()
== dumping B instance:
esrever: 'reverse'
>>>
HTH,
John
Oct 7 '07 #11
In article <2t******************************@comcast.com>,
Steven Bethard <st************@gmail.comwrote:
>
You can use __slots__ [...]
Aaaugh! Don't use __slots__!

Seriously, __slots__ are for wizards writing applications with huuuge
numbers of object instances (like, millions of instances). For an
extended thread about this, see

http://groups.google.com/group/comp....25f368e23ab058
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.
Oct 8 '07 #12
On Oct 8, 12:27 am, a...@pythoncraft.com (Aahz) wrote:
>
Aaaugh! Don't use __slots__!
+1 QOTW ;)

Michele Simionato

Oct 8 '07 #13
On Oct 7, 7:58 pm, al...@mac.com (Alex Martelli) wrote:
If you REALLY pine for Pascal's records, you might choose to inherit
from ctypes.Structure, which has the additional "advantages" of
specifying a C type for each field and (a real advantage;-) creating an
appropriate __init__ method.
>import ctypes
class Record(ctypes.Structure):

... _fields_ =
(('x',ctypes.c_float),('y',ctypes.c_float),('z',ct ypes.c_float)
)
...>>r=Record()
>r.x
0.0
>r=Record(1,2,3)
r.x
1.0
>r=Record('zip','zop','zap')

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float expected instead of str instance

See? You get type-checking too -- Pascal looms closer and closer!-)

And if you need an array of 1000 such Records, just use as the type
Record*1000 -- think of the savings in memory (no indirectness, no
overallocations as lists may have...).
That's very cool Alex! I have just a question: suppose I want
to measure the memory allocation of a million of records made
with ctypes vs the memory allocation of equivalent
records made with __slots__, how do I measure it? Say on Linux,
Mac and Windows?
If ctypes records are more efficient than __slots__ records,
I will ask for deprecation of __slots__ (which is something
I wanted from the beginning!).
Michele Simionato

Oct 8 '07 #14
Brian Elmegaard a écrit :
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
writes:
>Use dicts, not lists or tuples:

a = dict(name='yadda', val=42)
print a['name']
print a['val']

I guess you will then need a list or tuple to store the dicts?
Should be a list then IMHO. But then it's the correct use of a list : an
homegenous collection.

Oct 8 '07 #15
On Sun, 07 Oct 2007 21:27:31 -0700, Aahz wrote:
In article <2t******************************@comcast.com>, Steven
Bethard <st************@gmail.comwrote:
>>
You can use __slots__ [...]

Aaaugh! Don't use __slots__!

Seriously, __slots__ are for wizards writing applications with huuuge
numbers of object instances (like, millions of instances). For an
extended thread about this, see

http://groups.google.com/group/comp....browse_thread/
thread/8775c70565fb4a65/0e25f368e23ab058

Well, I've read the thread, and I've read the thread it links to, and for
the life of me I'm still no clearer as to why __slots__ shouldn't be used
except that:

1 Aahz and Guido say __slots__ are teh suxxor;

2 rumour (?) has it that __slots__ won't make it into Python 3.0;

3 inheritance from classes using __slots__ doesn't inherit the slot-
nature of the superclass.
Point 1 is never to be lightly dismissed, but on the other hand Guido
doesn't like reduce(), and I'm allergic to "Cos I Said So" arguments.

History is full of things which were invented for one purpose being used
for something else. So, that being the case, suppose I accept that using
__slots__ is not the best way of solving the problem, and that people of
the skill and experience of Guido and Aahz will roll their eyes and
snicker at me.

But is there actually anything *harmful* that can happen if I use
__slots__?

--
Steven.
Oct 8 '07 #16
Aahz wrote:
In article <2t******************************@comcast.com>,
Steven Bethard <st************@gmail.comwrote:
>You can use __slots__ [...]

Aaaugh! Don't use __slots__!

Seriously, __slots__ are for wizards writing applications with huuuge
numbers of object instances (like, millions of instances).
You clipped me saying that __slots__ are for performance tweaks:

You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects
that need such performance tweaks should start like...

I fully agree that __slots__ are for applications with huge numbers of
instances. But if you have that situation, you really do want to be
using __slots__.

STeVe
Oct 8 '07 #17
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrites:
Well, I've read the thread, and I've read the thread it links to,
and for the life of me I'm still no clearer as to why __slots__
shouldn't be used except that:
[...]
But is there actually anything *harmful* that can happen if I use
__slots__?
Here is one harmful consequence: __slots__ breaks multiple
inheritance:

class A(object):
__slots__ = ['a', 'b']

class B(object):
__slots__ = ['c']

class AB(A, B):
pass

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict

Even if A and B had the exact same slots, for example ['a', 'b'], it
wouldn't make a difference. AB explicitly setting __slots__ to
something like ['a', 'b', 'c'] doesn't help either. But that is only
a technical answer to your technical question which misses the real
problem people like Aahz and Guido have with __slots__. (I don't
claim to represent them, of course, the following is my
interpretation.)

The backlash against __slots__ is a consequence of it being so easy to
misunderstand what __slots__ does and why it exists. Seeing __slots__
has led some people to recommend __slots__ to beginners as a way to
"catch spelling mistakes", or as a way to turn Python's classes into
member-declared structures, a la Java. For people coming from Java
background, catching mistakes as early as possible is almost a dogma,
and they are prone to accept the use of __slots__ (and living with the
shortcomings) as a rule.

Python power users scoff at that because it goes against everything
that makes Python Python. Use of __slots__ greatly reduces class
flexibility, by both disabling __dict__ and __weakref__ by default,
and by forcing a tight instance layout that cripples inheritance.
With people using __slots__ for the majority of their classes, it
becomes much harder for 3rd-party code to attach an unforeseen
attribute to an existing object. Even with single inheritance,
__slots__ has unintuitive semantics because subclasses automatically
get __dict__ and __weakref__, thereby easily breaking the "benefits"
of their use.

__slots__ is a low-level tool that allows creation of dict-less
objects without resorting to Python/C. As long as one understands it
as such, there is no problem with using it.
Oct 8 '07 #18
On Oct 8, 4:24 am, al...@mac.com (Alex Martelli) wrote:
Licheng Fang <fanglich...@gmail.comwrote:

...
Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Just measure:

$ python -mtimeit -s'class A(object):pass' -s'a=A()' 'a.zop=23'
1000000 loops, best of 3: 0.241 usec per loop

$ python -mtimeit -s'a=[None]' 'a[0]=23'
10000000 loops, best of 3: 0.156 usec per loop

So, the difference, on my 18-months-old laptop, is about 85 nanoseconds
per write-access; if you have a million such accesses in a typical run
of your program, it will slow the program down by about 85 milliseconds.
Is that "much overhead"? If your program does nothing else except those
accesses, maybe, but then why are your writing that program AT ALL?-)

And yes, you CAN save about 1/3 of those 85 nanoseconds by having
'__slots__=["zop"]' in your class A(object)... but that's the kind of
thing one normally does only to tiny parts of one's program that have
been identified by profiling as dramatic bottlenecks, to shave off the
last few nanoseconds in the very last stages of micro-optimization of a
program that's ALMOST, but not QUITE, fast enough... knowing about such
"extreme last-ditch optimization tricks" is of very doubtful value (and
I think I'm qualified to say that, since I _do_ know many of them...:-).
There ARE important performance things to know about Python, but those
worth a few nanoseconds don't matter much.

Alex
This is enlightening. Surely I shouldn't have worried too much about
performance before doing some measurement.

Oct 10 '07 #19
Am I missing something, or am I the only one who explicitly declares
structs in python?

For example:
FileObject = {
"filename" : None,
"path" : None,
}

fobj = FileObject.copy()
fobj["filename"] = "passwd"
fobj["path"] = "/etc/"

Kevin Kelley

On 10/7/07, Licheng Fang <fa*********@gmail.comwrote:
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 with
heterogeneous lists/tuples at hand, I tend to stuff many things into
the list and *assume* a structure of the list or tuple, instead of
declaring them explicitly as one will do with C structs. So, what used
to be

struct nameval {
char * name;
int val;
} a;

a.name = ...
a.val = ...

becomes cryptic

a[0] = ...
a[1] = ...

Python Tutorial says an empty class can be used to do this. But if
namespaces are implemented as dicts, wouldn't it incur much overhead
if one defines empty classes as such for some very frequently used
data structures of the program?

Any elegant solutions?

--
http://mail.python.org/mailman/listinfo/python-list

--
Kevin Kelley
http://technogeek.org/
Oct 10 '07 #20
Kevin wrote:
Am I missing something, or am I the only one who explicitly declares
structs in python?

For example:
FileObject = {
"filename" : None,
"path" : None,
}

fobj = FileObject.copy()
fobj["filename"] = "passwd"
fobj["path"] = "/etc/"
Yes, I think this is the only time I've ever seen that. I think the
normal way of doing this in Python is:

class FileObject(object):
def __init__(self, filename, path):
self.filename = filename
self.path = path

fobj = FileObject(filename='passwd', path='etc')

STeVe
Oct 10 '07 #21
On 10/10/07, Kevin <wy******@gmail.comwrote:
Am I missing something, or am I the only one who explicitly declares
structs in python?
For example:
FileObject = {
"filename" : None,
"path" : None,
}

fobj = FileObject.copy()
fobj["filename"] = "passwd"
fobj["path"] = "/etc/"

I am pretty new to python, but isn't that just a dictionary?
Oct 10 '07 #22
Kevin wrote:
Am I missing something, or am I the only one who explicitly
declares structs in python?
Yes -- you missed my posting :)

Regards,
Björn

--
BOFH excuse #209:

Only people with names beginning with 'A' are getting mail this week
(a la Microsoft)

Oct 10 '07 #23
Bjoern Schliessmann wrote:
Kevin wrote:
>Am I missing something, or am I the only one who explicitly
declares structs in python?

Yes -- you missed my posting :)
Actually, your posting just used dicts normally.

Kevin is creating a prototype dict with a certain set of keys, and then
copying that dict and filling in the keys each time he creates a new
instance. It's basically a poor man's OOP.

STeVe
Oct 10 '07 #24
Steven Bethard wrote:
Actually, your posting just used dicts normally.

Kevin is creating a prototype dict with a certain set of keys, and
then copying that dict and filling in the keys each time he
creates a new instance. It's basically a poor man's OOP.
And operatively, IMHO, there is no difference.

Regards,
Björn

--
BOFH excuse #176:

vapors from evaporating sticky-note adhesives

Oct 11 '07 #25
In article <oc******************************@comcast.com>,
Steven Bethard <st************@gmail.comwrote:
>Aahz wrote:
>In article <2t******************************@comcast.com>,
Steven Bethard <st************@gmail.comwrote:
>>>
You can use __slots__ [...]

Aaaugh! Don't use __slots__!

Seriously, __slots__ are for wizards writing applications with huuuge
numbers of object instances (like, millions of instances).

You clipped me saying that __slots__ are for performance tweaks:

You can use __slots__ to make objects consume less memory and have
slightly better attribute-access performance. Classes for objects
that need such performance tweaks should start like...

I fully agree that __slots__ are for applications with huge numbers of
instances. But if you have that situation, you really do want to be
using __slots__.
Well, then, just make sure to put big honking warnings up whenever you
mention __slots__. ;-)
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.
Oct 15 '07 #26
On Oct 17, 9:11 pm, "Chris Mellon" <ar*****@gmail.comwrote:
On 10/17/07, ki******@gmail.com <ki******@gmail.comwrote:
>>o = object()
>>o.foo = 7

What makes you think it can't be instantiated directly? You just did
it. It's not, however, suitable for use as an arbitrary thing to stick
attributes on.

Which is a little sad, but a necessary requirement for things like
int() and str() to be small and fast.
So it's an optimization with side effects, giving a special case where
the simple and otherwise "right" way to do it doesn't work? Too bad :-
(

Ok; I'll continue to create dummy classes inheriting from object. And
hope that one day it will be simpler.

Thanks,
Mads

Oct 17 '07 #27
On Wed, 17 Oct 2007 15:01:09 -0700, kiilerix wrote:
On Oct 17, 9:11 pm, "Chris Mellon" <ar*****@gmail.comwrote:
>On 10/17/07, ki******@gmail.com <ki******@gmail.comwrote:
>>o = object()
o.foo = 7

What makes you think it can't be instantiated directly? You just did
it. It's not, however, suitable for use as an arbitrary thing to stick
attributes on.

Which is a little sad, but a necessary requirement for things like
int() and str() to be small and fast.

So it's an optimization with side effects, giving a special case where
the simple and otherwise "right" way to do it doesn't work? Too bad :-
(

Ok; I'll continue to create dummy classes inheriting from object. And
hope that one day it will be simpler.
I'm using the following "dummy" class with a little extra functionality:

def Bunch(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

person = Bunch(name='Eric', age=42)
print person.name
point = Bunch(x=4711, y=23)

Ciao,
Marc 'BlackJack' Rintsch
Oct 18 '07 #28

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

Similar topics

68
by: Marco Bubke | last post by:
Hi I have read some mail on the dev mailing list about PEP 318 and find the new Syntax really ugly. def foo(x, y): pass I call this foo(1, 2), this isn't really intuitive to me! Also I...
3
by: David Stockwell | last post by:
Hi, I was looking through some of our source code and I found this: initModule( "$Revision: 3.1 $".split(" ") ) In this example, it looks like only the '3.1' is actually passed to the...
49
by: Mark Hahn | last post by:
As we are addressing the "warts" in Python to be fixed in Prothon, we have come upon the mutable default parameter problem. For those unfamiliar with the problem, it can be seen in this Prothon...
2
by: Bill Sneddon | last post by:
Can any one tell me how to output the following string? <%response.write "<tr><td><a href=""file://SERVER/mmlogs/TNAME" & yearmonth & """>"& "MYJUNK" & "</a><BR></td></tr>" %> ...
3
by: H J van Rooyen | last post by:
Hi, Still struggling with my GUI exercise - I have the following lines of code in a routine that is bound at <Key-Returnto an instance of Entry : self.disp.Amount_des = Label(self.disp,...
6
by: Dasn | last post by:
Hi, there. 'lines' is a large list of strings each of which is seperated by '\t' I wanna split each string into a list. For speed, using map() instead of 'for' loop. 'map(str.split, lines)'...
16
by: DE | last post by:
Hello, Here is what I do in C++ and can not right now in python : pushMatrix() { drawStuff(); pushMatrix(); {
2
by: Nathan Harmston | last post by:
Hi, I know this isnt the pyparsing list, but it doesnt seem like there is one. I m trying to use pyparsing to parse a file however I cant get the Optional keyword to work. My file generally...
11
by: Louis.Soninhu | last post by:
Hi pals I have a list like this mylist= I'd like to remove the first and the last item as they are irrevalent, and convert it to the dict: {'tom':'boss','mike':'manager','paul':'employee'}
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
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
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.