Re: How to avoid certain directories when using os.walk?

2009-10-29 Thread Chris Rebert
On Thu, Oct 29, 2009 at 9:53 PM, Peng Yu  wrote:
> I don't see a way to avoid walking over directories of certain names
> with os.walk. For example, I don't want os.walk return files whose
> path include '/backup/'. Is there a way to do so? Otherwise, maybe I
> will have to make my own program. Thank you!

Read the docs! (http://docs.python.org/library/os.html#os.walk):

"""
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Generate the file names in a directory tree by walking the tree
either top-down or bottom-up. For each directory in the tree rooted at
directory top (including top itself), it yields a 3-tuple (dirpath,
dirnames, filenames).
[...]
When topdown is True, the caller can modify the dirnames list
in-place (perhaps using del or slice assignment), and walk() will only
recurse into the subdirectories whose names remain in dirnames; this
can be used to prune the search, impose a specific order of visiting,
or even to inform walk() about directories the caller creates or
renames before it resumes walk() again.
"""

They even include a specific code example of how to skip unwanted
subdirectories.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: self.__dict__ tricks

2009-10-29 Thread Ben Finney
Ben Finney  writes:

> Steven D'Aprano  writes:
>
> > On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
> > > class formLoader():
> >
> > Idiomatic Python is to use CamelCase for classes.
>
> Or rather: Instead of camelCase names, idiomatic Python is to use
> TitleCase names.

Blah, my attempt at clarity just made it more confusing.

Instead of camelCase names, idiomatic Python is to use TitleCase names
for classes.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but how will we get a pair of Abe Vigoda's pants?” |
_o__)   —_Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: DARPA red balloon challenge

2009-10-29 Thread Mensanator
On Oct 29, 10:27 pm, Adam N  wrote:
> All,
>
> In case people hadn't heard, DARPA just announced what I think is the
> coolest competition ever:
>
> http://networkchallenge.darpa.mil/
>
> On December 5, DARPA will raise 10 red weather balloons somewhere in
> the US.  The first person to get the location of all 10 balloons and
> submit them will be given $40k.
>
> I'm proposing that if "I" win, half the money ($20k) will be given to
> the Django Software Foundation.  The other half ($20k) will go to the
> Python Software Foundation.

Uh...didn't read the rule about "Tax treatment of prizes will be
handled
in accordance with U.S. Internal Revenue Service guidelines", eh?

>
> I've set up a StackOverflow site for coordination for anybody who
> would like to join:
>
> http://darpa.stackexchange.com/
>
> I think the first thing that needs to happen is to get a critical mass
> of users on the site and to use the Q&A capabilities of the site to
> figure out what tools we should use next.
>
> Cheers,
> Adam Nelson

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


How to avoid certain directories when using os.walk?

2009-10-29 Thread Peng Yu
I don't see a way to avoid walking over directories of certain names
with os.walk. For example, I don't want os.walk return files whose
path include '/backup/'. Is there a way to do so? Otherwise, maybe I
will have to make my own program. Thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension problem

2009-10-29 Thread Terry Reedy

alex23 wrote:

On Oct 30, 1:10 pm, Nick Stinemates  wrote:

Some objects are singletons, ie there's only ever one of them. The most
common singleton is None. In virtually every other case you should be
using "==" and "!=".

Please correct me if I am wrong, but I believe you meant to say some
objects are immutable, in which case you would be correct.


You're completely wrong. Immutability has nothing to do with identity,
which is what 'is' is testing for:


What immutability has to do with identity is that 'two' immutable 
objects with the same value *may* actually be the same object, 
*depending on the particular version of a particular implementation*.





t1 = (1,2,3) # an immutable object
t2 = (1,2,3) # another immutable object


Whether or not this is 'another' object or the same object is irrelevant 
for all purposes except identity checking. It is completely up to the 
interpreter.



t1 is t2

False


In this case, but it could have been True.


t1 == t2

True

MRAB was refering to the singleton pattern[1], of which None is the
predominant example in Python. None is _always_ None, as it's always
the same object.


And in 3.x, the same is true of True and False.

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


Re: Python 2.6 Global Variables

2009-10-29 Thread Gabriel Genellina
En Fri, 30 Oct 2009 00:29:27 -0300, Steven D'Aprano  
 escribió:

On Thu, 29 Oct 2009 10:31:03 -0700, AK Eric wrote:



2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.


Isn't that __main__?


Well there you go, I just learned something new.

I was going to say "No, every module has its own __main__", and say that
the only truly global namespace was builtins, which you really shouldn't
mess with. But then I decided to just try it, and blow me down, it works!

[st...@sylar ~]$ cat set_parrot.py
import __main__
__main__.parrot = "Norwegian Blue"

[st...@sylar ~]$ cat get_parrot.py
import __main__
print __main__.parrot

[st...@sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import set_parrot
import get_parrot

Norwegian Blue


I'm sure there are all sorts of odd problems this would lead to in large
scale code, but it's a neat trick to know.


It isn't a neat trick anymore once you realize the name '__main__' isn't  
special.


Replace __main__ with foo, or config, or whatever, and you get the same  
results. Ok, there is a catch: a file with that name must exist, at least  
an empty one...


You're just importing the same module from two places; changes done in one  
place are reflected in the second place, like with any other object.


--
Gabriel Genellina

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


Re: How to get a unique function name for methods

2009-10-29 Thread Terry Reedy

Christian Heimes wrote:

Philip Guo wrote:

Does anyone know how to get this information either from a code object or
from a related object?  I am hacking the interpreter, so I have full access
to everything.


Does this help?


class A(object):

... def method(self):
... pass
...

A.method.im_class




In 3.x, A.method is the function, not a wrapper, so this will not work.

But as I said before, if one has class A 'in hand', it seems pointless 
to go looking for it.


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


Re: list comprehension problem

2009-10-29 Thread Steven D'Aprano
On Thu, 29 Oct 2009 23:10:39 -0400, Nick Stinemates wrote:

>> Some objects are singletons, ie there's only ever one of them. The most
>> common singleton is None. In virtually every other case you should be
>> using "==" and "!=".
> 
> Please correct me if I am wrong, but I believe you meant to say some
> objects are immutable, in which case you would be correct.


No, being immutable does not imply there is only one of it. Strings and 
ints are immutable:

>>> a = 987654
>>> b = 987654
>>> a == b
True
>>> a is b
False


However, None, True, False, NotImplemented, and most (all?) builtin 
functions are singletons:

>>> f = len; g = len
>>> f is g
True
>>> x = None; y = None
>>> x is y
True



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


Re: self.__dict__ tricks

2009-10-29 Thread Steven D'Aprano
On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:

> This is not a request for help but a request for comments: Consider the
> following code and note that 1)The initializer uses the dictionary style
> of arguments 2)The check loop executes before all of the class variables
>   are declared

Could you explain what problem you are trying to solve?


> class formLoader():

Idiomatic Python is to use CamelCase for classes.


>   def __init__(self,**kw):
>   self.fileName = None
>   self.record = None
>   self.string = None
>   ## Uncomment below to see that only fileName, record 
>   ## and string are recorded by __dict__
>   #std.debug("self.__dict__",self.__dict__)
>   for k in kw.keys():

In recent versions of Python, this is best written as

for k in kw:

>   if k in self.__dict__:
>   self.__dict__[k] = kw[k]

Is your intention to ensure that the only keyword arguments allowed are 
fileName, record and string?

Perhaps the easiest way to do that is:

for k in kw:
if k not in ('filename', 'record', 'string'):
raise Exception()  # whatever...
setattr(self, k) = kw[k]



>   else:
>   raise AttributeError(

In my opinion, AttributeError is not appropriate here. Passing an invalid 
parameter shouldn't raise the same error as failing an attribute look-up. 
That's misleading and confusing.


>   "%s is not a class member. Use one of ('%
>   s')" % (repr(k),"', '".join
>   (self.__dict__.keys(

[Aside: eight space tabs are *WAY* too big for Usenet and email. You 
should use four spaces, or even two, when posting here.]

It is idiomatic Python to use "instance attributes" to refer to 
attributes attached to instances, and "class attributes" to refer to 
those attached to classes. Talking about "class members" will confuse 
Python developers who aren't also familiar with Java or C++. (I know it 
confuses *me* -- are class members shared by all instances in a class, as 
the name implies, or are they individual to the instance, as your code 
implies?)

I also should point out that your trick will fail if you are using 
__slots__.



>   self.tokens = 
["form","input","textarea","select","option","form"]
>   self.inputTypes =
>   ["button","checkbox","file","hidden","image","password",
>  "radio","reset","submit","text"]
>   self.inputValTypes = ["file","hidden","password","text"] 
> self.colnames
>   = []  ## case-insensitive column names 
> self.formIndexes = []   ##
>   Index forms in outer list


Is any of that relevant to the trick you are asking for comments for? If 
not, why is it here?


> I'd welcome comments - such as any other applications.

Personally, I don't like it. The method signature makes it impossible to 
tell what arguments are excepted, and it forces me to use keywords even 
if I'd prefer to use positional arguments. I prefer to let the 
interpreter check the arguments for me:


class FormLoader():
def __init__(self, fileName=None, record=None, string=None):
self.fileName = fileName
self.record = record
self.string = string

That's all it takes, and you get the benefit of a method signature that 
makes it obvious what arguments it takes.



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


Re: Problem embedding Python.

2009-10-29 Thread Brandon Keown
O...K...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modify dict/set during iteration?

2009-10-29 Thread metal
On 10月30日, 上午11时59分, Steven D'Aprano  wrote:
> On Thu, 29 Oct 2009 19:02:01 -0700, metal wrote:
> > I used this quickndirty way, any good idea to solve this problem?
>
> It's not a problem that wants solving, it's a feature that wants paying
> attention to.
>
> As a general rule, you shouldn't modify data structures while you're
> iterating over them, unless the data structure is advertised as safe to
> modify while being iterated over, or you can do so in a way that is
> guaranteed to be safe. When it comes to dicts and sets, neither of those
> conditions hold.
>
> Why do you want to do this? It seems like a lot of effort to avoid a
> simple, straight-forward idiom:
>
> make a copy of the dict or set
> iterate over the copy, making changes to the original
>
> What are you trying to accomplish by modifying objects while iterating
> over them?
>
>
>
> > def miter(iterable):
> [...]
> >         except RuntimeError, e:
> >             # Not sure if there were any other RuntimeError
> >             if 'changed size during iteration' in e.message:
> >                 continue
>
> That is not safe. There's no guarantee that the error message won't
> change, even between one minor version to another, or between one Python
> implementation and another. If you insist on making such an unsafe test,
> at the very least be as conservative in what you expect as possible:
>
> if 'changed' in e.message and 'size' in e.message:
>
> and hope that nobody runs your code with internationalised error messages.
>
> --
> Steven

Yes the idoim rulz. I confused my self.

Maybe my real goal is the following:

def miter(iterable):
for x in tuple(iterable):
if x in iterable:
yield x

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


Re: Are *.pyd's universal?

2009-10-29 Thread Lawrence D'Oliveiro
In message , Christian 
Heimes wrote:

> Lawrence D'Oliveiro schrieb:
>
>> In message ,
>> Christian Heimes wrote:
>> 
>>> On Linux and several other Unices the suffix is .so and not .pyd.
>> 
>> Why is that? Or conversely, why isn't it .dll under Windows?
> 
> On Windows it used to be .dll, too.
> The suffix was changed to avoid issues with other dlls and name clashes.

What clashes? How come other OSes don't seem prone to the same problems?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension problem

2009-10-29 Thread alex23
On Oct 30, 1:10 pm, Nick Stinemates  wrote:
> > Some objects are singletons, ie there's only ever one of them. The most
> > common singleton is None. In virtually every other case you should be
> > using "==" and "!=".
>
> Please correct me if I am wrong, but I believe you meant to say some
> objects are immutable, in which case you would be correct.

You're completely wrong. Immutability has nothing to do with identity,
which is what 'is' is testing for:

>>> t1 = (1,2,3) # an immutable object
>>> t2 = (1,2,3) # another immutable object
>>> t1 is t2
False
>>> t1 == t2
True

MRAB was refering to the singleton pattern[1], of which None is the
predominant example in Python. None is _always_ None, as it's always
the same object.

1: http://en.wikipedia.org/wiki/Singleton_pattern
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* alex23:

"Alf P. Steinbach"  wrote:

However, given what I've now learned about the current situation wrt. versions
of Python, where Python 3.x is effectively a new language, and where apparently
ActiveState has no installer for that, I'm rewriting to use the "official"
distribution.


I hope the rest of your research is a little more thorough:

"Current releases of ActivePython are 2.6.3.7, 3.1.1.2, and 2.5.4.4."

From: http://www.activestate.com/activepython/


Thanks.

Several others have already mentioned the same else-thread, but thanks anyway! 
:-)

And no, I didn't do any research on that. If it mattered more (e.g. appearing as 
statement in the text) I'd have done that. The nice thing about Usenet is that 
people rush in to correct things. ;-) http://xkcd.com/386/>



Cheers,

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


Re: Modify dict/set during iteration?

2009-10-29 Thread Steven D'Aprano
On Thu, 29 Oct 2009 19:02:01 -0700, metal wrote:

> I used this quickndirty way, any good idea to solve this problem?

It's not a problem that wants solving, it's a feature that wants paying 
attention to.

As a general rule, you shouldn't modify data structures while you're 
iterating over them, unless the data structure is advertised as safe to 
modify while being iterated over, or you can do so in a way that is 
guaranteed to be safe. When it comes to dicts and sets, neither of those 
conditions hold.

Why do you want to do this? It seems like a lot of effort to avoid a 
simple, straight-forward idiom:

make a copy of the dict or set
iterate over the copy, making changes to the original


What are you trying to accomplish by modifying objects while iterating 
over them?


> def miter(iterable):
[...]
> except RuntimeError, e:
> # Not sure if there were any other RuntimeError
> if 'changed size during iteration' in e.message:
> continue

That is not safe. There's no guarantee that the error message won't 
change, even between one minor version to another, or between one Python 
implementation and another. If you insist on making such an unsafe test, 
at the very least be as conservative in what you expect as possible:

if 'changed' in e.message and 'size' in e.message:

and hope that nobody runs your code with internationalised error messages.



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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread alex23
"Alf P. Steinbach"  wrote:
> However, given what I've now learned about the current situation wrt. versions
> of Python, where Python 3.x is effectively a new language, and where 
> apparently
> ActiveState has no installer for that, I'm rewriting to use the "official"
> distribution.

I hope the rest of your research is a little more thorough:

"Current releases of ActivePython are 2.6.3.7, 3.1.1.2, and 2.5.4.4."

From: http://www.activestate.com/activepython/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* Ethan Furman:

Alf P. Steinbach wrote:

* Ethan Furman:


Alf P. Steinbach wrote:


* James Harris:


You get way too deep into Python in places (for a beginner's course in
programming). For example, "from now on I’ll always use from
__future__ in any program that uses print."


Sorry, but I think that hiding such concerns is a real disservice.


The disservice is in teaching folks to use non-standard elements, 
which is (sort-of) what __future__ is.  Changes to the language are 
experimented with in __future__ and can change from one release to 
the next.  If memory serves, the with statement is an example of 
having different behavior when it was moved out of __future__ and 
made a standard part of the language.


That's a bit of a straw man argument. 


You don't agree, so it's a straw man?  You didn't know, and when the 
information is pointed out, it's a straw man?


No. It's a "straw man" argument when the argument is made against something 
that's not the real position  --  often it's the opposite position  --  of the 
opponent. And that's what you (probably unwittingly, but literally) did: you 
claimed the text used "non-standard elements" and therefore was subject to 
changes in new versions of the language, while the reality was opposite: a 
defense against changes in new versions, and improvement in that respect.


Not that it matters much now. ;-)

I mean, I've started the work to change the text to 3.1.1.


I used "from __future__" to write forward-compatible calls of print, 
so that those examples would not mysteriously work or not depending on 
the Python version. 


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
 >>> from __future__ import print_function
  File "", line 1
SyntaxError: future feature print_function is not defined

Hmmm... Doesn't seem to work in 2.5.  So much for not working on a 
different version.


That's a bit of a straw man argument. :-)  "Forward compatibility" is one way. 
What you illustrate is lack of "backward compatibility", which is the other way.


It would be utterly silly to try to make the examples backward compatible.

I mean, how far back? :-D



I did not use it to access experimental features.


 From what I've seen of your posts so far, you wouldn't have known if 
the print in __future__ was slightly different from the actual print in 
3.x anyway.


Then you probably haven't read the passage in ch 2 where I introduced that.

If so then I understand why you commented as you did -- misled by the other 
poster's comment.


That happens a lot on Usenet, people use all kinds of rhetoric devices and 
assumptions, sometimes intentionally and sometimes uninentionally, and sometimes 
that "works", misleading others.



However, I didn't know then that the language has changed so much in 
3.x that it isn't practical to aim at general forward compatibility or 
version independence.


And I didn't know until your comment above that some features, 
apparently, only exist in __future__ but are not part of the language, 
subject to change.


Which is precisely the point raised by several -- writing a book for 
novices, while still a novice, is going to be risky... especially if you 
keep disregarding good advice about what to include and exclude.


Yes, it's risky.

Although please note that I'm very far from a novice at programming.

I have, through the years, learned quite a number of programming languages 
(started with Basic and 8080 assembler back around 1980), so I believe there is 
a >0 chance of doing this with a positive result, but yes, risky!


And no, I'm not disregarding advice; on the contrary, the reason I asked for 
feedback in a public forum was precisely because I'm *very* aware of the risk, 
as I stated in the thread's starting article. But there is also a risk with this 
public exposure, of course. Not everyone on Usenet is equally serious.


Btw., regarding the serious ones, I really appreciated your point about 
"Tkinter" -> "tkinter", for example. ;-)




Is there a current example?

And, just a suggestion, would it not be better to have a different 
name for such experimental (as opposed to future language version) 
features, e.g. "from __experimental__", differentiating between 
forward compatibility in e.g. production code, and trying out 
experimental subject-to-change features?


You're missing the point.  If it's in __future__ it's subject to change. 
 Most likely it won't be a drastic change, but it *can* change.  The 
'experimental' is more along the lines of "hey, this is coming down the 
pike, let's do some stress-testing so we can nail down the final 
implementation".


Does that mean that 'print' is still subject to change as of 3.1.1?


Cheers,

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Steven D'Aprano
On Thu, 29 Oct 2009 11:05:11 -0700, Ethan Furman wrote:

> Alf P. Steinbach wrote:
>> * James Harris:
>> 
>>> You get way too deep into Python in places (for a beginner's course in
>>> programming). For example, "from now on I’ll always use from
>>> __future__ in any program that uses print."
>> 
>> Sorry, but I think that hiding such concerns is a real disservice.
> 
> The disservice is in teaching folks to use non-standard elements, which
> is (sort-of) what __future__ is.  Changes to the language are
> experimented with in __future__ 

That is incorrect. Changes to the syntax or language semantics are 
*introduced* with __future__, so as to avoid a sudden and disruptive 
backwards incompatible change. If a feature makes it into __future__, it 
is anything but experimental.

http://www.python.org/dev/peps/pep-0236/


There is nothing "non-standard" about features introduced with 
__future__. The only thing that concerns me is that __future__ may be a 
little too advanced for beginners.



> and can change from one release to the next.

Python guarantees that no feature will ever be removed from __future__. 
It may become a no-op, but it will always be there. Note that 3.0 still 
defines nested_scopes, even though that's been standard in the language 
since 2.2:

[st...@sylar ~]$ python3.0
Python 3.0.1 (r301:69556, Apr  2 2009, 00:41:38)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import nested_scopes
>>>
>>> import __future__
>>> __future__.nested_scopes
_Feature((2, 1, 0, 'beta', 1), (2, 2, 0, 'alpha', 0), 16)



> If memory serves, the with statement is an example of having
> different behavior when it was moved out of __future__ and made a
> standard part of the language.

I feel safe to claim you are wrong without even checking.


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


Re: __eq__() inconvenience when subclassing set

2009-10-29 Thread Gabriel Genellina
En Wed, 28 Oct 2009 23:12:53 -0300, Jess Austin   
escribió:



class mySet(set):

... def __eq__(self, other):
... print "called mySet.__eq__()!"
... if isinstance(other, (set, frozenset)):
... return True
... return set.__eq__(self, other)
...

Now I want the builtin set and frozenset types to use the new
__eq__() with mySet symmetrically.


mySet() == set([1])

called mySet.__eq__()!
True

mySet() == frozenset([1])

called mySet.__eq__()!
True

set([1]) == mySet()

called mySet.__eq__()!
True

frozenset([1]) == mySet()

False

frozenset doesn't use mySet.__eq__() because mySet is not a subclass
of frozenset as it is for set. [...failed attempts to inherit from both  
set and frozenset...]

I must redefine __eq__(), and I'd like to be able to compare
instances of the class to both set and frozenset instances.


We know the last test fails because the == logic fails to recognize mySet  
(on the right side) as a "more specialized" object than frozenset (on the  
left side), because set and frozenset don't have a common base type  
(although they share a lot of implementation)


I think the only way would require modifying tp_richcompare of  
set/frozenset objects, so it is aware of subclasses on the right side.  
Currently, frozenset() == mySet() effectively ignores the fact that mySet  
is a subclass of set.


--
Gabriel Genellina

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


Re: Python 2.6 Global Variables

2009-10-29 Thread Steven D'Aprano
On Thu, 29 Oct 2009 10:31:03 -0700, AK Eric wrote:

>> 2/ in Python, "global" really means "module-level" - there's nothing
>> like a "true" global namespace.
> 
> Isn't that __main__?

Well there you go, I just learned something new.

I was going to say "No, every module has its own __main__", and say that 
the only truly global namespace was builtins, which you really shouldn't 
mess with. But then I decided to just try it, and blow me down, it works!


[st...@sylar ~]$ cat set_parrot.py
import __main__
__main__.parrot = "Norwegian Blue"

[st...@sylar ~]$ cat get_parrot.py
import __main__
print __main__.parrot

[st...@sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import set_parrot
>>> import get_parrot
Norwegian Blue


I'm sure there are all sorts of odd problems this would lead to in large 
scale code, but it's a neat trick to know.



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


OT: DARPA red balloon challenge

2009-10-29 Thread Adam N
All,

In case people hadn't heard, DARPA just announced what I think is the
coolest competition ever:

http://networkchallenge.darpa.mil/

On December 5, DARPA will raise 10 red weather balloons somewhere in
the US.  The first person to get the location of all 10 balloons and
submit them will be given $40k.

I'm proposing that if "I" win, half the money ($20k) will be given to
the Django Software Foundation.  The other half ($20k) will go to the
Python Software Foundation.

I've set up a StackOverflow site for coordination for anybody who
would like to join:

http://darpa.stackexchange.com/

I think the first thing that needs to happen is to get a critical mass
of users on the site and to use the Q&A capabilities of the site to
figure out what tools we should use next.

Cheers,
Adam Nelson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* Rhodri James:
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach  
wrote:


There's rather a lot to know about the environment that a program 
executes in if one is going to create robust, dependable, generally 
usable programs, not just toy examples.


I'd say this was at best an extremely misleading statement.  The robust,
dependable, usable, low-fat, carcinogen-free programs that I've written
fall into two categories; either they are embedded programs whose
environment is the silicon they're running on pretty much literally, or
they carefully *don't* know about their environment so run equally
effectively everywhere.  It's the programs that do know about their
environment and go on to make assumptions about it that turn out
not to be robust, dependable, or very often usable.

Unfortunately even most professional programs do not handle the 
requirements of their environs very well, and I think that educators, 
even such as I, have a responsibility to now start teaching students 
to do things right. To take but one example that you may or may not be 
aware of, Microsoft's own Windows Explorer, the main GUI shell for 
Windows, which presumably was made by the best programmers available


Bwahahahahahahaha.

Uh, sorry.  I know that wasn't terribly nice, but the politest answer
I can think of that gets over the utter wrongness of this assumption is
"Hell, no."

with the best knowledge of the program's environment, is unable to 
handle (such as delete) files or folders with paths greater than some 
260 characters, is unable to handle filenames that differ only in case 
and are in the same directory, and is unable to e.g. delete a folder 
called "con"  --  although such files & folders can very easily be 
created.


You may or may not be aware that some of these things are limitations of
the underlying disc format,


Sorry no, it isn't.

Even assuming you meant the more reasonable "file system", no, it isn't.

Depending on the file system a program may be unable to create such things as I 
mentioned. And depending on the program design it may be reasonable to refuse to 
create them.


But a program should have no trouble deleting the files etc. once they're there.

That's why the Windows API handles them just fine, while Windows Explorer does 
not. You may consider, since you're unfamiliar with the API, that mostly it's no 
problem doing these things in the command interpreter, which has no special 
support (rather, the reason it's easy is because it doesn't properly check 
command arguments). And from that you can deduce that the API support is there.





and some of them limitations of the API.
Laying them at the feet of Windows Explorer is a tad unfair.


Sorry, no. That's where the responsibility is. No other program or API is 
responsible.



In addition to such things impacting on the design and functionality 
of programs even just the tool usage is very complex and runs to a 
great many pages.


That rather depends on what tool you're using for what purpose.  Tools
which require stonking amounts of flagging or button-pressing for simple
uses are IMHO bad tools.  Most IDEs fall into this category.  If your
tools make simple things hard, stop recommending them to people and get
better tools.

For example, for general tool usage in Windows the student needs to 
know about levels of environment variable specifications and file 
associations, which in turn requires knowledge of processes and the 
Windows registry database and various commands.


Mercifully this is rubbish.  For most purposes with most tools even
Windows users don't need to know much if anything about environment
variables and the registry.  Needing to know anything about the
registry is usually a sign that Windows has stuffed you up royally.


I deduce that you mainly use IDEs and don't know about the things you're 
commenting on here (more than you did above). Sorry, but there it is.




* Martin P. Hellwig:
I don't think it is a virtue to help adding to the pool of 
programmers unaware of the command line, whatever platform that might 
be.


This comment baffles me.


The fact that you can say this and write "How to program" books
terrifies me.  Don't make me compare you to Herbert Schildt!


I'm sorry but you haven't written anything correct in this article.


Cheers & hth.,

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread alex23
kj  wrote:
> As my Python apps grow in complexity and execution, I'm finding it
> more often the situation in which a program dies after a lengthy
> (i.e. expensive) run because the execution reaches, say, a typo.

This is a good reason for breaking your program down into testable
units and verifying they behave as expected before a long execution
phase. You can get a long way with unittest in the stdlib, but I
personally prefer using nose[1], I find the tests to be less weighty
in boilerplate.

1: http://code.google.com/p/python-nose/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* bartc:


"Alf P. Steinbach"  wrote in message 
news:hc8pn3$dd...@news.eternal-september.org...

[Cross-posted comp.programming and comp.lang.python]


I may finally have found the perfect language for a practically 
oriented introductory book on programming, namely Python.


C++ was way too complex for the novice, JScript and C# suffered from 
too fast-changing specifications and runtime environment, Java, well, 
nothing particularly wrong but it's sort of too large and unwieldy and 
inefficient.


I don't know whether this will ever become an actual book. I hope so!

But since I don't know much Python -- I'm *learning* Python as I write 
--  I know that there's a significant chance of communicating 
misconceptions, non-idiomatic ways to do things, bad conventions, 
etc., in addition to of course plain errors of fact and understanding 
in general, to which I'm not yet immune...


So I would would be very happy for feedback.


Have you ever done technical writing before? With positive feedback?


Yes, and yes.


You use the highly commercial-looking activatestate website; what's 
wrong with www.python.org?


I guess "commercial looking" is something negative.

Please note regarding the question: I'm not a telepath. I don't know what you 
think is wrong with [www.python.org]. And I have no interest in evaluating the 
site for you, at least not unless you pay me for that job.



You say elsewhere that you're not specifically teaching Python, but the 
text is full of technical details specific to both Python


Yes. A programming language is required to do programming. Can't do without it, 
sorry.



and Windows, 




not much actual programming!


Hm. There's /only/ programming in there and nothing else so far. But given that 
you think programming can be done without a programming language, I hypothesize 
that there is something to learn for you about what programming is. :-)



Python has a lot of baggage which is OK if that's what's going to be 
used, but otherwise is unnecessary confusion: where to put the program 
code (typed in live or in a file, or some combination); whether to call 
the file .py or .pyw; the difference between console and graphical 
programs and so on.


Well.


Cheers & hth.,

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


Re: list comprehension problem

2009-10-29 Thread Nick Stinemates

> Some objects are singletons, ie there's only ever one of them. The most
> common singleton is None. In virtually every other case you should be
> using "==" and "!=".

Please correct me if I am wrong, but I believe you meant to say some 
objects are immutable, in which case you would be correct.

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


self.__dict__ tricks

2009-10-29 Thread Tim Johnson
This is not a request for help but a request for comments:
Consider the following code and note that
1)The initializer uses the dictionary style of arguments
2)The check loop executes before all of the class variables
  are declared
## 
class formLoader():
def __init__(self,**kw):
self.fileName = None
self.record = None
self.string = None
## Uncomment below to see that only fileName, record and string
## are recorded by __dict__
#std.debug("self.__dict__",self.__dict__) 
for k in kw.keys():
if k in self.__dict__:
self.__dict__[k] = kw[k]
else:
raise AttributeError("%s is not a class member. 
Use one of ('%s')"
   % (repr(k),"', 
'".join(self.__dict__.keys(
self.tokens = 
["form","input","textarea","select","option","form"]
self.inputTypes = 
["button","checkbox","file","hidden","image","password",
   "radio","reset","submit","text"]
self.inputValTypes = ["file","hidden","password","text"]
   
self.colnames = []  ## case-insensitive column names
self.formIndexes = []   ## Index forms in outer list
## .
## 
Now if I were to code something like the following:
fml = formLoader(fileName=doc,tokens="tim")
## Note that `tokens' is passed as a named argument.
I get the following error message:
AttributeError: 'tokens' is not a class member. Use one of ('record',
'string', 'fileName')

I am not complaining! This is a good thing and a cool idiom.
Placing the the check loop after _only_ the keywords that I wanted to
allow _disallows_ any others.
I'd welcome comments - such as any other applications.

Always a newbie 
-- 
Tim 
t...@johnsons-web.com
http://www.akwebsoft.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modify dict/set during iteration?

2009-10-29 Thread Paul Rubin
metal  writes:
> I used this quickndirty way, any good idea to solve this problem?

That's really ugly.  Why would you want to do a thing like that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Modify dict/set during iteration?

2009-10-29 Thread metal
I used this quickndirty way, any good idea to solve this problem?

def miter(iterable):
cache = set()
while True:
try:
for x in iterable:
if x not in cache:
cache.add(x)
yield x
break
except RuntimeError, e:
# Not sure if there were any other RuntimeError
if 'changed size during iteration' in e.message:
continue
raise

s = set([1, 2, 3, 5, 6, 7])
for x in miter(s):
start, stop = x, x+1
while start-1 in s:
start -= 1
while stop in s:
stop += 1
for i in range(start, stop):
s.discard(i)
print '[%d:%d]' % (start, stop)

d = {'foo':1}
for x in miter(d):
if x == 'foo':
d['bar']=1
print x

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


Re: Are *.pyd's universal?

2009-10-29 Thread Robert Kern

Philip Semanchuk wrote:


On Oct 29, 2009, at 8:41 PM, Christian Heimes wrote:


Lawrence D'Oliveiro schrieb:
In message , 
Christian

Heimes wrote:


On Linux and several other Unices the suffix is .so and not .pyd.


Why is that? Or conversely, why isn't it .dll under Windows?


.so is the common suffix of shared libraries on Linux. IIRC Python
extensions have .pyd on Mac OS X.


I've never seen a .pyd under OS X (although that doesn't mean they don't 
exist).


The Python extensions I've written in C compile to a .so under OS X.


This is true of all Python extensions on OS X. .pyd is only used on Windows.

--
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

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


Re: ftpilb.FTP.stor...() freeze mystery

2009-10-29 Thread Gabriel Genellina
En Thu, 29 Oct 2009 13:18:30 -0300, Anthra Norell  
 escribió:



Gabriel Genellina wrote:
En Wed, 28 Oct 2009 08:05:22 -0300, Anthra Norell  
 escribió:

Gabriel Genellina wrote:

En Tue, 27 Oct 2009 07:53:36 -0300, Anthra Norell
 escribió:

I am trying to upload a bunch of web pages to a hosting  
service.[...]  I wrote a loop that iterates through the file names  
and calls either of the stor... () methods as appropriate. The loop  
successfully uploads eight of some twenty files and then freezes.  
Ctrl-C doesn't unlock the freeze. I have to kill the IDLE window


freezes are less predictable than it seemed in the beginning. On one  
occasion it occurred after the transfer of a single file from the IDLE  
command line (my_ftp_object.storlines ("STOR file_name", f). The file  
did upload. So the freezes seem to occur after a successful transfer.


In this thread from last month, Sean DiZazzo shows how to add a timeout  
parameter to storbinary:

http://comments.gmane.org/gmane.comp.python.general/639258
Do the same with storlines and see whether it helps.

Thanks a million! Here's a way out by the look of it. As the devil is in  
the details I get an error that indicates an inconsistency in my ftplib  
library (2.4) (*** marks my comments):


Traceback (most recent call last):
 File "", line 1, in -toplevel-
   d2jm = upload.run (1)
 File "I:/DOK/projects/WEB/JM\upload.py", line 369, in run
   D2JM.copy_1_2 (do)
 File "I:/DOK/projects/WEB/JM\upload.py", line 342, in copy_1_2
   try: self.FS2.storbinary ('STOR %s' % name, f, timeout = timeout)
*** Here's the call to the overwritten method with the timeout.

 File "I:/DOK/projects/WEB/JM\upload.py", line 440, in storbinary
   self.connection = self.transfercmd (command)   *** command is 'STOR  
(target file name)'. Control passes to ftplib

 File "C:\PYTHON24\lib\ftplib.py", line 345, in transfercmd
   return self.ntransfercmd(cmd, rest)[0]
 File "C:\PYTHON24\lib\ftplib.py", line 321, in ntransfercmd
   host, port = self.makepasv()
 File "C:\PYTHON24\lib\ftplib.py", line 299, in makepasv
   host, port = parse227(self.sendcmd('PASV'))
 File "C:\PYTHON24\lib\ftplib.py", line 566, in parse227
   raise error_reply, resp
error_reply: 200 TYPE is now 8-bit binary   <*** 'is now' indicates  
something has changed resulting in an inconsistency


Is 'resp' supposed to be an int (227) rather than a string ('227')?  
Probably a wrong conclusion. In version 2.5 it is still a string.  
Anyway, I can't start editing the library trial-and-error style. So, I  
do thank you for the push. Mores pushes will be greatly appreciated, but  
I hesitate to invite travel companions for a stroll into this wilderness.


resp is a string, but not the response that PASV expected; apparently the  
server is sending some unexpected responses.  r52739 seems to fix that.  
Perhaps you should upgrade to a newer Python version.


http://svn.python.org/view?view=rev&revision=52739

--
Gabriel Genellina

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


Re: Checking if a function invocation will throw a TypeError?

2009-10-29 Thread Andrey Fedorov
Will do, thanks. Doing it to make a @curry decorator, which only executes a
function once enough arguments have been passed in.

- Andrey

On Thu, Oct 29, 2009 at 6:53 PM, Chris Rebert  wrote:

> On Thu, Oct 29, 2009 at 11:43 AM, Andrey Fedorov 
> wrote:
> > Is there a standard function that will check whether certain *args, and
> > **kwargs satisfy a argspec of a function (s.t. it does not throw a
> > TypeError). Say:
> >
> > def foo(a,b=1):
> > pass
> >
> > check(foo, 1,2) # True
> > check(foo, 1) # True
> > check(foo) # False
> > check(foo, 1, a=2) # False
>
> Not that I know of, but you can write one yourself using
> inspect.getargspec():
> http://docs.python.org/library/inspect.html#inspect.getargspec
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: '11' + '1' is '111'?

2009-10-29 Thread MRAB

Benjamin Peterson wrote:

metal  gmail.com> writes:


'11' + '1' == '111' is well known.

but it suprises me '11'+'1' IS '111'.

Why? Obviously they are two differnt object.

Is this special feature of imutable object?


As other posters have pointed out, CPython does cache some small strings. In
this case, however, it's because '1' + '11' is constant folded.


It's also easy to fool the constant folding:

>>> '11' + '1' is '111'
True
>>> '11' * 1 + '1' is '111'
True
>>> '11' + '1' * 1 is '111'
False
--
http://mail.python.org/mailman/listinfo/python-list


Re: '11' + '1' is '111'?

2009-10-29 Thread metal
On 10月30日, 上午9时03分, Benjamin Peterson  wrote:
> metal  gmail.com> writes:
>
>
>
> > '11' + '1' == '111' is well known.
>
> > but it suprises me '11'+'1' IS '111'.
>
> > Why? Obviously they are two differnt object.
>
> > Is this special feature of imutable object?
>
> As other posters have pointed out, CPython does cache some small strings. In
> this case, however, it's because '1' + '11' is constant folded.

You are right. It's not cache, just constant folding, but it does not
propagate further.

a = '1'
a+a is not a+a

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


Re: '11' + '1' is '111'?

2009-10-29 Thread John Machin
On Oct 30, 11:52 am, Benjamin Kaplan  wrote:
> On Thu, Oct 29, 2009 at 8:43 PM, metal  wrote:
> > '11' + '1' == '111' is well known.
>
> > but it suprises me '11'+'1' IS '111'.
>
> > Why? Obviously they are two differnt object.
>
> > Is this special feature of imutable object?
>
> It's an implementation detail of small strings without spaces and
> small numbers. You're more likely to reuse those values, so Python
> caches them. You shouldn't rely on it. It's not guaranteed to stay the
> same between different implementations, or even different versions of
> CPython.

It also relies on the implementation detail that the CPython bytecode
has peephole optimisation applied to it:

| Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit
(Intel)] on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> def foo():
| ...return '11' + '1' is '111'
| ...
| >>> import dis
| >>> dis.dis(foo)
|   2   0 LOAD_CONST   4 ('111')
|   3 LOAD_CONST   3 ('111')
|   6 COMPARE_OP   8 (is)
|   9 RETURN_VALUE
| >>> def bar():
| ...a = '11'
| ...b = '1'
| ...return a + b is '111'
| ...
| >>> dis.dis(bar)
|   2   0 LOAD_CONST   1 ('11')
|   3 STORE_FAST   0 (a)
|
|   3   6 LOAD_CONST   2 ('1')
|   9 STORE_FAST   1 (b)
|
|   4  12 LOAD_FAST0 (a)
|  15 LOAD_FAST1 (b)
|  18 BINARY_ADD
|  19 LOAD_CONST   3 ('111')
|  22 COMPARE_OP   8 (is)
|  25 RETURN_VALUE
| >>> foo()
| True
| >>> bar()
| False
| >>>

In general, whether (expression1 is expression2) is true or false is
not useful knowledge when the expressions result in "scalars" like
str, int, float.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Rhodri James
On Thu, 29 Oct 2009 16:53:05 -, Alf P. Steinbach   
wrote:


There's rather a lot to know about the environment that a program  
executes in if one is going to create robust, dependable, generally  
usable programs, not just toy examples.


I'd say this was at best an extremely misleading statement.  The robust,
dependable, usable, low-fat, carcinogen-free programs that I've written
fall into two categories; either they are embedded programs whose
environment is the silicon they're running on pretty much literally, or
they carefully *don't* know about their environment so run equally
effectively everywhere.  It's the programs that do know about their
environment and go on to make assumptions about it that turn out
not to be robust, dependable, or very often usable.

Unfortunately even most professional programs do not handle the  
requirements of their environs very well, and I think that educators,  
even such as I, have a responsibility to now start teaching students to  
do things right. To take but one example that you may or may not be  
aware of, Microsoft's own Windows Explorer, the main GUI shell for  
Windows, which presumably was made by the best programmers available


Bwahahahahahahaha.

Uh, sorry.  I know that wasn't terribly nice, but the politest answer
I can think of that gets over the utter wrongness of this assumption is
"Hell, no."

with the best knowledge of the program's environment, is unable to  
handle (such as delete) files or folders with paths greater than some  
260 characters, is unable to handle filenames that differ only in case  
and are in the same directory, and is unable to e.g. delete a folder  
called "con"  --  although such files & folders can very easily be  
created.


You may or may not be aware that some of these things are limitations of
the underlying disc format, and some of them limitations of the API.
Laying them at the feet of Windows Explorer is a tad unfair.

In addition to such things impacting on the design and functionality of  
programs even just the tool usage is very complex and runs to a great  
many pages.


That rather depends on what tool you're using for what purpose.  Tools
which require stonking amounts of flagging or button-pressing for simple
uses are IMHO bad tools.  Most IDEs fall into this category.  If your
tools make simple things hard, stop recommending them to people and get
better tools.

For example, for general tool usage in Windows the student needs to know  
about levels of environment variable specifications and file  
associations, which in turn requires knowledge of processes and the  
Windows registry database and various commands.


Mercifully this is rubbish.  For most purposes with most tools even
Windows users don't need to know much if anything about environment
variables and the registry.  Needing to know anything about the
registry is usually a sign that Windows has stuffed you up royally.


* Martin P. Hellwig:
I don't think it is a virtue to help adding to the pool of programmers  
unaware of the command line, whatever platform that might be.


This comment baffles me.


The fact that you can say this and write "How to program" books
terrifies me.  Don't make me compare you to Herbert Schildt!

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: '11' + '1' is '111'?

2009-10-29 Thread Benjamin Peterson
metal  gmail.com> writes:

> 
> '11' + '1' == '111' is well known.
> 
> but it suprises me '11'+'1' IS '111'.
> 
> Why? Obviously they are two differnt object.
> 
> Is this special feature of imutable object?

As other posters have pointed out, CPython does cache some small strings. In
this case, however, it's because '1' + '11' is constant folded.



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


Re: '11' + '1' is '111'?

2009-10-29 Thread metal
On 10月30日, 上午8时49分, Chris Rebert  wrote:
> On Thu, Oct 29, 2009 at 5:43 PM, metal  wrote:
> > '11' + '1' == '111' is well known.
>
> > but it suprises me '11'+'1' IS '111'.
>
> > Why? Obviously they are two differnt object.
>
> > Is this special feature of imutable object?
>
> It's an implementation detail used to optimize performance. CPython
> caches certain small strings and returns the same object when asked
> for a string with identical content to one in the cache, thus the
> behavior you're observing.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

True, '1'*1000 IS NOT '1'*999+'1'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.6 + win32com crashes with unicode bug

2009-10-29 Thread John Machin
On Oct 30, 11:11 am, Terry Reedy  wrote:
> GerritM wrote:
[snip]
> >   File "C:\Python26\lib\site-packages\win32com\client\build.py", line
> > 542, in 
> >     return filter( lambda char: char in valid_identifier_chars, className)
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52:
> > ordinal not in range(128)
>
> I suspect that 2.6 fixed the bug of allowing non-ascii chars when using
> the ascii codec.  I would check to see if there is an 0x83 in
> D:/temp/test.vsd

  Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
(Intel)] on win32
  Type "help", "copyright", "credits" or "license" for more
information.
  >>> '\x83'.decode('ascii')
  Traceback (most recent call last):
File "", line 1, in 
  UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in
position 0: ordinal not in range(128)
  >>>

What bug??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: '11' + '1' is '111'?

2009-10-29 Thread Benjamin Kaplan
On Thu, Oct 29, 2009 at 8:43 PM, metal  wrote:
> '11' + '1' == '111' is well known.
>
> but it suprises me '11'+'1' IS '111'.
>
> Why? Obviously they are two differnt object.
>
> Is this special feature of imutable object?

It's an implementation detail of small strings without spaces and
small numbers. You're more likely to reuse those values, so Python
caches them. You shouldn't rely on it. It's not guaranteed to stay the
same between different implementations, or even different versions of
CPython.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are *.pyd's universal?

2009-10-29 Thread Philip Semanchuk


On Oct 29, 2009, at 8:41 PM, Christian Heimes wrote:


Lawrence D'Oliveiro schrieb:
In message ,  
Christian

Heimes wrote:


On Linux and several other Unices the suffix is .so and not .pyd.


Why is that? Or conversely, why isn't it .dll under Windows?


.so is the common suffix of shared libraries on Linux. IIRC Python
extensions have .pyd on Mac OS X.


I've never seen a .pyd under OS X (although that doesn't mean they  
don't exist).


The Python extensions I've written in C compile to a .so under OS X.

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


Re: '11' + '1' is '111'?

2009-10-29 Thread Chris Rebert
On Thu, Oct 29, 2009 at 5:43 PM, metal  wrote:
> '11' + '1' == '111' is well known.
>
> but it suprises me '11'+'1' IS '111'.
>
> Why? Obviously they are two differnt object.
>
> Is this special feature of imutable object?

It's an implementation detail used to optimize performance. CPython
caches certain small strings and returns the same object when asked
for a string with identical content to one in the cache, thus the
behavior you're observing.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


'11' + '1' is '111'?

2009-10-29 Thread metal
'11' + '1' == '111' is well known.

but it suprises me '11'+'1' IS '111'.

Why? Obviously they are two differnt object.

Is this special feature of imutable object?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are *.pyd's universal?

2009-10-29 Thread Christian Heimes
Lawrence D'Oliveiro schrieb:
> In message , Christian 
> Heimes wrote:
> 
>> On Linux and several other Unices the suffix is .so and not .pyd.
> 
> Why is that? Or conversely, why isn't it .dll under Windows?

.so is the common suffix of shared libraries on Linux. IIRC Python
extensions have .pyd on Mac OS X. On Windows it used to be .dll, too.
The suffix was changed to avoid issues with other dlls and name clashes.

Christian

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


Re: How to get a unique function name for methods

2009-10-29 Thread Terry Reedy

Philip Guo wrote:

Hi all,

This is my first post, so sorry for the n00bish question.  Let's say I 
have 2 classes with the same __init__ method defined in a file foo.py:


class A:
  def __init__(self):
pass

class B:
  def __init__(self):
pass

For the purpose of a code analysis, I need to get a UNIQUE name for each 
of the two __init__ methods.  In the Python code object, i can get 
co_name and co_filename, which returns me the method name and filename, 
respectively, but NOT the enclosing classname.  This is a problem since 
both A.__init__ and B.__init__ will show up as {co_name: "__init__", 
co_filename: "foo.py"} in my analysis.  Ideally, I want to distinguish 
them by their class names:


{co_name: "__init__", co_filename: "foo.py", classname: "A"}
{co_name: "__init__", co_filename: "foo.py", classname: "B"}

(Simply using their line numbers isn't gonna work for me, I need their 
class names.)


Does anyone know how to get this information either from a code object 
or from a related object?  I am hacking the interpreter, so I have full 
access to everything.


I do not quite understand your question. 1) a method is simply a 
function accessed as a class attribute. Like all attributes, methods do 
not really belong to any particular class, even if they look like they 
do. 2) if you access a function as a class attribute, as I presume you 
did, then you already know the class.


If you are asking "How to I recover class info after discarding it?", 
then the answer is "You can't, don' discard the info!".


Terry Jan Reedy

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


Re: Are *.pyd's universal?

2009-10-29 Thread Lawrence D'Oliveiro
In message , Christian 
Heimes wrote:

> On Linux and several other Unices the suffix is .so and not .pyd.

Why is that? Or conversely, why isn't it .dll under Windows?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Ben Finney
Albert Hopkins  writes:

> On Thu, 2009-10-29 at 17:27 -0500, Robert Kern wrote:
> > I consider "import *" the first error to be fixed, so it doesn't
> > bother me much. :-)
>
> But does pyflakes at least *warn* about the use of "import *" (I've
> never used it so just asking)?

That's easy enough to check:

=
$ cat namespace_clobber.py
from foo import *

$ pyflakes namespace_clobber.py 
namespace_clobber.py:1: 'from foo import *' used; unable to detect undefined 
names
=

-- 
 \“There are no significant bugs in our released software that |
  `\ any significant number of users want fixed.” —Bill Gates, |
_o__)   1995-10-23 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.6 + win32com crashes with unicode bug

2009-10-29 Thread Terry Reedy

GerritM wrote:
I have automated image generation with Python, win32com and Visio5.0. 
This works well upto Python2.5 but fails with Python 2.6.

Short term solution is to return to 2.5 :-(.

I have reproduced the bug below with a minimum of Python lines. Below 
the problem the working example from 2.5


kind regards, Gerrit

---minimal session reproducing the bug---

Python 2.6.3 (r263:75183, Oct  5 2009, 14:41:55) [MSC v.1500 32 bit 
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 2.6.3
 >>> from win32com.client.dynamic import Dispatch
 >>> v = Dispatch("Visio.Application")
 >>> d = v.Documents.OpenEx("D:/temp/test.vsd",8)

Traceback (most recent call last):
  File "", line 1, in 
d = v.Documents.OpenEx("D:/temp/test.vsd",8)
  File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 
467, in __getattr__
if self._olerepr_.mapFuncs.has_key(attr): return 
self._make_method_(attr)
  File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 
295, in _make_method_
methodCodeList = 
self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
297, in MakeFuncMethod

return self.MakeDispatchFuncMethod(entry, name, bMakeClass)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
318, in MakeDispatchFuncMethod
s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, 
names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):'
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
604, in BuildCallList

argName = MakePublicAttributeName(argName)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
542, in MakePublicAttributeName

return filter( lambda char: char in valid_identifier_chars, className)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
542, in 

return filter( lambda char: char in valid_identifier_chars, className)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: 
ordinal not in range(128)


I suspect that 2.6 fixed the bug of allowing non-ascii chars when using 
the ascii codec.  I would check to see if there is an 0x83 in 
D:/temp/test.vsd




---no problem with 2.5---
Python 2.5 (r25:51908, Mar  9 2007, 17:40:28) [MSC v.1310 32 bit 
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2
 >>> from win32com.client.dynamic import Dispatch
 >>> v = Dispatch("Visio.Application")
 >>> d = v.Documents.OpenEx("D:/temp/test.vsd",8)
 >>>

---configuration data---
Windows XP SP3
ASUS 1106HA (11.6" EEE PC)
Visio 5.0


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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Albert Hopkins
On Thu, 2009-10-29 at 17:27 -0500, Robert Kern wrote:
> I consider "import *" the first error to be fixed, so it doesn't
> bother me much. :-)

But does pyflakes at least *warn* about the use of "import *" (I've
never used it so just asking)?



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


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread metal
The actual situation is I'm coding with a immuable set-like datatype
XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax'] if I
declare ax is consists of al and ah

"That" means I can't explian it very well 'cause my english...

Now I try to make some mess like this...I know it's not good to wrap
all methods...I just try to make code looks good

class MyMeta(type):
def __init__(cls, name, bases, namespace):
type.__init__(cls, name, bases, namespace) # needed?
cls.wrap_methods()
def methods(cls):
return [k for k, v in cls.__dict__.items() if callable(v)]
def wrap_methods(cls):
for k in cls.methods():
f = cls.__dict__[k]
def g(self, *v, **k):
rv = f(self, *v, **k)
if rv.__class__ is cls:
rv = self.__class__()
rv.__dict__.update(self.__dict__)
return rv
setattr(cls, k, g)

class Parent(object):
__metaclass__ = MyMeta # I prefer class decorator, but I'm using
Py2.5
def some_method(self):
return Parent()

class Child(Parent):
pass

print Child().some_method()

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


Re: Win XP: How to hide command window for sub processes?

2009-10-29 Thread klausfpga
On Oct 29, 11:25 am, Rüdiger Ranft <_r...@web.de> wrote:
> klausfpga schrieb:
>
> > Hi,
>
> > I have a Python script which wants to start a subprocess and wait for
> > it to finish.
>
> > However I would like to have NO command window popping up during
> > execution.
>
> You need to specify the hide parameter for windows.
>
> import subprocess
> kwargs = {}
> if subprocess.mswindows:
>     su = subprocess.STARTUPINFO()
>     su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
>     su.wShowWindow = subprocess.SW_HIDE
>     kwargs['startupinfo'] = su
> process = subprocess.Popen( (r'c:\python25\python.exe',
>     r'd:\projekte\bar.py'), **kwargs )

Thanks Ruediger,

I'll try that immediately tomorrow, when working again on a windows
host.

Good to know, that the Python API supports this.
though this feature was not that easy to be found in the doc.

This will make my application much nicer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 Global Variables

2009-10-29 Thread Benjamin Kaplan
On Thu, Oct 29, 2009 at 7:11 PM, AK Eric  wrote:
>> Good that you're not advocating it, because IMHO it's bad practice to
>> have circular import dependencies.  By using the __main__ alias, you
>> avoid the worst problems, but that just means the others are more subtle.
>
> I figured I'd get that kind of response, not that it's incorrect ;)
> Great power\great responsibility\etc.
>
> As I understand it, when you enter Python statements at the
> interactive prompt, it's adding the result directly to ___main___
> (which for lack of a better term I like to call 'universal' scope...
> rolls off the tongue better than 'doubleunderscore main
> doubleunderscore'):
>
 foo = 23
 import __main__
 print __main__.foo
> 23
>
> While this might not be the most common way of working for most people
> (I'm guessing most folks are in a nice cozy IDE), people working this
> way are mucking about in the 'universal' scope without (possibly) even
> knowing it.
> --

Or, you could use any other random module for this like, say, a module
made specifically for this purpose and given a name like "config.py"
or "settings.py" or something like that which describes what you're
using it for. You don't have a "universal" scope- it's the
module-level scope of the script that is actually run (or the
interactive interpreter in this case).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread Dave Angel

metal wrote:

Consider the following:


class Parent:
def some_method(self):
return Parent(...)
class Child:
def some_method(self):
...
return Parent.some_method(self)


Or Simply:


class Parent:
def some_method(self):
return Parent(...)
class Child:
pass


Child().some_method() returns a Parent instance.

We can rewrite Parent like this to avoid that


class Parent:
def some_method(self):
return self.__class__(...)
class Child:
def some_method(self):
...
return Parent.some_method(self)


But this style makes code full with ugly  self.__class__

Any standard/pythonic way out there?


  
You need to do a few things here. 
1) tell us what version of Python you're targeting, and whether these 
are old-style or new-style classes you're trying to define.


2) Actually show the class declaration completely.  Currently you don't 
show the (object) or the (Parent) base class declarations.


3) Explain what the desired goal is.  Using a phrase like "rewrite 
Parent like this to avoid that" implies that I already know what 
particular "that" has you bothered.


4) If you post multiple similar code blocks, label them somehow, so we 
have a way to refer to them unambiguously.


With my present guesses, the definition of some_method() in the third 
declaration of Child would seem to be redundant.


DaveA

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


Re: Newbie advice

2009-10-29 Thread CSharpner
On Oct 29, 1:08 pm, Bryan  wrote:
> On Oct 28, 9:53 pm,CSharpner wrote:
>
>
>
> > Alright, I'm not new to programming, but I'm diving in head first into
> > Python for the first time.  I'm running on Windows 7, just installed
> > "Eclipse Java EE IDE for Web Developers" and installed PyDev in it and
> > installed Python 2.6.  I've written my first "Hello World" program,
> > which simply displays "Hello World!" in the console output.
>
> > Here's what I /want/ to do, but don't know where to begin:
>
> > - Write web services in Python (I've done plenty of this in .NET,
> > BTW).
> > - Write plain DLLs (is that even an option in Python (I told you I was
> > a newb to Python, didn't I? :))
> > - Write a web app (HTML front end, Python web services called from
> > JavaScript).
> > - Write a plain old web app with Python (no web services or Ajax, just
> > plain HTML & Python).
> > - Is it possible to create a Windows client desktop GUI app with
> > Python?  How?  How 'bout a Linux GUI app?
>
> > I don't know how to create and write a Python project with Eclipse to
> > tell it to "be" a web service or a web app, or if what I need to do in
> > the code to make as such, no "run" it from Eclipse to launch the app
> > in a web server and launch a browser automatically.  Can I debug after
> > doing this?  In other words, can I put break points in my web services
> > or web apps and go back into the IDE to step through the code for web
> > services and web apps?
>
> > Also, I'm not tied to Eclipse.  I'm totally open to other IDEs as
> > well.  SharpDevelop with the Python plugin looks interesting too.
>
> > And finally, I'm not completely committed to using Windows to host my
> > development either.  I'm willing to use Linux too (but would prefer
> > Windows... at least to get started, until I'm comfortable enough with
> > Python).
>
> > TIA
>
> I first started coding using Visual Studio + VB.net in college (not a
> CS major).  I have now sworn off all that jazz for python+vim+*nix.
> Your thinking reminds me very much of how I used to think about
> solving problems with software.  I thought in terms of the tools I
> had, which was basically which VS templates were available, which GUI
> widget library I could buy, which MS application framework I could use
> etc.
>
> At some point I decided to start all over.  I started reading *basic*
> computer programming books, teaching myself C, and doing all coding in
> a simple text editor.  It was a tough period but I'm glad I went
> through it because I think about programming completely differently
> now.  Now a programming language is mostly an implementation detail.
> I design the solution without even thinking about programming
> languages or tools.  I choose to implement most solutions in python
> because its syntax describes what I want to do the cleanest, its not
> tied to a corporate strategy, it has tons of useful libraries bla bla
> bla.
>
> This post describes the IDS vs language divide that I crossed 
> over:http://osteele.com/archives/2004/11/ides
>
> Python can do everything you ask in your post, and their are many
> resources to help you do those things.  I just wanted to give you some
> advice for the bigger picture.
>
> Bryan

Thanks Bryan.  Though my post may have misled. I feel the same way.  I
started out on text editor source editing because that's all we had
back in the early 80's with the old 8-bits.  Actually, line editor
editing is what I started on... enter one line at a time and it's
"entered"... couldn't even cursor up and down...  Before I had an
assembler, I'd write assembly programs with /machine/ code, hex byte
by hex byte.  Was pretty cryptic by today's standards, but waaay fun.
Anyway, your points are right on and I'm glad to see you have moved in
this direction, though I'd encourage you not to dismiss tools that can
make your job easier too.  Take it from someone who went through all
of it from hex byte editing up through the latest IDEs:  You don't
want to forsake the tools that can reduce your workload.  You'll be
more valuable.  You don't want to be completely dependent on them
either, of course, but I know I don't have to tell you /that/ because
you're clearly not dependent on them.

My questions were more geared towards:  I know code isn't just a "web
service" because I will it and it doesn't "connect" with a browser
(for lack of a better term) because I wish it.  There are steps to be
taken to make those happen.  I'm merely querying "what are they?".

Having said that and agreeing with your premise, I will say that after
having used dozens of languages, technologies, architectures, tools,
etc... over the last 27 years, at the end of the day, I have to
produce for the people paying me, so I won't /avoid/ "tools", for
sure.  If there's anything I can use to get my product out earlier and/
or help produce more robust code and more maintainable code for the
folks that come in behind me, you can bet your favorite, sweet text
editor, I'll us

Re: : yappi v0.2 beta

2009-10-29 Thread Aahz
In article <90507058-c366-4650-9e81-381cbbdaa...@k19g2000yqc.googlegroups.com>,
Oktaka Com   wrote:
>
>Forgot to give the project web page:) Here it is:
>
>http://code.google.com/p/yappi/

Looks interesting, but I think I'll wait until the docs are a bit more
mature.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread Rhodri James

On Thu, 29 Oct 2009 22:45:45 -, metal  wrote:


Consider the following:


[fixed to actually inherit...]



class Parent:
def some_method(self):
return Parent(...)
class Child(Parent):
pass


Child().some_method() returns a Parent instance.

We can rewrite Parent like this to avoid that


class Parent:
def some_method(self):
return self.__class__(...)
class Child(Parent):
def some_method(self):
return Parent.some_method(self)


But this style makes code full with ugly  self.__class__

Any standard/pythonic way out there?


That's a perfectly good way to do it.  If __class__ really
offends you that much, wrap it in another (probably static)
method:

class Parent(object):
  def some_method(self):
return self.another_one(...)

  @staticmethod
  def another_one(...):
return Parent(...)

class Child(Parent):
  def some_method(self):
return Parent.some_method(self)

  @staticmethod
  def another_one(...):
return Child(...)

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Ben Finney
a...@pythoncraft.com (Aahz) writes:

> Coincidentally, I tried PyFlakes yesterday and was unimpressed with
> the way it doesn't work with "import *".

That's pretty much the reason to avoid ‘from foo import *’: it makes the
namespace indeterminate without actually running the code. Just as much
a problem for the human reader as for a reader like ‘pyflakes’.

But you knew that already.

-- 
 \“Humanity has advanced, when it has advanced, not because it |
  `\ has been sober, responsible, and cautious, but because it has |
_o__)been playful, rebellious, and immature.” —Tom Robbins |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommended number of threads? (in CPython)

2009-10-29 Thread Dave Angel

Paul Rubin wrote:

Neil Hodgson  writes:
  

   If you are running on a 32-bit environment, it is common to run out
of address space with many threads. Each thread allocates a stack and
this allocation may be as large as 10 Megabytes on Linux. 



I'm sure it's smaller than that under most circumstances.  I run
python programs with hundreds of threads all the time, and they don't
use gigabytes of memory.

  
As Neil pointed out further on, in the same message you quoted, address 
space is not the same as allocated memory.  It's easy to run out of 
allocatable address space long before you run out of virtual memory, or 
swap space.


Any time a buffer is needed that will need to be contiguous (such as a 
return stack), the address space for the max possible size must be 
reserved, but the actual virtual memory allocations (which is what you 
see when you're using the system utilities to display memory usage) are 
done incrementally, as needed.


It's been several years, but I believe the two terms on Windows are 
"reserve" and "commit."  Reserve is done in multiples of 64k, and commit 
in multiples of 4k.


DaveA

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


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread Chris Rebert
On Thu, Oct 29, 2009 at 3:45 PM, metal  wrote:
> Consider the following:

> class Parent:
>        def some_method(self):
>                return Parent(...)
> class Child:
>        pass
> 
>
> Child().some_method() returns a Parent instance.
>
> We can rewrite Parent like this to avoid that
>
> 
> class Parent:
>        def some_method(self):
>                return self.__class__(...)
> class Child:
>        def some_method(self):
>                ...
>                return Parent.some_method(self)
> 
>
> But this style makes code full with ugly  self.__class__
>
> Any standard/pythonic way out there?

That pretty much is the standard way AFAIK. A few underscores aren't
all that bad in the grand scheme of things.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 Global Variables

2009-10-29 Thread AK Eric
> Good that you're not advocating it, because IMHO it's bad practice to
> have circular import dependencies.  By using the __main__ alias, you
> avoid the worst problems, but that just means the others are more subtle.

I figured I'd get that kind of response, not that it's incorrect ;)
Great power\great responsibility\etc.

As I understand it, when you enter Python statements at the
interactive prompt, it's adding the result directly to ___main___
(which for lack of a better term I like to call 'universal' scope...
rolls off the tongue better than 'doubleunderscore main
doubleunderscore'):

>>> foo = 23
>>> import __main__
>>> print __main__.foo
23

While this might not be the most common way of working for most people
(I'm guessing most folks are in a nice cozy IDE), people working this
way are mucking about in the 'universal' scope without (possibly) even
knowing it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread Christian Heimes
metal wrote:
> But this style makes code full with ugly  self.__class__
> 
> Any standard/pythonic way out there?

You are already using one standard way to implement an alternative
constructor.

If you don't need any instance attributes you can use another way:

class Egg(object):
@classmethod
def spam(cls):
return cls(...)

Christian

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Richard Heathfield
In , Richard Heathfield 
wrote:

> In <7ku6jhf3a23e...@mid.individual.net>, osmium wrote:

>> 
>> In some cultures, implying that someone is illiterate suggests "not
>> smart".
> 
> I don't see that at all. Babies are illiterate. Nobody knows whether
> they're smart.

Clarification: nobody knows for sure how smart any given baby is, but 
certainly some babies are going to be very smart indeed. Illiteracy 
is clearly not a measure of unsmartness.

When I use the word "illiterate", I am describing, not insulting. 
Likewise, when I use the word "literate", I am describing, not 
praising.

-- 
Richard Heathfield 
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread exarkun

On 09:52 pm, a...@pythoncraft.com wrote:

In article ,
Robert Kern   wrote:


I like using pyflakes. It catches most of these kinds of typo errors, 
but is

much faster than pylint or pychecker.


Coincidentally, I tried PyFlakes yesterday and was unimpressed with the
way it doesn't work with "import *".


Consider it (some very small, I'm sure) motivation to stop using "import 
*", which is itself only something used in unimpressive software. ;)


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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Richard Heathfield
In <7ku6jhf3a23e...@mid.individual.net>, osmium wrote:

> "Richard Heathfield" wrote:
> 
>>> if the OP had just been smarter.
>>
>> Er, no, I didn't have that in mind at all.
> 
> In some cultures, implying that someone is illiterate suggests "not
> smart".

I don't see that at all. Babies are illiterate. Nobody knows whether 
they're smart. In any case, I /said/ "computer-illiterate". Albert 
Einstein was computer-illiterate.

> There is a formal disconnect there but possibly you can see
> how someone might infer that.

I can see how an unsmart person might infer that.

> At least I found out what your choice was, HTML, same as mine.

Naturally. It's the smart person's choice. :-)

-- 
Richard Heathfield 
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a unique function name for methods

2009-10-29 Thread Christian Heimes
Philip Guo wrote:
> Does anyone know how to get this information either from a code object or
> from a related object?  I am hacking the interpreter, so I have full access
> to everything.

Does this help?

>>> class A(object):
... def method(self):
... pass
...
>>> A.method.im_class

>>> A.method.im_class.__module__
'__main__'
>>> A.method.im_class.__name__
'A'
>>> A.method.im_func

>>> A.method.im_func.__name__
'method'
>>> '.'.join((A.method.im_class.__module__, A.method.im_class.__name__, 
>>> A.method.im_func.__name__))
'__main__.A.method'

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


Re: Checking if a function invocation will throw a TypeError?

2009-10-29 Thread Chris Rebert
On Thu, Oct 29, 2009 at 11:43 AM, Andrey Fedorov  wrote:
> Is there a standard function that will check whether certain *args, and
> **kwargs satisfy a argspec of a function (s.t. it does not throw a
> TypeError). Say:
>
> def foo(a,b=1):
>     pass
>
> check(foo, 1,2) # True
> check(foo, 1) # True
> check(foo) # False
> check(foo, 1, a=2) # False

Not that I know of, but you can write one yourself using inspect.getargspec():
http://docs.python.org/library/inspect.html#inspect.getargspec

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 Global Variables

2009-10-29 Thread Dave Angel

AK Eric wrote:

2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.



Isn't that __main__?


import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.

  
Good that you're not advocating it, because IMHO it's bad practice to 
have circular import dependencies.  By using the __main__ alias, you 
avoid the worst problems, but that just means the others are more subtle.


You can make it safe, by carefully avoiding certain constructs.  But 
it's still fragile, in that a minor change in one module of the loop can 
cause either an exception or unexpected behavior.


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


If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

2009-10-29 Thread metal
Consider the following:


class Parent:
def some_method(self):
return Parent(...)
class Child:
def some_method(self):
...
return Parent.some_method(self)


Or Simply:


class Parent:
def some_method(self):
return Parent(...)
class Child:
pass


Child().some_method() returns a Parent instance.

We can rewrite Parent like this to avoid that


class Parent:
def some_method(self):
return self.__class__(...)
class Child:
def some_method(self):
...
return Parent.some_method(self)


But this style makes code full with ugly  self.__class__

Any standard/pythonic way out there?

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Robert Kern

On 2009-10-29 16:52 PM, Aahz wrote:

In article,
Robert Kern  wrote:


I like using pyflakes. It catches most of these kinds of typo errors, but is
much faster than pylint or pychecker.


Coincidentally, I tried PyFlakes yesterday and was unimpressed with the
way it doesn't work with "import *".


I consider "import *" the first error to be fixed, so it doesn't bother me 
much. :-)

--
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

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


Re: PyQT4 user group

2009-10-29 Thread David Boddie
On Thursday 29 October 2009 17:15, Diez B. Roggisch wrote:

> Chris wrote:
> 
>> I'm starting to learn and use PyQT4 at work.  Is there a good user
>> group or forum out there that I should know about?
> 
> The PyQt Mailinglist.

There's a #pyqt IRC channel on Freenode:

irc://irc.freenode.net/pyqt

The Wiki is also a fairly useful resource:

http://www.diotavelli.net/PyQtWiki

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Ethan Furman

Alf P. Steinbach wrote:

* Ethan Furman:


Alf P. Steinbach wrote:


* James Harris:


You get way too deep into Python in places (for a beginner's course in
programming). For example, "from now on I’ll always use from
__future__ in any program that uses print."


Sorry, but I think that hiding such concerns is a real disservice.


The disservice is in teaching folks to use non-standard elements, 
which is (sort-of) what __future__ is.  Changes to the language are 
experimented with in __future__ and can change from one release to the 
next.  If memory serves, the with statement is an example of having 
different behavior when it was moved out of __future__ and made a 
standard part of the language.


That's a bit of a straw man argument. 


You don't agree, so it's a straw man?  You didn't know, and when the 
information is pointed out, it's a straw man?


I used "from __future__" to write 
forward-compatible calls of print, so that those examples would not 
mysteriously work or not depending on the Python version. 


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import print_function
  File "", line 1
SyntaxError: future feature print_function is not defined

Hmmm... Doesn't seem to work in 2.5.  So much for not working on a 
different version.


I did not use 
it to access experimental features.


From what I've seen of your posts so far, you wouldn't have known if 
the print in __future__ was slightly different from the actual print in 
3.x anyway.


However, I didn't know then that the language has changed so much in 3.x 
that it isn't practical to aim at general forward compatibility or 
version independence.


And I didn't know until your comment above that some features, 
apparently, only exist in __future__ but are not part of the language, 
subject to change.


Which is precisely the point raised by several -- writing a book for 
novices, while still a novice, is going to be risky... especially if you 
keep disregarding good advice about what to include and exclude.



Is there a current example?

And, just a suggestion, would it not be better to have a different name 
for such experimental (as opposed to future language version) features, 
e.g. "from __experimental__", differentiating between forward 
compatibility in e.g. production code, and trying out experimental 
subject-to-change features?


You're missing the point.  If it's in __future__ it's subject to change. 
 Most likely it won't be a drastic change, but it *can* change.  The 
'experimental' is more along the lines of "hey, this is coming down the 
pike, let's do some stress-testing so we can nail down the final 
implementation".


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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread bartc


"Alf P. Steinbach"  wrote in message 
news:hc8pn3$dd...@news.eternal-september.org...

[Cross-posted comp.programming and comp.lang.python]


I may finally have found the perfect language for a practically oriented 
introductory book on programming, namely Python.


C++ was way too complex for the novice, JScript and C# suffered from too 
fast-changing specifications and runtime environment, Java, well, nothing 
particularly wrong but it's sort of too large and unwieldy and 
inefficient.


I don't know whether this will ever become an actual book. I hope so!

But since I don't know much Python -- I'm *learning* Python as I write --  
I know that there's a significant chance of communicating misconceptions, 
non-idiomatic ways to do things, bad conventions, etc., in addition to of 
course plain errors of fact and understanding in general, to which I'm not 
yet immune...


So I would would be very happy for feedback.


Have you ever done technical writing before? With positive feedback?

You use the highly commercial-looking activatestate website; what's wrong 
with www.python.org?


You say elsewhere that you're not specifically teaching Python, but the text 
is full of technical details specific to both Python and Windows, not much 
actual programming!


Python has a lot of baggage which is OK if that's what's going to be used, 
but otherwise is unnecessary confusion: where to put the program code (typed 
in live or in a file, or some combination); whether to call the file .py or 
.pyw; the difference between console and graphical programs and so on.


--
Bartc 


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


Re: __eq__() inconvenience when subclassing set

2009-10-29 Thread Jess Austin
On Oct 29, 3:54 pm, Mick Krippendorf  wrote:
> Jess Austin wrote:
> > That's nice, but it means that everyone who imports my class will have
> > to import the monkeypatch of frozenset, as well.  I'm not sure I want
> > that.  More ruby than python, ne?
>
> I thought it was only a toy class?

Well, I posted a toy, but it's a stand-in for something else more
complicated.  Trying to conserve bytes, you know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: disutils, project structure & developing - n00b question

2009-10-29 Thread Lie Ryan

Simon Forman wrote:


In order for "from pymlb import fetcher" no work you must make the
'./pymlb' directory into a "package" by adding a file called
__init__.py (it can be empty.)

Then make sure the "top" directory (i.e. '.' in your example) is in
the python PATH.  There are a couple of ways to do that:

1.) Hack it in demo.py before importing fetcher
  (i.e. "import sys; sys.path.append()")

2.) Use the PYTHONPATH environment variable.

3.) Use a .pth file (See http://docs.python.org/library/site.html)
You'll have to figure out what directory to put it in (on my system
'/usr/lib/python2.5/site-packages' works) Note, although it's not
mentioned in the site module docs you can include an absolute path and
it will be added to sys.path.

There is additional good information about .pth files on Bob
Ippolito's blog:
http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/
Be sure to read the comments too.

4.) Probably some other method(s) that someone else will tell you...  ;]


4.) By importing the module from a main.py script in the main directory, 
and making every imported folder a package (by putting __init__.py 
file). This is the simplest method I found, but has the drawback that 
you can't use a subpackage for execution (only for imports).


i.e.

$ ls
./__init__.py
./setup.py
./pymlb/
./pymln/__init__.py
./pymlb/fetcher.py
./demos
./demos/demo.py
./run_script.py
$ cat run_script.py
#!/usr/bin/env python
from demos import demo
$ cat demos/demo.py
from pymlb import fetcher
$ ./run_script.py
...

or something like that...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* Benjamin Kaplan:

On Thu, Oct 29, 2009 at 1:24 PM, Alf P. Steinbach  wrote:

ActiveState is simplest to install.

However, given what I've now learned about the current situation wrt.
versions of Python, where Python 3.x is effectively a new language, and
where apparently ActiveState has no installer for that, I'm rewriting to use
the "official" distribution.

It has some bugs in the installer and is in many respects incompatible with
the information the student can find and will most easily stumble on on the
net, even the sites that the 3.1.1 documentation links to (e.g. now
"tkinter" instead of "Tkinter", now "/" does not perform integer division
and there goes my example of that, so on), but it's a more clean language.



ActiveState does have Python 3 installers. They've had them almost
since the day it was released. It's just not the default because many
of the libraries people use haven't been ported yet.

https://www.activestate.com/activepython/downloads/


Oh well, thanks, but now I've spent some time on *reworking* the text (it took 
some time because I had to uninstall and install again to create new screenshot, 
and, thus discovered the module docs server in the mainstream distribution :-).


Is there such a thing also in the ActiveState 3.x distribution?

Since Python has so many batteries included I'm fairly sure that 3rd party 
libraries won't be needed. Or, I can probably wing it if necessary.



Cheers,

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


Re: Recommended number of threads? (in CPython)

2009-10-29 Thread Paul Rubin
Neil Hodgson  writes:
>If you are running on a 32-bit environment, it is common to run out
> of address space with many threads. Each thread allocates a stack and
> this allocation may be as large as 10 Megabytes on Linux. 

I'm sure it's smaller than that under most circumstances.  I run
python programs with hundreds of threads all the time, and they don't
use gigabytes of memory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Trent Mick

However, given what I've now learned about the current situation wrt.
versions of Python, where Python 3.x is effectively a new language, and
where apparently ActiveState has no installer for that, I'm rewriting to use
the "official" distribution.

...
ActiveState does have Python 3 installers. They've had them almost
since the day it was released. It's just not the default because many
of the libraries people use haven't been ported yet.

https://www.activestate.com/activepython/downloads/


Also:
http://www.activestate.com/activepython/python3/



Trent

--
Trent Mick
trentm at activestate.com
http://trentm.com/blog/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Aahz
In article ,
Robert Kern   wrote:
>
>I like using pyflakes. It catches most of these kinds of typo errors, but is 
>much faster than pylint or pychecker. 

Coincidentally, I tried PyFlakes yesterday and was unimpressed with the
way it doesn't work with "import *".
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow."  --PNH to rb in r.a.sf.f
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get a unique function name for methods

2009-10-29 Thread Philip Guo
Hi all,

This is my first post, so sorry for the n00bish question.  Let's say I have
2 classes with the same __init__ method defined in a file foo.py:

class A:
  def __init__(self):
pass

class B:
  def __init__(self):
pass

For the purpose of a code analysis, I need to get a UNIQUE name for each of
the two __init__ methods.  In the Python code object, i can get co_name and
co_filename, which returns me the method name and filename, respectively,
but NOT the enclosing classname.  This is a problem since both A.__init__
and B.__init__ will show up as {co_name: "__init__", co_filename: "foo.py"}
in my analysis.  Ideally, I want to distinguish them by their class names:

{co_name: "__init__", co_filename: "foo.py", classname: "A"}
{co_name: "__init__", co_filename: "foo.py", classname: "B"}

(Simply using their line numbers isn't gonna work for me, I need their class
names.)

Does anyone know how to get this information either from a code object or
from a related object?  I am hacking the interpreter, so I have full access
to everything.

Thanks in advance,
Philip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommended number of threads? (in CPython)

2009-10-29 Thread Neil Hodgson
mk:

> I found that when using more than several hundred threads causes weird
> exceptions to be thrown *sometimes* (rarely actually, but it happens
> from time to time). 

   If you are running on a 32-bit environment, it is common to run out
of address space with many threads. Each thread allocates a stack and
this allocation may be as large as 10 Megabytes on Linux. With a 4
Gigabyte 32-bit address space this means that the maximum number of
threads will be 400. In practice, the operating system will further
subdivide the address space so only 200 to 300 threads will be possible.
On Windows, I think the normal stack allocation is 1 Megabyte.

   The allocation is only of address space, not memory since memory can
be mapped into this space when it is needed and many threads do not need
very much stack.

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Robert Kern

On 2009-10-29 15:48 PM, kj wrote:


How can one check that a Python script is lexically correct?

As my Python apps grow in complexity and execution, I'm finding it
more often the situation in which a program dies after a lengthy
(i.e. expensive) run because the execution reaches, say, a typo.
Of course, this typo needs to be fixed, but I'd like to find out
about it before I waste hours on a run that is bound to fail.  Is
there any way to do this?  I imagine the answer is no, because
given Python's scoping rules, the interpreter can't know about
these things at compile time, but I thought I'd ask.


I like using pyflakes. It catches most of these kinds of typo errors, but is 
much faster than pylint or pychecker. That means I can hook up a key macro to 
run it in my editor so I can use it frequently without hesitation (e.g. in Vim, 
it is my makeprg for Python files).


It doesn't catch other stupid errors, of course. Try your best to write small, 
simple, quick-to-run tests for each piece of functionality that you are working 
on. Test the methods you've just coded independently of the rest of your code 
using that small test before doing full hours-long runs of the whole program. 
Bonus: you now have a suite of unit tests.


--
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

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


Re: PyQT4 user group

2009-10-29 Thread Colin W.

Diez B. Roggisch wrote:

Chris wrote:


Hi!

I'm starting to learn and use PyQT4 at work.  Is there a good user
group or forum out there that I should know about?


The PyQt Mailinglist.

Diez
I find the Gmane server, which delivers items from the PyQt Mailing 
List, easier to use.  It threads the messages.


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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Diez B. Roggisch

kj schrieb:

How can one check that a Python script is lexically correct?

As my Python apps grow in complexity and execution, I'm finding it
more often the situation in which a program dies after a lengthy
(i.e. expensive) run because the execution reaches, say, a typo.
Of course, this typo needs to be fixed, but I'd like to find out
about it before I waste hours on a run that is bound to fail.  Is
there any way to do this?  I imagine the answer is no, because
given Python's scoping rules, the interpreter can't know about
these things at compile time, but I thought I'd ask.


pylint, pychecker, pydev. Maybe more.

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Mick Krippendorf
kj wrote:
> How can one check that a Python script is lexically correct?

By using pylint.

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


Re: __eq__() inconvenience when subclassing set

2009-10-29 Thread Mick Krippendorf
Jess Austin wrote:
> That's nice, but it means that everyone who imports my class will have
> to import the monkeypatch of frozenset, as well.  I'm not sure I want
> that.  More ruby than python, ne?

I thought it was only a toy class?

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


Re: Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread Daniel da Silva
There are several static analysis tools that can check whether a variable
name is used before it is defined.

At my old workplace we used "pylint", so I can recommend that:
http://www.logilab.org/857

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


Re: Problem embedding Python.

2009-10-29 Thread Dave Angel

Brandon Keown wrote:

On Oct 27, 7:48 pm, "Gabriel Genellina" 
wrote:
  


Now that you've solved your problem, revise your conclusion. A file
without a path *is* searched in the current working directory - but that
directory may not be the one you think it is.

--
Gabriel Genellina



I'm not sure what you mean.  I executed the program from the directory
the file was in, they were in the same directory.  And when a program
executes from a path in CMD in windows, that is supposed to be the
CWD.  I'm not sure what it would be set to if not that...

  
Gabriel is right.  But if you care to get our diagnosis, you need to 
state your working conditions more clearly.  Or perhaps do a bit of 
debugging on it.  For a start, you might do aprint os.curdir   right 
before the open() function to see what the current directory is.


Or you could remove the several ambiguities in your paragraph above that 
starts "I'm not sure..."  Maybe show a transcript of your CMD session.  
And if the python.* that's on your PATH is a batch file, show us the 
contents of that as well.


And if you're running from CMD, or from an interpreter, or from IDLE, or 
from an IDE, or from Explorer, each one may have its own idea of what to 
give you for current directory.


If you're running the script from a CMD prompt, by just entering the 
script name and letting Windows find the executable (which is not the 
script), then you're correct, CWD should be the same as it was in the 
CMD shell.


DaveA

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


Aaaargh! "global name 'eggz' is not defined"

2009-10-29 Thread kj


How can one check that a Python script is lexically correct?

As my Python apps grow in complexity and execution, I'm finding it
more often the situation in which a program dies after a lengthy
(i.e. expensive) run because the execution reaches, say, a typo.
Of course, this typo needs to be fixed, but I'd like to find out
about it before I waste hours on a run that is bound to fail.  Is
there any way to do this?  I imagine the answer is no, because
given Python's scoping rules, the interpreter can't know about
these things at compile time, but I thought I'd ask.

TIA!

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Benjamin Kaplan
On Thu, Oct 29, 2009 at 1:24 PM, Alf P. Steinbach  wrote:
>
> ActiveState is simplest to install.
>
> However, given what I've now learned about the current situation wrt.
> versions of Python, where Python 3.x is effectively a new language, and
> where apparently ActiveState has no installer for that, I'm rewriting to use
> the "official" distribution.
>
> It has some bugs in the installer and is in many respects incompatible with
> the information the student can find and will most easily stumble on on the
> net, even the sites that the 3.1.1 documentation links to (e.g. now
> "tkinter" instead of "Tkinter", now "/" does not perform integer division
> and there goes my example of that, so on), but it's a more clean language.
>

ActiveState does have Python 3 installers. They've had them almost
since the day it was released. It's just not the default because many
of the libraries people use haven't been ported yet.

https://www.activestate.com/activepython/downloads/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building Python on Solaris 10?

2009-10-29 Thread Judy Booth
"M.-A. Lemburg"  wrote in 
news:mailman.2237.1256807688.2807.python-l...@python.org:

> Why are you building with "--with-universal-archs=64-bit
> --enable-universalsdk" on Solaris ?
> 
> Those options should only be used for Mac OS X.
> 
> Python currently does not support building universal binaries
> on Solaris.
> 
> If you're still having problems, you might want to look at this
> patch:
> 
> http://bugs.python.org/issue1628484
> 
> If it works for you, please add a comment.
> 

I can't answer the question about univeral binaries because I'm not 
building it myself. As a software developer I can build our software 
releases on the Solaris boxes but I have to ask one of the sysadmins to 
install new software on there and the one tring to install Python for us 
ran into problems.

Thanks for the comments - I will take a look at that patch and see if it 
helps. However, from the sound of it I think the next step may be for me 
to either sit with him or build it myself and then tell him what he needs 
to do.

Whatever we end up doing I will try to post an update on here about how 
we resolve this.

Thanks,

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


Re: __eq__() inconvenience when subclassing set

2009-10-29 Thread Jess Austin
On Oct 28, 10:07 pm, Mick Krippendorf  wrote:
> You could just overwrite set and frozenset:
>
> class eqmixin(object):
>     def __eq__(self, other):
>         print "called %s.__eq__()" % self.__class__
>         if isinstance(other, (set, frozenset)):
>             return True
>         return super(eqmixin, self).__eq__(other)
>
> class frozenset(eqmixin, frozenset):
>     pass

That's nice, but it means that everyone who imports my class will have
to import the monkeypatch of frozenset, as well.  I'm not sure I want
that.  More ruby than python, ne?

thanks,
Jess
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* Richard Heathfield:


The best way is the simplest technology that will do the job properly. 
If that truly is PDF, okay, use PDF. But it is hard for me to 
envisage circumstances where Web content is best presented in that 
way.


Google docs sharing. It made a mess of my *Word* documents. 

Cheers & hth.,

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


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread Alf P. Steinbach

* Ethan Furman:

Alf P. Steinbach wrote:

* James Harris:


You get way too deep into Python in places (for a beginner's course in
programming). For example, "from now on I’ll always use from
__future__ in any program that uses print."


Sorry, but I think that hiding such concerns is a real disservice.


The disservice is in teaching folks to use non-standard elements, which 
is (sort-of) what __future__ is.  Changes to the language are 
experimented with in __future__ and can change from one release to the 
next.  If memory serves, the with statement is an example of having 
different behavior when it was moved out of __future__ and made a 
standard part of the language.


That's a bit of a straw man argument. I used "from __future__" to write 
forward-compatible calls of print, so that those examples would not mysteriously 
work or not depending on the Python version. I did not use it to access 
experimental features.


However, I didn't know then that the language has changed so much in 3.x that it 
isn't practical to aim at general forward compatibility or version independence.


And I didn't know until your comment above that some features, apparently, only 
exist in __future__ but are not part of the language, subject to change.


Is there a current example?

And, just a suggestion, would it not be better to have a different name for such 
experimental (as opposed to future language version) features, e.g. "from 
__experimental__", differentiating between forward compatibility in e.g. 
production code, and trying out experimental subject-to-change features?



Cheers,

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


Re: disutils, project structure & developing - n00b question

2009-10-29 Thread Simon Forman
On Thu, Oct 29, 2009 at 3:45 PM, Simon Forman  wrote:
> In order for "from pymlb import fetcher" no work you must make the

s/no/to/

D'oh!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: disutils, project structure & developing - n00b question

2009-10-29 Thread Simon Forman
On Thu, Oct 29, 2009 at 2:42 PM, Wells  wrote:
> So I have my project partitioned like so:
>
> ./setup.py
> ./pymlb/
> ./pymlb/fetcher.py
> ./demos
> ./demos/demo.py
>
> In demo.py I have:
>
> from pymlb import fetcher
>
> However, it fails b/c pymlb is up a folder. It's also NOT installed as
> a module in my module directory because it's a development effort and
> I don't want to run setup.py to install them. See what I mean?
>
> What's the work around here?


In order for "from pymlb import fetcher" no work you must make the
'./pymlb' directory into a "package" by adding a file called
__init__.py (it can be empty.)

Then make sure the "top" directory (i.e. '.' in your example) is in
the python PATH.  There are a couple of ways to do that:

1.) Hack it in demo.py before importing fetcher
  (i.e. "import sys; sys.path.append()")

2.) Use the PYTHONPATH environment variable.

3.) Use a .pth file (See http://docs.python.org/library/site.html)
You'll have to figure out what directory to put it in (on my system
'/usr/lib/python2.5/site-packages' works) Note, although it's not
mentioned in the site module docs you can include an absolute path and
it will be added to sys.path.

There is additional good information about .pth files on Bob
Ippolito's blog:
http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/
Be sure to read the comments too.

4.) Probably some other method(s) that someone else will tell you...  ;]

HTH,
~Simon
-- 
http://mail.python.org/mailman/listinfo/python-list


Python2.6 + win32com crashes with unicode bug

2009-10-29 Thread GerritM
I have automated image generation with Python, win32com and Visio5.0. 
This works well upto Python2.5 but fails with Python 2.6.

Short term solution is to return to 2.5 :-(.

I have reproduced the bug below with a minimum of Python lines. Below 
the problem the working example from 2.5


kind regards, Gerrit

---minimal session reproducing the bug---

Python 2.6.3 (r263:75183, Oct  5 2009, 14:41:55) [MSC v.1500 32 bit 
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 2.6.3
>>> from win32com.client.dynamic import Dispatch
>>> v = Dispatch("Visio.Application")
>>> d = v.Documents.OpenEx("D:/temp/test.vsd",8)

Traceback (most recent call last):
  File "", line 1, in 
d = v.Documents.OpenEx("D:/temp/test.vsd",8)
  File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 
467, in __getattr__
if self._olerepr_.mapFuncs.has_key(attr): return 
self._make_method_(attr)
  File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 
295, in _make_method_
methodCodeList = 
self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
297, in MakeFuncMethod

return self.MakeDispatchFuncMethod(entry, name, bMakeClass)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
318, in MakeDispatchFuncMethod
s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, 
names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):'
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
604, in BuildCallList

argName = MakePublicAttributeName(argName)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
542, in MakePublicAttributeName

return filter( lambda char: char in valid_identifier_chars, className)
  File "C:\Python26\lib\site-packages\win32com\client\build.py", line 
542, in 

return filter( lambda char: char in valid_identifier_chars, className)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: 
ordinal not in range(128)

>>>

---no problem with 2.5---
Python 2.5 (r25:51908, Mar  9 2007, 17:40:28) [MSC v.1310 32 bit 
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2
>>> from win32com.client.dynamic import Dispatch
>>> v = Dispatch("Visio.Application")
>>> d = v.Documents.OpenEx("D:/temp/test.vsd",8)
>>>

---configuration data---
Windows XP SP3
ASUS 1106HA (11.6" EEE PC)
Visio 5.0
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feedback wanted on programming introduction (Python in Windows)

2009-10-29 Thread osmium
"Richard Heathfield" wrote:

>> if the OP had just been smarter.
>
> Er, no, I didn't have that in mind at all.

In some cultures, implying that someone is illiterate suggests "not smart". 
There is a formal disconnect there but possibly you can see how someone 
might infer that.

At least I found out what your choice was, HTML, same as mine. 


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


disutils, project structure & developing - n00b question

2009-10-29 Thread Wells
So I have my project partitioned like so:

./setup.py
./pymlb/
./pymlb/fetcher.py
./demos
./demos/demo.py

In demo.py I have:

from pymlb import fetcher

However, it fails b/c pymlb is up a folder. It's also NOT installed as
a module in my module directory because it's a development effort and
I don't want to run setup.py to install them. See what I mean?

What's the work around here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Checking if a function invocation will throw a TypeError?

2009-10-29 Thread Andrey Fedorov
Is there a standard function that will check whether certain *args, and
**kwargs satisfy a argspec of a function (s.t. it does not throw a
TypeError). Say:

def foo(a,b=1):
pass

check(foo, 1,2) # True
check(foo, 1) # True
check(foo) # False
check(foo, 1, a=2) # False

Cheers,
Andrey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug(s) in Python 3.1.1 Windows installation

2009-10-29 Thread Ethan Furman

Alf P. Steinbach wrote:

* Ethan Furman:


Mark Hammond wrote:


On 29/10/2009 11:06 AM, Alf P. Steinbach wrote:


So I suggest switching to some other more light-weight installer
technology.




Thanks for the suggestion, but I expect we will stick with MSI even 
with its shortcomings.  Using MSI files has significant other 
advantages, particularly in "managed" environments.



(2) Failure to set up PATH.




This is by design.  If you really care passionately about this, you 
should be able to find a number of discussions here, in python-dev 
and in the python bug tracker.


One example of why the current behaviour is useful is that many 
people install multiple Python versions side-by-side and a "last 
installed wins" strategy isn't a great option.



Even after setting up a correct PATH Tkinter does not work:




I suspect this will be a Python 3.x issue - you probably want to 
stick with 2.x.


HTH,

Mark



Looks like in 3.x the name was changed to tkinter.

~Ethan~



That works! 

Thanks. But, where I can find information about how "import" now works? 
I mean there's no *file* named [tkinter.*] anywhere, so I suspect it 
looks in the [tkinter] directory or perhaps uses some setup file's name 
association or?



Alf, apologies for e-mailing you directly: I hit Reply instead of 
Reply-to-all.


Try searching the archives -- there have been many discussions about 
import, and a few about import in 3.x.


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


Re: Are *.pyd's universal?

2009-10-29 Thread Christian Heimes
Bakes wrote:
> Can I use a pyd compiled on linux in a Windows distribution?
> 
> Or must I recompile it for windows users?

On Linux and several other Unices the suffix is .so and not .pyd. The
compiled extensions depend on the Python version, operating system as
well as platform and architecture.

Christian

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


  1   2   >