Re: Cool object trick

2004-12-18 Thread Carl Banks
Bengt Richter wrote:
> m=type('',(),{})()

Nick Coghlan wrote:
> Heh.
>
> Look ma, Perlython!

I doubt anyone could perform such a ghastly hack so simply and
straightforwardly in Perl.


-- 
CARL BANKS

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


Re: Cool object trick

2004-12-18 Thread Nick Coghlan
Robert Brewer wrote:
Bengt Richter wrote:
>>> m=type('',(),{})()
>>> m.title = 'not so fast ;-)'
>>> m.title
'not so fast ;-)'

Now THAT is a cool object trick. :)
Heh.
Look ma, Perlython!
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


RE: Cool object trick

2004-12-18 Thread Robert Brewer
Bengt Richter wrote:
>  >>> m=type('',(),{})()
>  >>> m.title = 'not so fast ;-)'
>  >>> m.title
>  'not so fast ;-)'

Now THAT is a cool object trick. :)


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


Re: Cool object trick

2004-12-18 Thread Fredrik Lundh
Bengt Richter wrote:

> >>> m = object()
> >>> m.title = 'not so fast ;-)'
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'object' object has no attribute 'title'

>>> m = object()
>>> m.title = 'yeah, that's stupid'
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'object' object has no attribute 'title'

>>> class m: pass
>>> m.title = 'this works better'

>>> class result: pass
>>> m = result()
>>> m.title = 'this also works, and is a bit less obscure'

 



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


Re: Cool object trick

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 08:39:47 +0100, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

>Carl Banks wrote:
>
>> For example:
>>
>> .def lookup_reference(key):
>> .
>> .return Bunch(title=title,author=author,...)
>>
>> The code quickly and easily returns a object with the desired keys.
>> The code that calls this function would access the return values
>> directly, like this:
>>
>> .m = lookupreference()
>> .print "%s was written by %s" % (m.title,m.author)
>>
>> You could still use a dict for this, but a Bunch class neater and more
>> concise (not to mention less typing).
>
>this is how your example looks in Python:
>
>def lookup_reference(key):
>...
>return dict(title=title, author=author, ...)
>
>m = lookup_reference(...)
>print "%(title)s was written by %(author)s" % m
>
>(if you fix the bug in your example, and count the characters, you'll find
>that my example is a bit shorter)
>
>with enough keys, you can also save typing by using dummy object instead
>of a dictionary, and getting rid of the locals in lookup_reference:
>
>def lookup_reference(key):
>m = object()
>m.title = ... assign directly to return struct members ...
>m.author = ...
>return m
>
>m = lookup_reference(...)
>print "%(title)s was written by %(author)s" % vars(m)
>
 >>> m = object()
 >>> m.title = 'not so fast ;-)'
 Traceback (most recent call last):
   File "", line 1, in ?
 AttributeError: 'object' object has no attribute 'title'
 >>> m=type('',(),{})()
 >>> m.title = 'not so fast ;-)'
 >>> m.title
 'not so fast ;-)'

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread Fredrik Lundh
Carl Banks wrote:

> For example:
>
> .def lookup_reference(key):
> .
> .return Bunch(title=title,author=author,...)
>
> The code quickly and easily returns a object with the desired keys.
> The code that calls this function would access the return values
> directly, like this:
>
> .m = lookupreference()
> .print "%s was written by %s" % (m.title,m.author)
>
> You could still use a dict for this, but a Bunch class neater and more
> concise (not to mention less typing).

this is how your example looks in Python:

def lookup_reference(key):
...
return dict(title=title, author=author, ...)

m = lookup_reference(...)
print "%(title)s was written by %(author)s" % m

(if you fix the bug in your example, and count the characters, you'll find
that my example is a bit shorter)

with enough keys, you can also save typing by using dummy object instead
of a dictionary, and getting rid of the locals in lookup_reference:

def lookup_reference(key):
m = object()
m.title = ... assign directly to return struct members ...
m.author = ...
return m

m = lookup_reference(...)
print "%(title)s was written by %(author)s" % vars(m)

 



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


Re: Cool object trick

2004-12-17 Thread Carl Banks
Alex Stapleton wrote:
> Hmm true, (i had forgotten about getattr :/) in that case im
indifferent
> to Bunch() not that i really see why it's useful except for making
code
> look a bit nicer occasionaly.

When using Bunch, the idea is not to access the elements indirectly.
If you need to access elements indirectly, you ought to be using a dict
(of course).  But sometimes (perhaps often) it's useful to bundle a
bunch of variables together, to be accessed directly.

Say, for example, you are writing a function that returns a variety of
unrelated information (unrelated in that it doesn't make sense to
perform operations on them).  One thing you could do is return a tuple,
but that could be unwieldy if you have too many items.  Instead, you
could return a Bunch.  For example:

.def lookup_reference(key):
.
.return Bunch(title=title,author=author,...)

The code quickly and easily returns a object with the desired keys.
The code that calls this function would access the return values
directly, like this:

.m = lookupreference()
.print "%s was written by %s" % (m.title,m.author)

You could still use a dict for this, but a Bunch class neater and more
concise (not to mention less typing).


-- 
CARL BANKS

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


Re: Cool object trick

2004-12-17 Thread Steven Bethard
Robert Brewer wrote:
Alex Stapleton wrote:
you can't do
var = "varA"
obj = struct(varA = "Hello")
print obj.var
and expect it to say Hello to you.
Did you mean "print obj.varA"?
I believe he meant that he wanted the equivalent of:
getattr(obj, var)
Steve
--
http://mail.python.org/mailman/listinfo/python-list


RE: Cool object trick

2004-12-17 Thread Robert Brewer
Alex Stapleton wrote:
> you can't do
>
> var = "varA"
> obj = struct(varA = "Hello")
> print obj.var
>
> and expect it to say Hello to you.

Did you mean "print obj.varA"? I can't think of any use case for the way
you wrote it, so I'm naively guessing you've got a typo. Feel free to
correct me. ;)

>>> class struct(object):
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
... 
>>> var = "varA"
>>> obj = struct(**{str(var): "Hello"})
>>> print obj.varA
Hello


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread has
Jive wrote:

> # Is that really much different from this?

Functionally, no. However it can help make code more readable when
dealing with complex data structures, e.g. compare:

obj.spam[1].eggs[3].ham

to:

obj["spam"][1]["eggs"][3]["ham"]

I've used it a couple times for this particular reason and it
definitely has its niche; though I'm not sure it's sufficiently common
or useful to justify its inclusion it in the standard library, and it's
trivial to whip up as-and-when it's needed.

BTW & FWIW, I think the usual name for this kind of structure is
'record' (or 'struct' in C).

HTH

has

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


Re: Cool object trick

2004-12-17 Thread Steve Holden
Fredrik Lundh wrote:
Steve Holden wrote:

Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
obj.sausages, "and", obj.spam' a lot easier ;-)
Of course this whole thing of substituting attribute access for dictionary keys only works as long 
as the keys are strings with the same syntax as Python identifiers, so one shouldn't go completely 
overboard.

unless you're willing to use getattr() for thos oddball cases, of course.
Of course.
>>> class Dummy:
... pass
...
>>> x = Dummy()
>>> setattr(x, "spam&egg", "hello")
>>> getattr(x, "spam&egg")
'hello'
>>> x.spam&egg
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: Dummy instance has no attribute 'spam'
but seriously, turning container elements into attributes should only be done
if it makes sense from a design perspective.  (and vice versa; you shouldn't
use a dictionary if an object would make more sense -- but attribute abuse
is a lot more common)
Really we are talking about the outer limits here. Anyone preferring
setattr(x, "spam&egg", "hello")
to
x["spam&egg"] = "hello"
when it isn't necessary clearly doesn't share our two principal 
attributes: an elegant sense of design, fine knowledge of Python and an 
   inherent modesty.

Sorry: out *three* principal attributes. Bugger, I'll come in again.
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread Fredrik Lundh
Steve Holden wrote:

>> Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
>> obj.sausages, "and", obj.spam' a lot easier ;-)
>>
> Of course this whole thing of substituting attribute access for dictionary 
> keys only works as long 
> as the keys are strings with the same syntax as Python identifiers, so one 
> shouldn't go completely 
> overboard.

unless you're willing to use getattr() for thos oddball cases, of course.

>>> class Dummy:
... pass
...
>>> x = Dummy()
>>> setattr(x, "spam&egg", "hello")
>>> getattr(x, "spam&egg")
'hello'
>>> x.spam&egg
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: Dummy instance has no attribute 'spam'

but seriously, turning container elements into attributes should only be done
if it makes sense from a design perspective.  (and vice versa; you shouldn't
use a dictionary if an object would make more sense -- but attribute abuse
is a lot more common)

 



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


Re: Cool object trick

2004-12-17 Thread Steve Holden
[EMAIL PROTECTED] wrote:
I rather like it!  I prefer writing obj.spam to obj["spam"]!  I wonder if
there is a technical downside to this use of Python?
P.S.
Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
obj.sausages, "and", obj.spam' a lot easier ;-)
Of course this whole thing of substituting attribute access for 
dictionary keys only works as long as the keys are strings with the same 
syntax as Python identifiers, so one shouldn't go completely overboard. 
"To the man with a hammer everything looks like a nail", and so on.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread Alex Stapleton
Steven Bethard wrote:
Alex Stapleton wrote:
you are setting the variable name in your code (b.varA), not 
generating the variable name in a string (var = "varA") (dictionary 
key) at run-time and fetching it from the __dict__ like i was 
attempting to describe.

Ahh.  Well if you just want to get an attribute, I don't see why you 
wouldn't do it the normal way:

 >>> b = Bunch(varA="Hello!")
 >>> getattr(b, "varA")
'Hello!'
That's what getattr's for. ;)  No need to go poking around in __dict__.
Steve
Hmm true, (i had forgotten about getattr :/) in that case im indifferent 
to Bunch() not that i really see why it's useful except for making code 
look a bit nicer occasionaly.

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


Re: Cool object trick

2004-12-17 Thread Steven Bethard
Alex Stapleton wrote:
you are setting the variable name in your code (b.varA), not generating 
the variable name in a string (var = "varA") (dictionary key) at 
run-time and fetching it from the __dict__ like i was attempting to 
describe.
Ahh.  Well if you just want to get an attribute, I don't see why you 
wouldn't do it the normal way:

>>> b = Bunch(varA="Hello!")
>>> getattr(b, "varA")
'Hello!'
That's what getattr's for. ;)  No need to go poking around in __dict__.
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread Alex Stapleton
Steven Bethard wrote:
Alex Stapleton wrote:
you can't do
var = "varA"
obj = struct(varA = "Hello")
print obj.var
and expect it to say Hello to you.

The Bunch object from the PEP can take parameters in the same way that 
dict() and dict.update() can, so this behavior can be supported like:

 >>> b = Bunch({"varA":"Hello!"})
 >>> b.varA
'Hello!'
or
 >>> b = Bunch([("varA", "Hello!")])
 >>> b.varA
'Hello!'
Steve
thats nothing like what i described.
you are setting the variable name in your code (b.varA), not generating 
the variable name in a string (var = "varA") (dictionary key) at 
run-time and fetching it from the __dict__ like i was attempting to 
describe.

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


Re: Cool object trick

2004-12-17 Thread Steven Bethard
Alex Stapleton wrote:
you can't do
var = "varA"
obj = struct(varA = "Hello")
print obj.var
and expect it to say Hello to you.
The Bunch object from the PEP can take parameters in the same way that 
dict() and dict.update() can, so this behavior can be supported like:

>>> b = Bunch({"varA":"Hello!"})
>>> b.varA
'Hello!'
or
>>> b = Bunch([("varA", "Hello!")])
>>> b.varA
'Hello!'
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-17 Thread Alex Stapleton
Except what if you want to access elements based on user input or something?
you can't do
var = "varA"
obj = struct(varA = "Hello")
print obj.var
and expect it to say Hello to you.
objects contain a __dict__ for a reason :P
> Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
> obj.sausages, "and", obj.spam' a lot easier ;-)
then why dont you have a breakfast class? if you have this many 
properties associated with the same thing you might as well stick them 
in a class anyway.

[EMAIL PROTECTED] wrote:
I rather like it!  I prefer writing obj.spam to obj["spam"]!  I wonder if
there is a technical downside to this use of Python?
P.S.
Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
obj.sausages, "and", obj.spam' a lot easier ;-)
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Jive
Sent: 17 December 2004 06:29
To: [EMAIL PROTECTED]
Subject: Re: Cool object trick
Kinda cool.
It's occured to me that just about everything Pythonic can be done with
dicts and functions.  Your Obj is just a dict with an alternate syntax.  You
don't have to put quotes around the keys.  But that's cool.
class struct(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# Indented this way, it looks like a struct:
obj = struct(  saying = "Nee"
   , something = "different"
   , spam = "eggs"
  )
print obj.spam
# Is that really much different from this?
obj2 = { "saying" : "Nee"
, "something" : "different"
, "spam" : "eggs"
   }
print obj2["spam"]

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


RE: Cool object trick

2004-12-16 Thread Doran_Dermot
I rather like it!  I prefer writing obj.spam to obj["spam"]!  I wonder if
there is a technical downside to this use of Python?

P.S.

Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
obj.sausages, "and", obj.spam' a lot easier ;-)

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Jive
Sent: 17 December 2004 06:29
To: [EMAIL PROTECTED]
Subject: Re: Cool object trick

Kinda cool.

It's occured to me that just about everything Pythonic can be done with
dicts and functions.  Your Obj is just a dict with an alternate syntax.  You
don't have to put quotes around the keys.  But that's cool.


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

# Indented this way, it looks like a struct:
obj = struct(  saying = "Nee"
   , something = "different"
   , spam = "eggs"
  )

print obj.spam

# Is that really much different from this?

obj2 = { "saying" : "Nee"
, "something" : "different"
, "spam" : "eggs"
   }

print obj2["spam"]


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


Re: Cool object trick

2004-12-16 Thread Jive
Kinda cool.

It's occured to me that just about everything Pythonic can be done with
dicts and functions.  Your Obj is just a dict with an alternate syntax.  You
don't have to put quotes around the keys.  But that's cool.


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

# Indented this way, it looks like a struct:
obj = struct(  saying = "Nee"
   , something = "different"
   , spam = "eggs"
  )

print obj.spam

# Is that really much different from this?

obj2 = { "saying" : "Nee"
, "something" : "different"
, "spam" : "eggs"
   }

print obj2["spam"]


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


Re: Cool object trick

2004-12-12 Thread Steven Bethard
dataangel wrote:
Normally I'd just use class Obj(object): pass, but the advantage to this 
method is you can create an Obj like this:

Obj(id="desktop", last=0, color=self.getColor(DESKTOP_COLOR))
You can pass all the attributes you want the object to have this way. 
Nifty :)
Yup, that's basically what I was proposing in the pre-PEP:
http://mail.python.org/pipermail/python-list/2004-November/252621.html
I've let it slide for a bit here, but my intent is to make a patch that 
puts something like the pre-PEP class into the collections module and 
then send in the PEP.  I've been kinda busy recently, and it's not quite 
trivial since Bunch is in Python and currently the collections module is 
in C, but hopefully in the next few weeks I'll have the time.

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


Cool object trick

2004-12-12 Thread dataangel
I read some discussion on this list before about how sometimes it's 
useful to create a generic object class that you can just stick 
attributes to. I was reading the PyPanel source (not written by me) and 
I came across this:

#

class Obj(object):
# 

   """ Multi-purpose class """
   #
   def __init__(self, **kwargs):
   #
   self.__dict__.update(kwargs)
Normally I'd just use class Obj(object): pass, but the advantage to this 
method is you can create an Obj like this:

Obj(id="desktop", last=0, color=self.getColor(DESKTOP_COLOR))
You can pass all the attributes you want the object to have this way. 
Nifty :)

Sorry if this has been posted before, but I haven't seen it.
--
http://mail.python.org/mailman/listinfo/python-list