Thursday, April 1, 2010

comp.lang.python - 25 new messages in 14 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* decorators only when __debug__ == True - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/5da23b4a51e9a19e?hl=en
* Python 3.1, object, and setattr() - 5 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/621c86af4d407a34?hl=en
* sorting ascending/descending with operator.attrgetter - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/95c91eb2efe1bcc7?hl=en
* newbie with a encoding question, please help - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/dbf7a1880d0bb2a0?hl=en
* sort array, apply rearrangement to second - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/e282242a44ded215?hl=en
* CGI templating with python - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/04585b9f95c60dcd?hl=en
* Developement Question? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/44ac4387b21d6c29?hl=en
* (a==b) ? 'Yes' : 'No' - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/b985d5727945d2b4?hl=en
* Q: We have *args and **kwargs. Woud ***allargs be useful? - 2 messages, 2
authors
http://groups.google.com/group/comp.lang.python/t/c6aed08acf3bc006?hl=en
* subprocess only good for win32? - 4 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/37b513d9f7a3638d?hl=en
* "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada
jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ - 1 messages,
1 author
http://groups.google.com/group/comp.lang.python/t/4bc7a9d81ad251f6?hl=en
* no module named exceptions? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/a98e8d61335b8975?hl=en
* question on namedtuple - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/87748df52aedfcda?hl=en
* folks, what's wrong with this? - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/6ac8a11de4e2526f?hl=en

==============================================================================
TOPIC: decorators only when __debug__ == True
http://groups.google.com/group/comp.lang.python/t/5da23b4a51e9a19e?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 7:07 am
From: Steve Howell


On Apr 1, 6:16 am, Steve Holden <st...@holdenweb.com> wrote:
> MRAB wrote:
>
> > I had the following idea: define the terms 'decorator', 'decoration' and
> > 'decoratee'. The decorator applies the decoration to the decoratee. The
> > decoratee is the function defined locally in the decorator.
>
> It would make more sense (to me, at least) if the decoratee were the
> function passed as an argument to the decorator.
>

Me too. I do like the idea of coming up with a consistent terminology.


== 2 of 2 ==
Date: Thurs, Apr 1 2010 10:01 am
From: MRAB


Steve Holden wrote:
> MRAB wrote:
>> Steven D'Aprano wrote:
>>> On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:
>>>
>>>>>> A decorator shouldn't call the function it's decorating.
>>>>> *raises eyebrow*
>>>>>
>>>>> Surely, in the general case, a decorator SHOULD call the function it is
>>>>> decorating? I'm sure you know that, but your wording is funny and could
>>>>> confuse the OP.
>>>>>
>>>> What I mean is that the function that's doing the decorating shouldn't
>>>> call the function; it's the locally-defined wrapper function that calls
>>>> the decorated function.
>>> Ah, gotcha, that makes sense. Now I understand the distinction you
>>> were making. Thank you for the clarification.
>>>
>> I had the following idea: define the terms 'decorator', 'decoration' and
>> 'decoratee'. The decorator applies the decoration to the decoratee. The
>> decoratee is the function defined locally in the decorator.
>
> It would make more sense (to me, at least) if the decoratee were the
> function passed as an argument to the decorator.
>
Oops, you're right! What I meant was that the _decoration_ is the
function defined locally in the decorator.

==============================================================================
TOPIC: Python 3.1, object, and setattr()
http://groups.google.com/group/comp.lang.python/t/621c86af4d407a34?hl=en
==============================================================================

== 1 of 5 ==
Date: Thurs, Apr 1 2010 7:16 am
From: Steve Howell


On Apr 1, 6:46 am, Ethan Furman <et...@stoneleaf.us> wrote:
> Greetings!
>
> Perhaps I woke up too early this morning, but this behaviour has me baffled:
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> test = object()
>
> --> setattr(test, 'example', 123)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'example'
>
> Shouldn't setattr() be creating the 'example' attribute?  Any tips
> greatly appreciated!
>

On 2.6.2 the error seems to be limited to instances of object. If you
subclass object, you are fine. I do not know why that is so; I'm just
verifying that the behavior you see is not limited to 3.1.1.

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> class Foo(object): pass
...
>>> test = Foo()
>>> setattr(test, 'example', 123)
>>> test.example
123
>>> test = object()
>>> setattr(test, 'example', 123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'example'

It's probably good to subclass object anyway, with something like:

class Record(object):
pass

But I do not know your use case.

== 2 of 5 ==
Date: Thurs, Apr 1 2010 7:21 am
From: Steve Holden


Ethan Furman wrote:
> Greetings!
>
> Perhaps I woke up too early this morning, but this behaviour has me
> baffled:
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> test = object()
>
> --> setattr(test, 'example', 123)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'example'
>
> Shouldn't setattr() be creating the 'example' attribute? Any tips
> greatly appreciated!
>
It's not just object, and it's not just the setattr() function. It's not
even just Python 3.1 for that matter! Later Python 2 implementations
have the same issue.

>>> x = 1
>>> setattr(x, 'example', 123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'example'
>>> x.example = 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'example'
>>>

There are limits to what you can do with the built-in types. No matter
how hard Python tries to make them look the same, ultimately the
built-in types are implemented differently from the types you create
yourself.

For efficiency reasons the attributes of the built-ins are stored in a
different way (that's more accessible to the C implementation) than
those of the declared types.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 3 of 5 ==
Date: Thurs, Apr 1 2010 7:25 am
From: Steve Holden


Ethan Furman wrote:
> Greetings!
>
> Perhaps I woke up too early this morning, but this behaviour has me
> baffled:
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> test = object()
>
> --> setattr(test, 'example', 123)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'example'
>
> Shouldn't setattr() be creating the 'example' attribute? Any tips
> greatly appreciated!
>
By the way, the "solution" is to create a subclass of object (which in
Python 3 simply requires you to declare a class! In Python 2 you'd have
to explicitly subclass object, or (equivalently) set your class's
metaclass to type with

__metaclass__ = type


regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 4 of 5 ==
Date: Thurs, Apr 1 2010 10:44 am
From: Terry Reedy


On 4/1/2010 10:16 AM, Steve Howell wrote:
> On Apr 1, 6:46 am, Ethan Furman<et...@stoneleaf.us> wrote:
>
> On 2.6.2 the error seems to be limited to instances of object. If you
> subclass object, you are fine. I do not know why that is so;

As the other Steve said, object is a built-in class; user-defined
subclasses of object are user-defined classes. (And all other built-in
classes are built-in subclasses of object, at least in 3.x.)

Python objects can have either a fixed or variable set of attributes. By
default, instances of user classes have an attribute dictionary
(__dict__) for a variable set of attributes.

>>> a = A()
>>> a.a = 3
>>> a.a
3
>>> a.__dict__
{'a': 3}

The exception is when '__slots__ = xxx' is part of the class definition.
It instances then have a fixed set of attributes.

>>> class C(): __slots__ = ()

>>> c = C()
>>> c.a = 1
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
c.a = 1
AttributeError: 'C' object has no attribute 'a'

The error message means that 'a' is not in the fixed set of instance
attributes (as defined by __slots__) for class C.

In general, instances of built-in classes do not have such attribute
dictionaries and one their attribute set is fixed (and often empty). It
is as if built-in classes have '__slots__ = xxx' as part of their
definition. In particular, object and others act like they have
'__slots__ = ()', which means they have no instance attributes.

There are two exceptions among built-in classes that I know of: type and
'function', (whose instances are user-defined functions).

>>> def f(): pass

>>> f.__dict__
{} # standard dict just as with user class instances

Instances of type are more complicated:

>>> C.__dict__
<dict_proxy object at 0x00F682F0>
>>> C.z = 3
>>> C.z
3

so the dict_proxy for user classes is writable

but
>>> int.__dict__
<dict_proxy object at 0x00F5CDD0>
>>> int.z = 3
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int.z = 3
TypeError: can't set attributes of built-in/extension type 'int'

wheres for builtins, it is not.

Terry Jan Reedy


== 5 of 5 ==
Date: Thurs, Apr 1 2010 12:14 pm
From: Ethan Furman


Many thanks for the replies, and especially for the very detailed
explanation. Makes much more sense now.

~Ethan~


==============================================================================
TOPIC: sorting ascending/descending with operator.attrgetter
http://groups.google.com/group/comp.lang.python/t/95c91eb2efe1bcc7?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 7:23 am
From: Patrick Maupin


On Apr 1, 12:50 am, Steve Holden <st...@holdenweb.com> wrote:
> > I can well imagine that everybody who has to work with you thoroughly
> >  enjoys proving you wrong as often as possible.
>
> I am glad I wasn't drinking when I read this. Liquid in one's nose is so
> uncomfortable.

Well, in that case, I'm glad you enjoyed it. It's hard to know when
to put a disclaimer on these things. Others might not find the same
sorts of things funny, and the very act of putting a disclaimer often
promises more than it delivers, so I think it's pretty much just
"caveat reader."

> I guess we have to value the good that's in Steven (few would deny that
> he *is* technically very competent) and try and ignore his more annoying
> side.

Well, I suppose there are two coping strategies. Ignoring him (yes, I
need to do that more), and also, reading more carefully before
posting. The latter is always a good thing, but on the other hand it
takes more mental effort. Yes, it's better for posterity, but someone
reading the thread later and seeing what is written in context will
probably figure out what is meant, even if there are a few mistakes.
The extra effort shifts the balance from "will this help the OP?" to
"if this email were read completely devoid of external context, how
many ways are there to mis-interpret it, and how much time am I
willing to spend reducing that number, when it's impossible to get it
to zero, anyway?"

> I have toyed many times with the idea of giving a presentation at PyCon
> called something like "Humanity 101". It would include such advice as
> "When I say 'use soap' I am not talking about the Simple Object Access
> Protocol" and "Being wrong is usually survivable; offending a homicidal
> maniac often isn't".
>
> Perhaps I should just add it to the Holden Web course schedule?

Well, I haven't killed anybody yet; OTOH a few events from my
childhood taught me that there are really only two kinds of people:
those who could kill under the right circumstances, and those who
haven't figured it out yet. So, yes, that might be a good idea ;-)

Regards,
Pat

==============================================================================
TOPIC: newbie with a encoding question, please help
http://groups.google.com/group/comp.lang.python/t/dbf7a1880d0bb2a0?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 7:53 am
From: Mister Yu


On Apr 1, 9:31 pm, Stefan Behnel <stefan...@behnel.de> wrote:
> Mister Yu, 01.04.2010 14:26:
>
> > On Apr 1, 8:13 pm, Chris Rebert wrote:
> >> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
> >> unicode_string = gb2312_bytes.decode('gb2312')
> >> utf8_bytes = unicode_string.encode('utf-8') #as you wanted
>
> Simplifying this hack a bit:
>
> gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1')
> unicode_string = gb2312_bytes.decode('gb2312')
> utf8_bytes = unicode_string.encode('utf-8')
>
> Although I have to wonder why you want a UTF-8 encoded byte string as
> output instead of Unicode.
>
> >> If possible, I'd look at the code that's giving you that funky
> >> "string" in the first place and see if it can be fixed to give you
> >> either a proper bytestring or proper unicode string rather than the
> >> bastardized mess you're currently having to deal with.
>
> > thanks for the great tips! it works like a charm.
>
> I hope you're aware that it's a big ugly hack, though. You should really
> try to fix your input instead.
>
> > i m using the Scrapy project(http://doc.scrapy.org/intro/
> > tutorial.html) to write my crawler, when it extract data with xpath,
> > it puts the chinese characters directly into the unicode object.
>
> My guess is that the HTML page you are parsing is broken and doesn't
> specify its encoding. In that case, all that scrapy can do is guess, and it
> seems to have guessed incorrectly.
>
> You should check if there is a way to tell scrapy about the expected page
> encoding, so that it can return correctly decoded unicode strings directly,
> instead of resorting to dirty hacks that may or may not work depending on
> the page you are parsing.
>
> Stefan

Hi Stefan,

i don't think the page is broken or somehow, you can take a look at
the page http://www.7176.com/Sections/Genre/Comedy , it's kinda like
a chinese IMDB rip off

from what i can see from the source code of the page header, it
contains the coding info:
<HTML><head><meta http-equiv="Content-Type" content="text/html;
charset=gb2312" /><meta http-equiv="Content-Language" content="zh-CN" /
><meta content="all" name="robots" /><meta name="author"
content="admin(at)7176.com" /><meta name="Copyright" content="www.
7176.com" /> <meta content="类别为 剧情 的电影列表 第1页" name="keywords" /><TITLE>
类别为 剧情 的电影列表 第1页</TITLE><LINK href="http://www.7176.com/images/
pro.css" rel=stylesheet></HEAD>

maybe i should take a look at the source code of Scrapy, but i m just
not more than a week's newbie of python. not sure if i can understand
the source.

earlier Chris's walk around is looking pretty well until it meets some
string like this:
>>> su = u'一二三四 12345 一二三四'
>>> su
u'\u4e00\u4e8c\u4e09\u56db 12345 \u4e00\u4e8c\u4e09\u56db'
>>> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\u4e00\u4e8c\u4e09\u56db 12345 \u4e00\u4e8c\u4e09\u56db'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)

the digis doesn't get encoded so it messes up the code.

any ideas?

once again, thanks everybody's help!!!!


==============================================================================
TOPIC: sort array, apply rearrangement to second
http://groups.google.com/group/comp.lang.python/t/e282242a44ded215?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 7:59 am
From: Steve Howell


On Mar 31, 1:09 pm, Raymond Hettinger <pyt...@rcn.com> wrote:
> On Mar 30, 4:25 pm, s...@sig.for.address (Victor Eijkhout) wrote:
>
> > I have two arrays, made with numpy. The first one has values that I want
> > to use as sorting keys; the second one needs to be sorted by those keys.
> > Obviously I could turn them into a dictionary  of pairs and sort by the
> > first member, but I think that's not very efficient, at least in space,
> > and this needs to be done as efficiently as possible.
>
> Alf's recommendation is clean and correct.  Just make a list of
> tuples.
>
> FWIW, here's a little hack that does the work for you:
>
> >>> values = ['A', 'B', 'C', 'D', 'E']
> >>> keys = [50, 20, 40, 10, 30]
> >>> keyiter = iter(keys)
> >>> sorted(values, key=lambda k: next(keyiter))
>
> ['D', 'B', 'E', 'C', 'A']
>

Another option:

[values[i] for i in sorted(range(len(keys)), key=lambda i: keys[i])]

Sort the indexes according to keys values, then use indexes to get the
values.

It might read more clearly when broken out into two lines:

>>> sorted_indexes = sorted(range(len(keys)), key = lambda i: keys[i])
>>> sorted_indexes
[3, 1, 4, 2, 0]
>>> [values[i] for i in sorted_indexes]
['D', 'B', 'E', 'C', 'A']

The advantage of Raymond's solution is that he only creates one new
Python list, whereas my solutions create an intermediate Python list
of integers. I don't think my solution really is that space-wasteful,
though, since by the time the second list gets created, any internal
intermediate lists from CPython's sorted() implementation will
probably have been cleaned up.


==============================================================================
TOPIC: CGI templating with python
http://groups.google.com/group/comp.lang.python/t/04585b9f95c60dcd?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 8:19 am
From: KB

> Django will probably get you where you want to go the fastest:
>
>    http://www.djangoproject.com/
>
> In particular, its admin interface will probably automatically generate a usable
> UI for you without your having to write many templates at all.

Robert,

Thank you very very much. I had a brief peruse of django last night
and it does indeed look like what I am after! Will take me some
time :) to delve into it deeper but I wanted to thank you!

==============================================================================
TOPIC: Developement Question?
http://groups.google.com/group/comp.lang.python/t/44ac4387b21d6c29?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 8:23 am
From: KB


On Apr 1, 3:34 am, Wayne <infotech...@fairpoint.net> wrote:
> My town office uses Microsoft operating system. They have a proprietary
> accounting system that uses excel for their accounting reports.
> I would like to read these report and reproduce the report so that
> the report can be seen on the web. I was thinking about using xlrd and
> xlwt along with some sort of software for building the web pages. I
> use linux only and do not use Microsoft.
> Q. Does python have to be installed on there computer to run the script?
>
> Q. Am I approaching this the wrong way? If so, what would be a better
> approach?

Wayne, check out google group python-excel.

They are very helpful there, and I believe there are threads on how to
compile what you are looking for into a .exe for just such a situation
(Disclaimer: I am far from an expert, so I may have misunderstood from
the python-excel thread if python is/isn't required on the target
machine once the .exe is built, but try that group - John Machin is
very responsive)

==============================================================================
TOPIC: (a==b) ? 'Yes' : 'No'
http://groups.google.com/group/comp.lang.python/t/b985d5727945d2b4?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 8:27 am
From: Den


On Mar 30, 10:56 am, Steve Holden <st...@holdenweb.com> wrote:
> John Nagle wrote:
> > Chris Rebert wrote:
> >> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor.b...@hotmail.com>
> >> wrote:
> >>> Hi, how can I write the popular C/JAVA syntax in Python?
>
> >>> Java example:
> >>>    return (a==b) ? 'Yes' : 'No'
>
> >>> My first idea is:
> >>>    return ('No','Yes')[bool(a==b)]
>
> >>> Is there a more elegant/common python expression for this?
>
> >> Yes, Python has ternary operator-like syntax:
> >> return ('Yes' if a==b else 'No')
>
> >> Note that this requires a recent version of Python.
>
> >     Who let the dogs in?  That's awful syntax.
>
> Yes, that's deliberately awful syntax. Guido designed it that way to
> ensure that people didn't aver-use it, thereby reducing the readability
> of Python applications. Speaking purely personally I hardly ever use it,
> but don't dislike it.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
> Holden Web LLC                http://www.holdenweb.com/
> UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

I've been following this thread for a few days now. My thoughts are
that, in view of a long known widely used syntax for this operator,
python's syntax seems like change for change sake. If current
programing paradigm provides that particular trinary operator, why
should python's be different from the previously well known one.

For instance, no reasonable language designer would, now, use post-fix
(I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
(Just as no reasonable car designer would put the accelerator pedal on
the left.) There are conventions which should span products. Yes
python has the trinary operator and it's not going to change, but this
seems like a bit of petulance on the part of the designer.

Den


== 2 of 2 ==
Date: Thurs, Apr 1 2010 9:44 am
From: Steve Holden


Den wrote:
[...]
> I've been following this thread for a few days now. My thoughts are
> that, in view of a long known widely used syntax for this operator,
> python's syntax seems like change for change sake. If current
> programing paradigm provides that particular trinary operator, why
> should python's be different from the previously well known one.
>
Because the "long known widely used syntax" has been responsible for
some of the most incomprehensible and buggy code in the known universe. \
> For instance, no reasonable language designer would, now, use post-fix
> (I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
> (Just as no reasonable car designer would put the accelerator pedal on
> the left.) There are conventions which should span products. Yes
> python has the trinary operator and it's not going to change, but this
> seems like a bit of petulance on the part of the designer.
>
That argument could easily be extended to suggesting that there should
be no new languages at all. Guido made the specific choice of this
syntax precisely to try and ensure that the ternary (not trinary)
operator wasn't abused the way it has been in C (and later C#). He is a
language designer with a fine sense of readability, and I personally
respect his decision.

This StackOverflow thread

http://stackoverflow.com/questions/1763543/ternary-operator-associativity-in-c-can-i-rely-on-it

is just one example of the time that gets wasted.

But then I suppose that this thread just exemplifies that people will
find something else to waste their time on if you don't encourage them
to abuse the ternary operator.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/


==============================================================================
TOPIC: Q: We have *args and **kwargs. Woud ***allargs be useful?
http://groups.google.com/group/comp.lang.python/t/c6aed08acf3bc006?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 8:38 am
From: Jon Clements


On 1 Apr, 10:57, Jonathan Fine <J.F...@open.ac.uk> wrote:
> The idioms
>      def f(*args, **kwargs):
>          # Do something.
> and
>      args = (1, 2, 3)
>      kwargs = dict(a=4, b=5)
>      g(*args, **kwargs)
> are often useful in Python.
>
> I'm finding myself picking up /all/ the arguments and storing them for
> later use (as part of a testing framework).  So for me it would be nice
> if I could write
>      def f(***allargs):
>           args, kwargs = allargs
>           # Continue as before.
>
> However, if we do this then 'args' in '*args' is misleading.  So I'll
> use 'sargs' (for sequence arguments) instead.
>
> I can now write, for a suitable class Args
>      args = Args(1, 2, 3, a=4, b=5)
>      g(***args)   # Same as before.
>      sargs, kwargs = args
>      g(*sargs, **kwargs)  # Same as before.
>
> Even better, now that Args is a class we can give it a method 'call' so that
>      args.call(g)
> is equivalent to
>      g(***args)
> which removes the need for the *** construct.
>
> This reminds me of functools.partial except, of course, we've fixed all
> the arguments and left the passing of the function for later, whereas in
> partial we fix the function and some of the arguments.
>      http://docs.python.org/library/functools.html#functools.partial
>
> My view are that
> 1.  Conceptually ***allargs is useful, but an Args class would be more
> useful (not that it need be either-or).
>
> 2.  If Args were built in , there could be performance benefits.
>
> 3.  It's clearer to write
>          def(*seqargs, **kwargs):
> than
>          def(*args, **kwargs):
>
> 4.  When the Args class is used a lot, one might welcome
>          def(***args):
>              # Do something with args.
> as a shortcut (and minor speedup) for
>          def(*seqargs, **kwargs):
>              args = Args(*seqargs, **kwargs)
>              # Do something with args.
>
> I look forward to your comments on this.
>
> --
> Jonathan

I'm not sure this'll catch on, it'll be interesting to see other
comments.
However, I believe you can get the behaviour you desire something
like:

import inspect

class AllArgs(object):
def __init__(self, func):
self._func = func
self._spec = inspect.getargspec(func)
self._nposargs = len(self._spec.args)
def __call__(self, *args, **kwdargs):
self._func.func_globals['Args'] = (args[self._nposargs:],
kwdargs)
return self._func(*args[:self._nposargs])

@AllArgs
def test():
print Args

@AllArgs
def test2(a, b):
print a, b, Args

test(1, 2, 3, 4, 5, a=3, b=5)
test2(1, 2, 3, 4, 5, c=7)

Done quickly, probably buggy, but does provide 'Args', but without
further work
swallows any *'s and **'s and might ignore defaults (hideously
untested)

hth

Jon.


== 2 of 2 ==
Date: Thurs, Apr 1 2010 9:44 am
From: Jonathan Fine


Jon Clements wrote:

> I'm not sure this'll catch on, it'll be interesting to see other
> comments.
> However, I believe you can get the behaviour you desire something
> like:
>
> import inspect
>
> class AllArgs(object):
> def __init__(self, func):
> self._func = func
> self._spec = inspect.getargspec(func)
> self._nposargs = len(self._spec.args)
> def __call__(self, *args, **kwdargs):
> self._func.func_globals['Args'] = (args[self._nposargs:],
> kwdargs)
> return self._func(*args[:self._nposargs])
>
> @AllArgs
> def test():
> print Args
>
> @AllArgs
> def test2(a, b):
> print a, b, Args
>
> test(1, 2, 3, 4, 5, a=3, b=5)
> test2(1, 2, 3, 4, 5, c=7)
>
> Done quickly, probably buggy, but does provide 'Args', but without
> further work
> swallows any *'s and **'s and might ignore defaults (hideously
> untested)

Thank you for your interest, Jon.

According to http://docs.python.org/library/inspect.html we have that
func_globals is the global namespace in which this function was defined.

Hence we have
>>> def f(): pass
...
>>> f.func_globals is globals()
True
>>> f.func_globals ['x'] = 3
>>> x
3
>>>

I don't yet understand what your code is intended to do, but I'm fairly
sure you're not wishing to 'monkey-patch' a global namespace of a module.

--
Jonathan

==============================================================================
TOPIC: subprocess only good for win32?
http://groups.google.com/group/comp.lang.python/t/37b513d9f7a3638d?hl=en
==============================================================================

== 1 of 4 ==
Date: Thurs, Apr 1 2010 9:35 am
From: wukong


On Mar 31, 3:47 pm, "Martin v. Loewis" <mar...@v.loewis.de> wrote:
> > WindowsError: [Error 14001] The application has failed to start
> > because its side-by-side configuration is incorrect. Please see the
> > application event log for more detail
>
> This is a configuration error on your system. The application you are
> trying to start is incorrectly installed - it's not only that Python
> can't start it, but nobody can.
>
> Regards,
> Martin

but python runs happy otherwise, only this call to subprocess resulted
in an err. does anyone know for sure subprocess runs on win64? or
any others like, popen does?
thanks
wk


== 2 of 4 ==
Date: Thurs, Apr 1 2010 9:36 am
From: wukong


On Mar 31, 3:47 pm, "Martin v. Loewis" <mar...@v.loewis.de> wrote:
> > WindowsError: [Error 14001] The application has failed to start
> > because its side-by-side configuration is incorrect. Please see the
> > application event log for more detail
>
> This is a configuration error on your system. The application you are
> trying to start is incorrectly installed - it's not only that Python
> can't start it, but nobody can.
>
> Regards,
> Martin

nad also as i mentioned previously, it runs great on win32.


== 3 of 4 ==
Date: Thurs, Apr 1 2010 9:58 am
From: Steve Holden


wukong wrote:
> On Mar 31, 3:47 pm, "Martin v. Loewis" <mar...@v.loewis.de> wrote:
>>> WindowsError: [Error 14001] The application has failed to start
>>> because its side-by-side configuration is incorrect. Please see the
>>> application event log for more detail
>> This is a configuration error on your system. The application you are
>> trying to start is incorrectly installed - it's not only that Python
>> can't start it, but nobody can.
>>
>> Regards,
>> Martin
>
> but python runs happy otherwise, only this call to subprocess resulted
> in an err. does anyone know for sure subprocess runs on win64? or
> any others like, popen does?
> thanks
> wk

Subprocess runs another program. It's the program you are running that's
giving the error, Python is merely reporting it.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 4 of 4 ==
Date: Thurs, Apr 1 2010 10:11 am
From: "Michel Claveau - MVP"


Hi!

> side-by-side configuration is incorrect

Others have given you an explanation.

A possibility: you use a DLL directly, without having installed.
That is OK with some DLL, and no OK with others DLL.

@-salutations
--
Michel Claveau

==============================================================================
TOPIC: "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada
jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
http://groups.google.com/group/comp.lang.python/t/4bc7a9d81ad251f6?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 10:12 am
From: saima81


"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
"jobs in canada" "jobs in canada for pakistanis" "jobs in canada for
foreigners" "jobs in canada hotels" "jobs in canada for accountants"
"canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/
v

==============================================================================
TOPIC: no module named exceptions?
http://groups.google.com/group/comp.lang.python/t/a98e8d61335b8975?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 10:12 am
From: Joaquin Abian


In python 3.1,

>>> import exceptions
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import exceptions
ImportError: No module named exceptions

in 2.6 no exception is raised
It should be the same in 3.1, isnt it?

Joaquin

==============================================================================
TOPIC: question on namedtuple
http://groups.google.com/group/comp.lang.python/t/87748df52aedfcda?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 11:35 am
From: hetchkay


Hi,
For purposes I don't want to go into here, I have the following code:
def handleObj(obj):
if isinstance(obj, MyType):
return obj.handle()
elif isinstance(obj, (list, tuple, set)):
return obj.__class__(map (handleObj, obj))
elif isinstance(obj, dict):
return obj.__class__((handleObj(k), handleObj(v)) for k, v in
obj.items())
else:
return obj

This works fine except if obj is a namedtuple. A namedtuple object has
different constructor signature from tuple:
>>> tuple([1,2])
(1,2)
>>> collections.namedtuple("sample", "a, b")([1, 2])
Traceback (most recent call last):
File "CommandConsole", line 1, in <module>
TypeError: __new__() takes exactly 3 arguments (2 given)
>>> collections.namedtuple("sample", "a, b")(1, 2)
sample(a=1, b=2)

Is there any easy way of knowing that the obj is a namedtuple and not
a plain tuple [so that I could use obj.__class__(*map(handleObj, obj))
instead of obj.__class__(map(handleObj, obj)) ].

Thanks in advance for your help.

Krishnan

==============================================================================
TOPIC: folks, what's wrong with this?
http://groups.google.com/group/comp.lang.python/t/6ac8a11de4e2526f?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 11:56 am
From: Ani


Hi All:

I am just a beginner in python. Can anyone please tell me what is
wrong with this piece of code?

import copy
class BaseDummyObject(object):

def __init__(self):
pass

def __getattr__(self, item):
try:
return self.__dict__.__getitem__(item)
except KeyError:
print "Attribute Error: attr %s of class %s non-existent!"
%(item,

self.__class__.__name__)
class DummyObject(BaseDummyObject):
pass


def main():
bar = 3
obj = DummyObject()
obj.foo = bar
obj.me = obj

newobj = copy.deepcopy(obj)


if __name__ == "__main__":
main()

So when I do this, I get:

Attribute Error: attr __deepcopy__ of class DummyObject non-existent!
Attribute Error: attr __getnewargs__ of class DummyObject non-
existent!
Traceback (most recent call last):
File "C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager
\test_code.py", line 39, in <module>
main()
File "C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager
\test_code.py", line 30, in main
newobj = copy.deepcopy(obj)
File "C:\Python26\lib\copy.py", line 181, in deepcopy
rv = reductor(2)
TypeError: 'NoneType' object is not callable

Any help will be really appreciated.


== 2 of 2 ==
Date: Thurs, Apr 1 2010 12:10 pm
From: Robert Kern


On 2010-04-01 13:56 PM, Ani wrote:
> Hi All:
>
> I am just a beginner in python. Can anyone please tell me what is
> wrong with this piece of code?
>
> import copy
> class BaseDummyObject(object):
>
> def __init__(self):
> pass
>
> def __getattr__(self, item):
> try:
> return self.__dict__.__getitem__(item)
> except KeyError:
> print "Attribute Error: attr %s of class %s non-existent!"
> %(item,
>
> self.__class__.__name__)

You need to raise an AttributeError here. Otherwise, it implicitly returns None
for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate