Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread [EMAIL PROTECTED]

Steven D'Aprano wrote:
> Why do you assume that everything you need for your list comprehension has
> to go into a single line? Chances are your list comp already calls
> functions, so just create one more for it to use.
>
>
> py> def describe(cond):
> ... if cond:
> ... return "odd"
> ... else:
> ... return "even"
> ...
> py> L = [describe(n % 2) for n in range(8)]
> py> L
> ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

this makes me "jump" from the list comprehension to the function,
harder to follow than 'in place', especially when the function is
simple, it is not necessary. What is the reason for introducing list
comprehension and then later, generator expression when :

a=[]
for x in range(8):
  a.append(describe(x%2))
return a

and

for x in range(8):
  yield describe(x%2)

can do the same thing ?

Doesn't it violate the general idiom that it better has one and only
one way to do certain thing ? I believe part of the reason is that one
doesn't need to "jump" up and down.

>
> One major advantage is that this makes it easier to test your function
> describe() in isolation, always a good thing.
>
> Another advantage is that the idiom "call a function" is extensible to
> more complex problems:
>
> def describe(n):
> if n < 0:
> return "negative " + describe(-n)
> elif n == 0:
> return "zero"
> elif n % 2:
> return "odd"
> else:
> return "even"
>
> L = [describe(n) for n in range(8)]
>
> if much easier to understand and follow than using ternary expressions:
>
> # obviously untested
> L = ["zero" if n == 0 else \
> "negative " + ("odd" if n % 2 else "even") if n < 0 else \
> "odd" if n % 2 else "even" for n in range(8)]
>
> Yes, I've seen ternary expressions nested three and even four deep.
Now that is obsession for(and bad use of) one-liner. But picking a bad
example of one liner to rule out its effectiveness and readability is a
stretch I would say.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 21:05:50 -0800, [EMAIL PROTECTED] wrote:


> Steven D'Aprano wrote:
>> WHY WHY WHY the obsession with one-liners? What is wrong with the good old
>> fashioned way?
>>
>> if cond:
>> x = true_value
>> else:
>> x = false_value
>>
>> It is easy to read, easy to understand, only one of true_value and
>> false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
>> think that newlines cost money or that ever time you used one God killed a
>> kitten.
>>
> How do you put this block into list comprehension or generator
> expression ? Why the obsession of these block style ?

Why do you assume that everything you need for your list comprehension has
to go into a single line? Chances are your list comp already calls
functions, so just create one more for it to use.


py> def describe(cond):
... if cond:
... return "odd"
... else:
... return "even"
... 
py> L = [describe(n % 2) for n in range(8)]
py> L
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

One major advantage is that this makes it easier to test your function
describe() in isolation, always a good thing.

Another advantage is that the idiom "call a function" is extensible to
more complex problems:

def describe(n):
if n < 0:
return "negative " + describe(-n)
elif n == 0:
return "zero"
elif n % 2:
return "odd"
else:
return "even"

L = [describe(n) for n in range(8)]

if much easier to understand and follow than using ternary expressions:

# obviously untested
L = ["zero" if n == 0 else \
"negative " + ("odd" if n % 2 else "even") if n < 0 else \
"odd" if n % 2 else "even" for n in range(8)]

Yes, I've seen ternary expressions nested three and even four deep.

I find it fascinating to read Guido's reasoning for introducing a ternary
statement. From the PEP here http://www.python.org/peps/pep-0308.html he
links to this comment of his:

[quote]
I think Raymond's example is more properly considered an argument for
adding a conditional expression than for removing the current behavior of
the and/or shortcut operators; had we had a conditional expression, he
wouldn't have tried to use the "x and y or z" syntax that bit him.
[end quote]

Looking back to Raymond's example here: 
http://mail.python.org/pipermail/python-dev/2005-September/056510.html

[quote]
I propose that in Py3.0, the "and" and "or" operators be simplified to
always return a Boolean value instead of returning the last evaluated
argument.

1) The construct can be error-prone.  When an error occurs it can be
invisible to the person who wrote it.  I got bitten in published code
that had survived testing and code review:

  def real(self):
'Return a vector with the real part of each input element'
# do not convert integer inputs to floats
return self.map(lambda z: type(z)==types.ComplexType and z.real or z)

The code fails silently when z is (0+4i).  It took a good while to trace
down a user reported error (when Matlab results disagreed with my matrix
module results) and determine that the real() method contained an error.
Even when traced down, I found it hard to see the error in the code.
Now that I know what to look for, it has not happened again, but I do
always have to stare hard at any "and/or" group to mentally verify each
case.
[end quote]


Dare I suggest that if Raymond wasn't struggling to force the body of his
function real() to be a one-liner, he wouldn't have tried to use the "x
and y or z" syntax that bit him? Brevity is not always a virtue.


-- 
Steven.

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


Weekly Python Patch/Bug Summary

2005-11-18 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  379 open (+14) /  2968 closed ( +7) /  3347 total (+21)
Bugs:  910 open ( +6) /  5384 closed (+17) /  6294 total (+23)
RFE :  200 open ( +0) /   191 closed ( +2) /   391 total ( +2)

New / Reopened Patches
__

PythonD DJGPP-specific patch set for porting to DOS.  (2005-11-08)
   http://python.org/sf/1351020  opened by  Ben Decker

PythonD new file: python2.4/plat-ms-dos5/djstat.py  (2005-11-08)
   http://python.org/sf/1351036  opened by  Ben Decker

askyesnocancel helper for tkMessageBox  (2005-11-08)
   http://python.org/sf/1351744  opened by  Fredrik Lundh

fix for resource leak in _subprocess  (2005-11-09)
CLOSED http://python.org/sf/1351997  opened by  Fredrik Lundh

[PATCH] Bug #1351707  (2005-11-10)
   http://python.org/sf/1352711  opened by  Thomas Lee

Small upgrades to platform.platform()  (2005-11-10)
   http://python.org/sf/1352731  opened by  daishi harada

a faster Modulefinder  (2005-11-11)
   http://python.org/sf/1353872  opened by  Thomas Heller

support whence argument for GzipFile.seek (bug #1316069)  (2005-11-12)
   http://python.org/sf/1355023  opened by  Fredrik Lundh

PEP 341 - Unification of try/except and try/finally  (2005-11-14)
   http://python.org/sf/1355913  opened by  Thomas Lee

Delete Python-ast.[ch] during "make depclean" (#1355883)  (2005-11-14)
CLOSED http://python.org/sf/1355940  opened by  Thomas Lee

Python-ast.h & Python-ast.c generated twice (#1355883)  (2005-11-14)
   http://python.org/sf/1355971  opened by  Thomas Lee

Sort nodes when writing to file  (2005-11-14)
CLOSED http://python.org/sf/1356571  opened by  Johan Ström

potential crash and free memory read  (2005-11-15)
   http://python.org/sf/1357836  opened by  Neal Norwitz

ftplib dir() problem with certain servers  (2005-11-17)
   http://python.org/sf/1359217  opened by  Stuart D. Gathman

Iterating closed StringIO.StringIO  (2005-11-18)
   http://python.org/sf/1359365  opened by  Walter Dörwald

Speed charmap encoder  (2005-11-18)
   http://python.org/sf/1359618  opened by  Martin v. Löwis

Patch for (Doc) #1357604  (2005-11-18)
   http://python.org/sf/1359879  opened by  Peter van Kampen

Add XML-RPC Fault Interoperability to XMLRPC libraries  (2005-11-18)
   http://python.org/sf/1360243  opened by  Joshua Ginsberg

correct display of pathnames in SimpleHTTPServer  (2005-11-18)
   http://python.org/sf/1360443  opened by  Ori Avtalion

Auto Complete module for IDLE  (2005-11-19)
   http://python.org/sf/1361016  opened by  Jerry

Patches Closed
__

Redundant connect() call in logging.handlers.SysLogHandler  (2005-11-07)
   http://python.org/sf/1350658  closed by  vsajip

incomplete support for AF_PACKET in socketmodule.c  (2004-11-19)
   http://python.org/sf/1069624  closed by  gustavo

fix for resource leak in _subprocess  (2005-11-09)
   http://python.org/sf/1351997  closed by  effbot

Info Associated with Merge to AST  (2005-01-07)
   http://python.org/sf/1097671  closed by  kbk

Delete Python-ast.[ch] during "make depclean" (#1355883)  (2005-11-13)
   http://python.org/sf/1355940  closed by  montanaro

Sort nodes when writing to file  (2005-11-14)
   http://python.org/sf/1356571  closed by  effbot

CodeContext - an extension to show you where you are  (2004-04-16)
   http://python.org/sf/936169  closed by  kbk

New / Reopened Bugs
___

win32serviceutil bug  (2005-11-08)
CLOSED http://python.org/sf/1351545  opened by  Tim Graber

Switch to make pprint.pprint display ints and longs in hex  (2005-11-08)
   http://python.org/sf/1351692  opened by  Mark Hirota

zipimport produces incomplete IOError instances  (2005-11-08)
   http://python.org/sf/1351707  opened by  Fred L. Drake, Jr.

CVS webbrowser.py (1.40) bugs  (2005-10-26)
CLOSED http://python.org/sf/1338995  reopened by  montanaro

SVN webbrowser.py fix 41419 didn't  (2005-11-09)
   http://python.org/sf/1352621  opened by  Greg Couch

poplib.POP3_SSL() class incompatible with socket.timeout  (2005-11-10)
   http://python.org/sf/1353269  opened by  Charles

Http redirection error in urllib2.py  (2005-11-10)
   http://python.org/sf/1353433  opened by  Thomas Dehn

Python drops core when stdin is bogus  (2005-11-10)
   http://python.org/sf/1353504  opened by  Skip Montanaro

Error in documentation for os.walk  (2005-11-11)
CLOSED http://python.org/sf/1353793  opened by  Martin Geisler

logging: Default handlers broken  (2005-11-11)
CLOSED http://python.org/sf/1354052  opened by  Jonathan S. Joseph

Interactive help fails with Windows Installer  (2005-11-11)
CLOSED http://python.org/sf/1354265  opened by  Colin J. Williams

shutil.move() does not preserve ownership  (2005-11-13)
   http://python.org/sf/1355826  opened by  lightweight

Incorrect Decimal-float behavior for +  (2005-11-13)
   http://python.org/sf/1355842  opene

Re: os.popen('alias')

2005-11-18 Thread Chris F.A. Johnson
On 2005-11-19, Chris F.A. Johnson wrote:
> On 2005-11-18, Belebele wrote:
>>>From an interactive python shell, I execute the following:
>>
>> import os
>> for line in os.popen('alias').readlines():
>>   print line
>>
>>
>> No aliases are printed.
>>
>> I started python from an bash environment that had many aliases
>> defined. I expected to see the list of aliases from within the
>> interactive python shell.
>
> Since bash does not export aliases, they cannot be seen by a child
> process.
>
>> What could I do to see those aliases defined in the shell from where
>> I started python?
>
> Store them in a file before calling python, and read that file.

   Or redefine them as functions and use:

import os
for line in os.popen('typeset -f').readlines():
  print line

-- 
   Chris F.A. Johnson, author   |
   Shell Scripting Recipes: |  My code in this post, if any,
   A Problem-Solution Approach  |  is released under the
   2005, Apress | GNU General Public Licence
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Underscores in Python numbers

2005-11-18 Thread [EMAIL PROTECTED]

Steven D'Aprano wrote:
> On Fri, 18 Nov 2005 16:26:08 -0800, [EMAIL PROTECTED] wrote:
>
> > Personally, I would rather see the int() and float() function be
> > smarter to take what is used for this, i.e. :
> >
> > a = int("1,234,567")
>
> But the problem isn't just with conversion of strings. It is also
> with literals.
>
> n = 999
>
> Without counting, how many nines?
For readability, I don't see why it cannot be written as :

   n = int("99,999,999,999")

we already needs to do this for decimal("9.9")

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


Re: os.popen('alias')

2005-11-18 Thread Chris F.A. Johnson
On 2005-11-18, Belebele wrote:
>>From an interactive python shell, I execute the following:
>
> import os
> for line in os.popen('alias').readlines():
>   print line
>
>
> No aliases are printed.
>
> I started python from an bash environment that had many aliases
> defined. I expected to see the list of aliases from within the
> interactive python shell.

Since bash does not export aliases, they cannot be seen by a child
process.

> What could I do to see those aliases defined in the shell from where
> I started python?

Store them in a file before calling python, and read that file.

-- 
   Chris F.A. Johnson, author   |
   Shell Scripting Recipes: |  My code in this post, if any,
   A Problem-Solution Approach  |  is released under the
   2005, Apress | GNU General Public Licence
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Underscores in Python numbers

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 16:26:08 -0800, [EMAIL PROTECTED] wrote:

> Personally, I would rather see the int() and float() function be
> smarter to take what is used for this, i.e. :
> 
> a = int("1,234,567")

But the problem isn't just with conversion of strings. It is also
with literals.

n = 999

Without counting, how many nines?

Obviously repeated digits is an extreme case, but even different digits
are easier to process if grouped. That's why we write phone numbers like
62 3 9621 2377 instead of 62396212377.

Here is a thought: Python already concatenates string literals:

"abc" "def" is the same as "abcdef".

Perhaps Python should concatenate numeric literals at compile time:

123 456 is the same as 123456.

Off the top of my head, I don't think this should break any older code,
because 123 456 is not currently legal in Python.


-- 
Steven.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread [EMAIL PROTECTED]

Roy Smith wrote:
> I think the list comprehensions are going to be the death of readable
> python programs.
Could be, but seems that someone in charge of the language wants
readable python programs to die then as if list comprehension is not
enough, there comes generator expression and now the formal acceptance
of ternary operator.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> Steven D'Aprano wrote:
> > WHY WHY WHY the obsession with one-liners? What is wrong with the good old
> > fashioned way?
> >
> > if cond:
> > x = true_value
> > else:
> > x = false_value
> >
> > It is easy to read, easy to understand, only one of true_value and
> > false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
> > think that newlines cost money or that ever time you used one God killed a
> > kitten.
> >
> How do you put this block into list comprehension or generator
> expression ? Why the obsession of these block style ?

I think the list comprehensions are going to be the death of readable 
python programs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread [EMAIL PROTECTED]

Steven D'Aprano wrote:
> WHY WHY WHY the obsession with one-liners? What is wrong with the good old
> fashioned way?
>
> if cond:
> x = true_value
> else:
> x = false_value
>
> It is easy to read, easy to understand, only one of true_value and
> false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
> think that newlines cost money or that ever time you used one God killed a
> kitten.
>
How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 11:17:17 -0800, David  Wahler wrote:

> Daniel Crespo wrote:
>> I would like to know how can I do the PHP ternary operator/statement
>> (... ? ... : ...) in Python...
>>
>> I want to something like:
>>
>> a = {'Huge': (quantity>90) ? True : False}
> 
> Well, in your example the '>' operator already returns a boolean value
> so you can just use it directly. Hoewver, I agree that there are
> situations in which a ternary operator would be nice. Unfortunately,
> Python doesn't support this directly; the closest approximation I've
> found is:
> 
 (value_if_false, value_if_true)[boolean_value]

Which doesn't short-circuit: both value_if_false and value_if_true are
evaluated.

WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.




-- 
Steven.

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


Re: Embedded Python interpreter and sockets

2005-11-18 Thread [EMAIL PROTECTED]
Hi Jan,

I believe the problem lies with how Houdini uses dlopen() to open your
plugin.  It uses RTLD_LOCAL to load your plugin, which means that all
your plugin's symbols (including the python symbols) are private to
that library.  Subsequent dlopen() calls, including those made by the
python library, won't be able to see any of those symbols.  This
problem isn't unique to Python, or Houdini, it's just a matter of how
dlopen() is being used.

One thing that may work (I just tried here, and it looks like it
does...but it's late on a Friday night, so I may have overlooked
something) is creating a wrapper plugin.  Say you have your plugin
called myplugin.so which links aginst libpython.  Create a new plugin
called myplugin_wrapper.so which exports the same required symbols.
myplugin_wrapper will need to dlopen("myplugin.so", RTLD_GLOBAL), and
then call the real methods inside myplugin.so.  Since myplugin.so is
the one linked against libpython, and it is being loaded with
RTLD_GLOBAL, then the python symbols should be available to other
shared libraries loaded at a future time.

Let me know if this works out!  If you need any help, head on over to
http://www.sidefx.com/forum.

Cheers,
Chris

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


Re: Behaviour of enumerated types

2005-11-18 Thread Bengt Richter
On Sat, 19 Nov 2005 11:10:42 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> wrote:

>Bengt Richter <[EMAIL PROTECTED]> wrote:
>> Ben Finney <[EMAIL PROTECTED]> wrote:
>> >Getting a numeric index might be useful in a language such as
>> >Pascal, with no built-in dict or sequence types. In Python, where
>> >any immutable object can be a dict key, and any sequence can be
>> >iterated, it seems of no use.
>>
>> Does your concept of enumeration not have a fixed order of a set of
>> names?
>
>It does. The values are iterable in the same order they were specified
>when creating the Enum.
>
>> If it does, what is more natural than using their index values as
>> keys to other ordered info?
>
>I don't see why. If you want sequence numbers, use enumerate(). If
>not, the enum object itself can be used directly as an iterable.
I changed mine so the enum _class_ is iterable, but enum instances are not.
>
>> OTOH, the index values (and hence my enums) are[1] not very good as
>> unique dict keys, since they compare[2] promiscuously with each
>> other and other number types.
>
>Indeed, that's why (in my design) the values from the enum are only
>useful for comparing with each other. This, to me, seems to be the
>purpose of an enumerated type.
Have you tried yet to use two different enum instances as keys in
the same dict? Then try to sort the keys(or items is the values are
misc different enums). I hit that, and changed __cmp__ to compare
(typename, ) tuples. That sorts
items grouped by enum type if they're keys. I think you can always
pass a stricter cmp to sorted if you want to assert type equality.

>
>> To me the int correspondence is as expectable and natural as
>> a,b,c=range(3) (at least as a default) though I think different
>> enumerations should be different types.
>
>That's a complete contradiction, then. If you want them to be
>different types, you don't want them to be integers.
No, it's not a contradiction. Different int _sub_types are different
types ;-)

>
>> Note that the ordering of int values makes the instances nicely
>> sortable too, e.g.,
>
>That only means the enum values need to compare in the same sequence;
>it doesn't mean they need to correspond to integer values.
True.

>
>> But bottom line, I really thing the int base type is more than an
>> implementation detail. I think it's natural for an _ordered_ set of
>> names ;-)
>
>I think I've addressed all your current concerns; I don't believe an
>inherent correlation to integers is necessary at all.
Necessary wasn't the question for me. It's whether it's desirable. YMMV ;-)

>
>It's no more necessary than saying that ["a", "b", "c"] requires that
>there be some specific correlation between the values of that list and
>the integers 0, 1, 2. If you *want* such a correlation, in some
>particular case, use enumerate() to get it; but there's nothing about
>the values themselves that requires that correspondence.
Yet it is comforting to know that ['a', 'b', 'c'][0] will interpret
the [0] to mean the first in the sequence (unless someone is doing
a list-like repr trick based on some other type ;-).

I haven't yet converted my generated enum classes to singletons,
but I did make it so you can define a named enumeration class and
iterate the class itself (its metaclass defines __getitem__). What
you get is the particular enum class instance, e.g. (... time passes,
never mind, I cached instanced for an effective singleton set of named numbers.

The class methods are introduced via metaclass in the makeEnum factory
and it's a very hacky workaround for the fact that execution of a
class definition body only has local and module global namespace, so
you can't directly reference anything local to the factory function.
This of course goes for the methods of the main class being constructed too,
so they are sneaked in via the metaclass before instantiating the class ;-/
(Anyone have an idea how to do this cleanly and have the same functionality
--being able to iterate the _class_ object etc.?

Anyway, this is my "feedback" ;-) What's missing in this? 

< makeenum.py >--
def makeEnum(ename, names):
"""
Factory function to returns enumeration class with name ename,
and enumerating space-delimited names in names string.
The class is an int subtype, and instances have int values as
well as corresponding names. Different enum instances with the
same int value are distinct as dict keys, but equal used as ints,
though they are not directly comparable unless the same type.

The return class itself defines an iterator that will return
all possible instances in order. The class names property returns
a tuple of the names, and the len(TheClass) returns the number of
names or of the iteration sequence.
"""
global __global_for_mc_hack__
class __global_for_mc_hack__(type):
"""
metaclass to define methods on the enum class per se, and to pass
t

Re: Python obfuscation

2005-11-18 Thread Steven D'Aprano
On Tue, 15 Nov 2005 03:06:31 -0800, Ben Sizer wrote:

> My interest lies in being able to use encrypted data (where 'data' can
> also include parts of the code) so that the data can only be read by my
> Python program, and specifically by a single instance of that program.
> You would be able to make a backup copy (or 20), you could give the
> whole lot to someone else, etc etc. I would just like to make it so
> that you can't stick the data file on Bittorrent and have the entire
> world playing with data that was only purchased once.

Well, if and when you find a way to make water not wet and three-sided
squares, then you can turn your mind towards solving the *really* hard
problem: how to make bytes not copyable.


-- 
Steven.

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


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 17:49:50 +, Leif K-Brooks wrote:

> Sion Arrowsmith wrote:
>> Steven Bethard  <[EMAIL PROTECTED]> wrote:
>> 
>>>[EMAIL PROTECTED] wrote:
>>>
s = long("0xL")
ValueError: invalid literal for long(): 0xL

>>int("0x", 0)
>>>
>>>4294967295L
>> 
>> So why does the base argument to int() (or long()) default to
>> 10 and not 0?
> 
> Because it's designed for numbers normal people provide, not for numbers
> programmers provide. Normal people see 0123 as being equal to 123, not 83.

The base arguments to int() and long() default to base 10 because base 10
is used by just about all people and cultures in the world. Leading zeroes
are mathematically meaningless: 0123 means 0*base**3 + 1*base**2 +
2*base**1 + 3*base**0, which is identical to 123 no matter what base you
choose.

Interpreting 0123 in octal is a sop to programmers who want/need
compatibility to the C bug that changes the meaning of numeric literals
according to the presence or absence of a leading zero. Alas I suspect
that this particular piece of illogic is too ingrained now to ever
eradicate.


-- 
Steven.

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


Re: need help about time.sleep, timer

2005-11-18 Thread Peter Hansen
Sinan Nalkaya wrote:
> i need a function like that,
> wait 5 seconds:
>(during wait) do the function
> but function waits for keyboard input so if you dont enter any it waits 
> forever.

It's quite unclear whether the last part, above, is one of your 
*requirements*, or a description of a problem you are having with your 
current approach.  Do you *want* it to wait forever if you don't enter 
anthing?

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


Re: How to convert a "long in a string" to a "long"?

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 11:10:06 -0500, Carsten Haese wrote:

>> s = long("0xL")
>> ValueError: invalid literal for long(): 0xL
>> 
>> s = long("0x")
>> ValueError: invalid literal for long(): 0xL
>> 
>> What can I do? 
>> 
>> Thank you in advance.
>> Stefan
> 
> Leave out the "0x" prefix and tell long() that you're using base 16:
> 
 long("", 16)
> 4294967295L


Or leave the prefix in, and tell Python to use the prefix to predict the
base:

py> long("0xL", 0)
4294967295L



-- 
Steven.

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


Re: path module / class

2005-11-18 Thread Peter Hansen
Neil Hodgson wrote:
> Chris:
> 
>> What is the status of the path module/class PEP?  Did somebody start
>> writing one, or did it die?  I would really like to see something like
>> Jason Orendorff's path class make its way into the python standard
>> library.
> 
>There is no PEP yet but there is a wiki page.
> http://wiki.python.org/moin/PathClass
>Guido was unenthusiastic so a good step would be to produce some 
> compelling examples.

Compelling to whom?  I wonder if it's even possible for Guido to find 
compelling anything which obsoletes much of os.path and shutil and 
friends (modules which Guido probably added first and has used the most 
and feels most comfortable with).

Personally, I find almost all uses of path.py to be compelling, most 
especially when I consider it from the points of view of "readability", 
"explicitness", "beauty", "simple", "flat", let alone "practical" 
(having all those tools in one place).  Those were all from Tim 
channeling Guido, but perhaps it was a noisy channel...  And Guido's 
views on consistency are well documented ;-) so the fact that the 
alternative to path.py is incredibly inconsistent probably has no weight 
in the argument.

Not so facetiously though: if the examples given haven't proven 
compelling, is it realistic to think that someone will dig up an example 
which suddenly changes Guido's mind?  I suspect it's more realistic to 
think, as with the ternary operator, that he either will or won't, and 
examples proposed from outside won't have much if any impact on his 
thinking.

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


Re: different binding behavior

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 15:34:36 +0100, Gabriel Zachmann wrote:

> i don't see why there should be only one instance of Int with the value 0.

"Small" ints are cached, so there may be only one instance of the int with
value 0. However, that's an implementation detail, which may change from
version to version, and is not generally true:

py> x = 0; y = 3-3
py> x == y
True
py> x is y
True

py> x = 35791; y = 3579*10+1
py> x == y
True
py> x is y
False

So in general, there can be many instances of int with the same value.
That's not what immutable means.



-- 
Steven.

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


Re: textwrap.dedent() drops tabs - bug or feature?

2005-11-18 Thread Peter Hansen
Steven Bethard wrote:
> Note that even though the tabs are internal, they are still removed by 
> textwrap.dedent().  The documentation[1] says:
...
> So it looks to me like even if this is a "feature" it is undocumented. 
> I'm planning on filing a bug report, but I wanted to check here first in 
> case I'm just smoking something.

While I wouldn't say it's obvious, I believe it is (indirectly?) 
documented and deliberate.

Search for this in the docs:
"""
expand_tabs
 (default: True) If true, then all tab characters in text will be 
expanded to spaces using the expandtabs() method of text.
"""

(This is not to say a specific rewording of the docs to lessen any 
confusion in this area wouldn't be welcomed.)

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


Re: examining python objects

2005-11-18 Thread rurpy
"Chris Mellon" <[EMAIL PROTECTED]> wrote:
On 18 Nov 2005 14:05:05 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> -- snip --
> > Writing my own __repr__() is emphatically what I don't
> > want to do!  That is no better than debugging by inserting
> > print statements, a technique from the 1980's.
>
> It's still a good idea, though

Yes and I often resort to it when I have no other choice.
But it is often faster and more efficient to step through
a section of problem code in pdb and look at variables.
(And no I don't want to use a hevyweight or gui based ide.)

> > I am surprised (err, astounded actually) that a basic
> > tool like this isn't available.  Besides debugging, I would
> > think it would be very helpful to people leaning python.
>
> All of this functionality is intrinsically available within Python -
> it's a dynamic language and you can easily inspect an object directly
> to see what it looks like. Try (pretty) printing the objects __dict__
> or __slots__.

Well, my reason for posting is that i've spent a couple days
already trying to roll my own and it is not so easy.  For one
thing, my knowlage about all of the nitty gritty of the internals
of objects is limited.  A big part of my wanting this is to help
me understand objects better.  Does __dict__ and __slots__
give you all the attributes of an object?  I thought new-style
objects didn't even have a __dict__.  I notice dir() does not
list __dict__ as an attribute, even though it is one.  You can
see my understanding of these things is rather limited right
now (due in no small part to Python's shitty docs.)

While doing this is a educational, I am (supposed to be) working
on something else I need to finish.  I think it is more efficient to
learn by looking at objects with a pre-written tool, then to spend
a week or more trying to write it myself.  And also, I also don't
like taking days to duplicate something I'm sure has already been
done numerous times.

> > Perhaps one of the Python IDEs contains something
> > like this I could extract from it but I was hoping to shortcut
> > what will be a time consuming search.
>
> wxPython includes a graphical shell & namespace browser which you may
> find useful.
>-- snip --

I'll look for this but I'd rather find something I didn't have to hack.
What a bummer, maybe I should be posting this to the "reinventing
the wheel" thread.  :-(

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


Re: Confused about namespaces

2005-11-18 Thread Alex Martelli
KvS <[EMAIL PROTECTED]> wrote:

> > There's no reason not to just "import wx" if you want that.
> 
> Yes, that's clear. But if you would make some huge application that has
> a large number of nested modules, each importing the former one, then
> avoiding the use of "from ... import *" would mean that you have to use
> long references like foo1.foo2 to get to the lowest modules plus

Not at all -- you may perfectly well "import a.b.c.d as e" and use e as
the reference throughout the importing module.

But the point is, modules should be MODULAR (duh) -- if I 'import x' I
should NOT rely on what x itself imports (and so on transitively), just
on what x ``exports'', so to speak, at its TOP level.  The Law of
Demeter in its simplified form "if you have more than one dot in your
reference you're doing things wrong" applies.  In fact, the many-dots
form of module naming is intended for nested PACKAGES, *NOT* for
"modules which import each other".

> that you'd have to check each module for imports outside this tree.

Why would you have to check any module for such "outside imports"?  I
don't see the need for any checks.


If you just simply forget the very _existence_ of "from X import *",
your Python code can only grow better as a result.  I earnestly hope it
disappears come Python 3.0 time...


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


Re: Hot to split string literals that will across two or more lines ?

2005-11-18 Thread Steven D'Aprano
On Fri, 18 Nov 2005 15:59:30 +1100, Ben Finney wrote:

> Tony Nelson <[EMAIL PROTECTED]> wrote:
>> While we're at it, I use bracketing instead of line continuation:
>> 
>> print ( "a long string, longer than this "
>> "and some more of the string" )
> 
> To continue the pedantry: Those are parentheses, not brackets.

To out-pedant your pedantry, "bracket" is a general term for any and all
of the various punctuation marks used to bracket a substring or phrase.
Brackets include:

parentheses or round brackets ( )
square brackets [ ]
braces or curly brackets { }
chevrons or angle brackets 〈 〉

The symbols for chevrons are not available on common keyboards, are not
available in ordinary ASCII, and may not show up correctly in many
typefaces, so a common alternative is to substitute less than and greater
than signs < > as brackets. HTML and XML use that convention.

Note that "square brackets" is the formal name for the specific
brackets which are square: the adjective is not redundant.

Double chevrons « » (and occasionally single) are used as quotation
marks in some European languages, for instance French and Italian, and
sometimes Dutch. When used as quote marks, the French term guillemet is
sometimes used as synonym for chevron.

-- 
Steven.

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

Re: Confused about namespaces

2005-11-18 Thread Diez B. Roggisch
  > Am I understanding correctly that if you have a module foo importing wx
> and a module main importing both foo and wx there are actually two
> instances of wx created, one referenced to by (at top level) foo.wx.*
> and one wx.*? If this is indeed the case it isn't too good for the
> performance doing this importing of wx multiple times right?
>

No, they aren't two instances. The first import will evaluate the 
wx-module (there could be code in there executed upon importing it). All 
subsequent imports of that module will only bind the already imported 
module to the name.

So - the way to have one module be available in several other modules is 
to import them in each of them - causing actually close to none 
overhead, as the import statement is evaluated only once per file 
(unless you put it in a loop or something, but this still only would 
return the same reference.)

Regards,

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


Embedded Python interpreter and sockets

2005-11-18 Thread wahn
Hi,

Here is a problem I came across and need some help with. I developed a
little Python script with some classes which runs standalone and
communicates with a database via sockets. So far everything works fine.
I also successfully embedded the Python interpreter into a plugin for a
commercial 3D package (in this case Houdini - http://www.sidefx.com/ -
using the HDK). I can use the interpreter to run Python commands and
get values back and forth between Python and C++. Anyway, I can also
successfully import SOME modules, but unfortunately not ALL. One
example would be the socket module which works fine in the standalone
version of my Python script but NOT from the embedded interpreter:

Traceback (most recent call last):
  File "", line 40, in ?
  File "/swdevl/jwalter/Houdini/ROPS/HoudiniToMayaBake/damn.py", line
10, in ?
import socket
  File
"/job/SYSTEMS/3PS/python/2.4.1/linux_intel//lib/python2.4/socket.py",
line 45, in ?
import _socket
ImportError:
/job/SYSTEMS/3PS/python/2.4.1/linux_intel/lib/python2.4/lib-dynload/_socket.so:
undefined symbol: PyObject_GenericGetAttr

Other modules which get imported before just work fine (e.g. re and
string) ...

The Python library gets linked into the plugin DSO as a static library
... Any ideas what's going wrong and why?

Cheers,

Jan

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


Re: Reinvent no more forever

2005-11-18 Thread ismaelgfk

Ben Finney wrote:
> Fine sentiments. What does this mean for PyPI though? How should those
> of us who also want to "reinvent no more forever" proceed? How do we
> deal with the rampant proliferation of a zillion implementations of
> some standard idiom in PyPI?

How about some kind of "mega util" package? One big package with all
those recurring reinventions. If it gets popular enough, I'm sure it
could stop so much reinvention.
Perhaps even pack all the similar-but-different implementations in one
package (and then have
from wheel import enumA
from wheel import enumB , etc.. )

Actually, "The wheel" is quite a good name for such a package :-P

I'm thinking that a Wiki would be quite suitable for development, to
incite more contributions (rather than only CVS).

What do you think?

Ismael

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


Re: Importing a class without knowing the module

2005-11-18 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:
> You did help me to better understand some of the roots of your many
> mistaken assertions in this thread, from your first "How about adding
> Foo.__file__" proposal onwards, yes -- thank you. 

I claim I haven't made a single mistaken assertion in this
thread. Referencing class.__file__ instead of module.__file__ was a
mistake, but not an assertion. In fact, when I did that, I asked the
OP what was wrong with it.

You have read into some of the things I've written assertions which
simply weren't there.  For instance, I said "you may not have the
module name", which led you to ask for an example of a class without
an __module__ attribute. I never asserted that you could get a class
without a __module__ attribute, merely that you could get classes
where the module name wasn't useful. if you had spent your time
reading the text a bit more carefully, you might have saved us both
some time.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


deleting registry keys and value

2005-11-18 Thread sdb1031
Hi,

I am trying to learn how to write, change and delete registry keys and
values of a remote computer via Python's _winreg module.  So far, I've
been able to programmatically create a value and read the value.
However, I am unable to figure out how to delete the value.  Using the
following code, I get the following output:

MyNewKey c:\winnt\explorer2.exe 1
Traceback (most recent call last):
  File "C:\Documents and Settings\sbriley.STAT\Desktop\testreg.py",
line 12, in
?
DeleteValue(aKey, r"MyNewKey")
WindowsError: [Errno 5] Access is denied

I have administrative access on the target machine and can delete the
key manually by connecting remotely using regedit.  Here's the code.
BTW,  does anyone know how to provide credentials to the remote system
if it has a different user/pass than the host system?  I don't believe
that ConnectRegistry() will allow this.

Thanks,

Steve

from _winreg import *
#create the key
aReg = ConnectRegistry("remotecomputer",HKEY_LOCAL_MACHINE)
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
0, KEY_WRITE)
SetValueEx(aKey,"MyNewKey",0, REG_SZ, r"c:\winnt\explorer2.exe")

aReg = ConnectRegistry("remotecomputer",HKEY_LOCAL_MACHINE)
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
KEY_ALL_ACCESS)
n,v,t = EnumValue(aKey,5)
#print out the key
print n, v, t
CloseKey(aKey)

aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
KEY_ALL_ACCESS)
DeleteValue(aKey, "MyNewKey")

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


Is there a way to create a button in either pygame or livewires?

2005-11-18 Thread Nathan Pinno
Hey all,

Is there a way to create a button in either pygame or livewires, that is 
able to be clicked and when clicked sends a command to restart the program?

Thanks,
Nathan Pinno

-- 
For great sites go to: http://www.the-web-surfers-store.com
MSN Messenger: [EMAIL PROTECTED],com
Yahoo! Messenger: spam_swatter31
ICQ: 199020705
AIM: f3mighty 



-- 

.
  >   Posted thru AtlantisNews - Explore EVERY Newsgroup  <
  >   http://www.AtlantisNews.com  --  Lightning Fast!!!  <
  >   Access the Most Content * No Limits * Best Service  <
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread KvS
> There's no reason not to just "import wx" if you want that.

Yes, that's clear. But if you would make some huge application that has
a large number of nested modules, each importing the former one, then
avoiding the use of "from ... import *" would mean that you have to use
long references like foo1.foo2 to get to the lowest modules plus
that you'd have to check each module for imports outside this tree.

If you would use "from ... import *" (except at top level) you have to
be aware of overriding, but you can also use this to your advantage and
any foo1.attr reference would just work right, without further ado...
Or would in such a case a class hierarchy be the thing to use?

> No. It creates the foos within each module, but which foo you have
> access to in the importing module is determined by the order of
> import.

Am I understanding correctly that if you have a module foo importing wx
and a module main importing both foo and wx there are actually two
instances of wx created, one referenced to by (at top level) foo.wx.*
and one wx.*? If this is indeed the case it isn't too good for the
performance doing this importing of wx multiple times right?

- Kees

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


Re: Underscores in Python numbers

2005-11-18 Thread [EMAIL PROTECTED]
Personally, I would rather see the int() and float() function be
smarter to take what is used for this, i.e. :

a = int("1,234,567")

Of course, also support the locale variant where the meaning of "," and
"." is swapped in most European countries.

Gustav Hållberg wrote:
> I tried finding a discussion around adding the possibility to have
> optional underscores inside numbers in Python. This is a popular option
> available in several "competing" scripting langauges, that I would love
> to see in Python.
>
> Examples:
>   1_234_567
>   0xdead_beef
>   3.141_592
>
> Would appreciate if someone could find a pointer to a previous
> discussion on this topic, or add it to a Python-feature-wishlist.
> 
> - Gustav

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


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 16:09:44 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Hmm. But actually I was doing this import from GUIclasses with exactly
> this in mind, namely that it would make wx also available at top level.

There's no reason not to just "import wx" if you want that.

> I (in my naive understanding) see this as "natural" and actually
> desirable, how could this cause confusing bugs? Do you mean multiple
> "from ... import *"'s 'on top of each other' would cause foo1.foo2.attr
> and foo1.attr both would become just attr and therefore ambiguous at
> top level?

the second import will overwrite the first, making the first inaccessible

>
> If you import foo in two different modules, does the interpreter then
> create one instance of foo and create a reference in both modules to
> the same foo rather than creating two different instances of foo?
>

No. It creates the foos within each module, but which foo you have
access to in the importing module is determined by the order of
import.

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


Re: Can anyone tell me if pygame and Tkinter can work together?

2005-11-18 Thread Nathan Pinno
Even its from one or two external libraries like Tkinter and pygame? I 
prefer to load what I need, not to constantly have to call it by its library 
dot its_name. It makes easier coding for me. I try to keep my code as simply 
as possible. Wonder if its possible to use a Tkinter question to make a 
pygame run again (example being you get killed on a level and you want to 
play again without exiting)?

-- 
For great sites go to: http://www.the-web-surfers-store.com
MSN Messenger: [EMAIL PROTECTED],com
Yahoo! Messenger: spam_swatter31
ICQ: 199020705
AIM: f3mighty
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Nathan Pinno wrote:
>
>> It's a warning that says:
>>
>> Can only use * in top level or something like that.
>>
>> It's kind of annoying
>
> why?  importing tons of unknown stuff into a local namespace is
> rather silly, and makes it impossible for the compiler to properly
> analyze your code -- which means that you cannot use nested
> scoping.  the language reference says:
>
>The from form with "*" may only occur in a module scope.
>If the wild card form of import -- "import *" -- is used in a
>function and the function contains or is a nested block with
>free variables, the compiler will raise a SyntaxError.
>
> future versions of Python will most likely issue a SyntaxError also
> for "import *" in non-nested functions.
>
>> but the program still ran after I made the import * lines top level,
>> and removed the def's.
>
> moving the "import *" line to the module scope would have been
> enough; functions can refer to module-level variables just fine.
>
> you might wish to read up on Python scoping rules:
>
>http://docs.python.org/ref/naming.html
>
> 
>
> 



-- 

.
  >   Posted thru AtlantisNews - Explore EVERY Newsgroup  <
  >   http://www.AtlantisNews.com  --  Lightning Fast!!!  <
  >   Access the Most Content * No Limits * Best Service  <
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behaviour of enumerated types

2005-11-18 Thread Ben Finney
Bengt Richter <[EMAIL PROTECTED]> wrote:
> Ben Finney <[EMAIL PROTECTED]> wrote:
> >Getting a numeric index might be useful in a language such as
> >Pascal, with no built-in dict or sequence types. In Python, where
> >any immutable object can be a dict key, and any sequence can be
> >iterated, it seems of no use.
>
> Does your concept of enumeration not have a fixed order of a set of
> names?

It does. The values are iterable in the same order they were specified
when creating the Enum.

> If it does, what is more natural than using their index values as
> keys to other ordered info?

I don't see why. If you want sequence numbers, use enumerate(). If
not, the enum object itself can be used directly as an iterable.

> OTOH, the index values (and hence my enums) are[1] not very good as
> unique dict keys, since they compare[2] promiscuously with each
> other and other number types.

Indeed, that's why (in my design) the values from the enum are only
useful for comparing with each other. This, to me, seems to be the
purpose of an enumerated type.

> To me the int correspondence is as expectable and natural as
> a,b,c=range(3) (at least as a default) though I think different
> enumerations should be different types.

That's a complete contradiction, then. If you want them to be
different types, you don't want them to be integers.

> Note that the ordering of int values makes the instances nicely
> sortable too, e.g.,

That only means the enum values need to compare in the same sequence;
it doesn't mean they need to correspond to integer values.

> But bottom line, I really thing the int base type is more than an
> implementation detail. I think it's natural for an _ordered_ set of
> names ;-)

I think I've addressed all your current concerns; I don't believe an
inherent correlation to integers is necessary at all.

It's no more necessary than saying that ["a", "b", "c"] requires that
there be some specific correlation between the values of that list and
the integers 0, 1, 2. If you *want* such a correlation, in some
particular case, use enumerate() to get it; but there's nothing about
the values themselves that requires that correspondence.

> I'll go look at PyPI now ;-)

Feedback appreciated :-)

-- 
 \ "Oh, I realize it's a penny here and a penny there, but look at |
  `\  me: I've worked myself up from nothing to a state of extreme |
_o__)   poverty."  -- Groucho Marx |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread KvS
Hmm. But actually I was doing this import from GUIclasses with exactly
this in mind, namely that it would make wx also available at top level.
I (in my naive understanding) see this as "natural" and actually
desirable, how could this cause confusing bugs? Do you mean multiple
"from ... import *"'s 'on top of each other' would cause foo1.foo2.attr
and foo1.attr both would become just attr and therefore ambiguous at
top level?

If you import foo in two different modules, does the interpreter then
create one instance of foo and create a reference in both modules to
the same foo rather than creating two different instances of foo?

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


Re: Underscores in Python numbers

2005-11-18 Thread Dave Hansen
Sorry for the delayed response.  I somehow missed this earlier.

On Tue, 8 Nov 2005 15:39:09 + (UTC) in comp.lang.python,
[EMAIL PROTECTED] (Roy Smith) wrote:

>Dave Hansen  <[EMAIL PROTECTED]> wrote:
>> Of course, I write _far_ more code in C than Python.  But I've seen
>> enough bugs of the sort where someone wrote 120 when they meant

Digression: 1 was enough.

>> 1200, that I see great value in being able to specify 12_000_000.
>
>I'll admit that being able to write 12_000_000 would be convenient.
>On the other hand, writing 12 * 1000 * 1000 is almost as clear.  In C,

Perhaps, but it's pretty obvious that something's wrong when you have
to resort to ugly tricks like this to make the value of a simple
integer constant "clear."

And think about 64 (or longer) -bit unsigned long long hexadecimal
values.  How much nicer is 0xFFF0_FF0F_F0FF_0FFF_ULL than
0xFFF0FF0FF0FF0FFFULL?  I guess we could do something like
0xFFF0ULL<<16)|0xFF0FULL)<<16)|0xF0FFULL)<<16)|0x0FFFULL), but I'm
not sure it's any better.

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread [EMAIL PROTECTED]

Peter Otten wrote:
> Daniel Crespo wrote:
>
> > How can I do
> >
> > new_variable = (variable) ? True : False;
> >
> > in Python in one line?
>
> new_variable = variable
>
> :-)

I would assume the OP is just lazy and don't want to type :

new_variable = (variable_is_true_value) ?
some_expression_when_variable_is_true_value is true :
some_expression_when_variable_is_true_value is false

rather than simple True/False.

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


Re: Importing a class without knowing the module

2005-11-18 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:
   ...
> I suggested using the module, and mentioned that he might not have a
> better choice than to use __file__ anyway. You overlooked the mention
> of __module__ to complain that __file__ wasn't his best choice,
> because he could use __module__. All I did was point out what you
> overlooked, and have been answering your questions about it ever

Sorry to have given the impression that I overlooked something -- I
didn't KNOW whether I had, which is why I checked back with you about
it, but apparently I hadn't.

> since. If you don't think __file__ is such a good idea, you should
> have said so in the first place.

And I did!  My exact words in my first post to this thread were "I think
that using the class's __module__ rather than __file__ should be what
you want" -- a pretty clear indication that I don't think using __file__
is a hot idea, don't you think?

> Instead, you asked questions about

About what would be the cases where the module's name was not available,
as you had claimed it could be; turns out that you haven't given a
single example yet, just one (__main__) where the module name is
perfectly available, though it may not be *useful* (and there's no
special reason to guess that the *file*'s name would be any use either).

> it. Trying to help you out, I answered them. If trying to help someone
> who seems to be having trouble understanding an issue is "dwelling on
> the issue", well, I'm glad we have a newsgroup full of people who
> dwell on issues.

You did help me to better understand some of the roots of your many
mistaken assertions in this thread, from your first "How about adding
Foo.__file__" proposal onwards, yes -- thank you.  However, I am now
reasonably convinced that your attempt to *defend*, at some level, those
assertions, appear to have no sound technical basis, just a
defensiveness that (in my mind) justifies the use of the word
"dwelling".  But we do fully agree that trying to be helpful, per se, is
never inherently blameworthy, whether one succeeds or fails in the
attempt -- so, thanks for your many (and mostly better based than this
one) attempts to be of help to c.l.py posters.


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


Re: running functions

2005-11-18 Thread Tom Anderson
On Thu, 17 Nov 2005, Scott David Daniels wrote:

> Gorlon the Impossible wrote:
>
>> I have to agree with you there. Threading is working out great for me
>> so far. The multiprocess thing has just baffled me, but then again I'm
>> learning. Any tips or suggestions offered are appreciated...
>
> The reason multiprocess is easier is that you have enforced separation. 
> Multiple processes / threads / whatever that share reads and writes into 
> shared memory are rife with irreproducible bugs and untestable code. 
> Processes must be explicit about their sharing (which is where the bugs 
> occur), so those parts of the code cane be examined carefully.

That's a good point.

> If you program threads with shared nothing and communication over Queues 
> you are, in effect, using processes.  If all you share is read-only 
> memory, similarly, you are doing "easy" stuff and can get away with it. 
> In all other cases you need to know things like "which operations are 
> indivisible" and "what happens if I read part of this from before an 
> update and the other after the update completes, .

Right, but you have exactly the same problem with separate processes - 
except that with processes, having that richness of interaction is so 
hard, that you'll probably never do it in the first place!

tom

-- 
science fiction, old TV shows, sports, food, New York City topography,
and golden age hiphop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Dave Hansen
On Fri, 18 Nov 2005 14:15:06 -0800 in comp.lang.python, Scott David
Daniels <[EMAIL PROTECTED]> wrote:

>
>
>Don't try to force everything to the type you expect,
>use things as they are; embrace duck-typing.
>

Wrong, the grammar you have.
Do not Everything to the type you expect force.
Do or do not, there is no try.
Things as they are use.
Duck-typing embrace.

>:-)

Ditto.  Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 15:29:43 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Ok, makes sense but didn't seem "natural" to me, although it is an
> obvious consequence of what you just pointed out, namely that modules
> are evaluated in their own namespace, something to keep in mind... On
> the other hand it does apparently work recursively "the other way
> around" since I didn't explicitly import wx in main.py but only
> indirect via importing GUIclasses in which wx is imported right?
>

it worked because all the code that used stuff from the wx namespace
was in GUIclasses.py. If you tried to use create wx classes directly
in your toplevel file it would fail unless you did an "import wx"
first.

Now, as a slight consequence of the specific way you imported, it may
appear to do something different - when GUIClasses.py imported wx, an
entry in the modules namespace was created with the value "wx", and
the value being the wx module. When you do "from GUIClasses import *",
that imports all the symbols in GUIClasses namespace into your local
namespace, including the "wx" entry. This kind of cascading behavior
is one reason that "from foo import *" is frowned up, because the
namespace pollution can cause confusing bugs.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread [EMAIL PROTECTED]
The cleanest(IMO) is this :

a = (predicate and [if_true_expr] or [if_false_expr])[0]

This would give you the necessary "short circuit" behaviour no matter
what.

a = predicate and if_true_expr or if_false_expr

works most of the time but should if_true_expr turns out to be 0 or
something like that(python False equvialent), the if_false_expr will
still be executed, that becomes a logic error. an example :
a = int_str is None and None or int(int_str)


a = [if_false_expr, if_true_expr][predicate]

This doesn't have the "short circuit" feature and the order is
reversed(harder to read for people familiar with ternary operator).
Cannot be used in some case. like this :

a = [0, int(int_str)][int_str is not None]

here int(int_str) may cause exception if None is a valid value.

The lambda form suggested by others is another variant of the first one
above where you get the short circuit feature but too complex to read.

I don't understand why people are so aganst ternary operator. It is a
must for list comprehension/generator expression(and I believe the
reason it has finally been approved), if/else block or try/except just
don't work in these situations.

Daniel Crespo wrote:
> Hi!
>
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}
> 
> Any suggestions?
> 
> Thanks
> 
> Daniel

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


Re: Choose meaningful subjects for posts

2005-11-18 Thread Mike Meyer
Micah Elliott <[EMAIL PROTECTED]> writes:
> On Nov 18, [EMAIL PROTECTED] wrote:
>> Grant> Obligatory aside: I'm completely baffled why anybody would choose
>> Grant> the mailing list format over Usenet.  I don't even read mailing
>> Grant> lists via mailing lists.  I recommend gmane.org's NNTP server for
>> Grant> all your mailing list needs.
>> For the same reason I don't like web forums as a means of
>> communication.  I would much rather operate in an interrupt-driven
>> mode than have to remember to poll some external service to get my
>> daily helping of information.
> Agreed!

That's actually how I decide which form I want to use. Mail lists for
thigns I want to interrupt me, newsgroups for things I want to poll.

> If you have any suggestions for console-based newsreaders, I'm all
> ears.  I have tried to setup "tin" in the past but the voluminosity of
> its documentation made me give up.

Gnus. Not only will it run in a console, but when run in an X
environment, it'll give you (user-configurable) menu bars, tool bars,
and clickable articles.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread KvS
Ok, makes sense but didn't seem "natural" to me, although it is an
obvious consequence of what you just pointed out, namely that modules
are evaluated in their own namespace, something to keep in mind... On
the other hand it does apparently work recursively "the other way
around" since I didn't explicitly import wx in main.py but only
indirect via importing GUIclasses in which wx is imported right?

Thanks. :).

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


Re: Adding through recursion

2005-11-18 Thread [EMAIL PROTECTED]

Ben Finney wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > def add(x, y):
> > if x == 0:
> > print y
> > return y
> > else:
> > x -= 1
> > y += 1
> > add(x, y)
>
> To add to the other good advice in this thread:
>
> This is just one of many reasons why I advocate always having a
> *single* return statement, at the *end* of the function. I usually
> start out writing my function setting a default return value, and the
> return statement immediately below.
>
> In your case, the default return value is None, so let's make that
> explicit.
>
> def recursive_add(x, y):
> result = None
> return result
>
> Then, the rest of the function's responsibility is about changing that
> default value if necessary.
>
> def recursive_add(x, y):
> result = None
> if x == 0:
> print y
> result = y
> else:
> x -= 1
> y += 1
> recursive_add(x, y)
> return result
>
> With this structure, it becomes quickly obvious what's gone wrong: one
> of the branches is not changing the default return value.
>
> def recursive_add(x, y):
> if x == 0:
> print y
> result = y
> else:
> x -= 1
> y += 1
> result = recursive_add(x, y)
> return result
>
> I find this much less error-prone than hiding return statements in
> branches throughout the function; if the only return statement is at
> the very end of the function, it becomes much easier to read.

I don't see this as clearer than multiple return. But then it I believe
it is really preference or style, rather than obvious
advantage/disadvantage.

Interestingly, this kind of error is easy to spot by the compiler in C.

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


Re: Web-based client code execution

2005-11-18 Thread Chris Mellon
On 11/18/05, Paul Watson <[EMAIL PROTECTED]> wrote:
> Steve wrote:
> > AJAX works because browsers can execute javascript.  I don't know of a
> > browser that can execute python.  Basically your stuck with java or
> > javascript because everything else really isn't cross platform.
>
> Well, I guess the Grail browser could run Python, but I do not think I
> can go there.
>
> I need READ access to the users local disk storage.  Can I do this in
> Javascript, or should I bite the bullet and turn to ActiveX?

This can only be done with scripts by disabling or bypassing browser
security restrictions. It can't even be done by zone in IE, only
globally, and I don't know if you can do it at all in Mozilla based
browsers.

A signed activex control or Java Applet (that registers for the
appropriate sandbox permissions) will work.

Overall, it's probably simplest not to do any of these and simply
write a standard application that you have users download and run.
This is the safest and most straightforward solution, and honestly
what you save in configuration managment when people call you
wondering why it doesn't work is probably worth the extra effort it
takes them to actually run your application.

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


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 15:04:23 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> to start with, excuse me, I'm still learning programming alltogether,
> probably I'm making some fundamental mistake here...
>
> I have the files settings.py, GUIclasses.py and main.py in the same
> directory. In the file main.py are the statements:
>
> import settings
> from GUIclasses import *
>
> class Toepassing(wx.App):
> def OnInit(self):
> window = KFrame(None, "Testerdetest", (1000,900))
> self.SetTopWindow(window)
> window.Show(True)
> return True
>
> app = Toepassing(None)
> app.MainLoop()
>
> In the file GUIclasses.py I have the statements:
>
> import wx
> import wx.lib.mixins.listctrl  as  listmix
>
> class KFrame(wx.Frame):
> def __init__(self, parent, title, Size):
> ...some code...
> self.lst = settings.attrLijst
> some more code..
>
> Now if I run the main.py file I get the error:
>
>   File "G:\Programmeren\Codes contactenlijst\GUIclasses.py", line 40,
> in __init_
> _
> self.lst = settings.attrLijst
> NameError: name 'settings' is not defined
>
> Why is this? Since "from GUIclasses import *" this KFrame is now at
> "the lowest" namespace and should therefore be able to make use of any
> variables living there, including "settings.*", no?
>

import is not like a C/C++ #include - the code in the imported module
is evaluated in it's own namespace, not in the namespace of the
importing file.

So no, this is expected behavior, and should be solved by importing
settings in GUIclasses.py as well.

You don't need to worry about multiple or redundent imports.


> Thanks in advance!
>
> - Kees
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing a class without knowing the module

2005-11-18 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:
> Mike Meyer <[EMAIL PROTECTED]> wrote:
>...
>> > How do you arrange a module so that its classes' __module__ attributes
>> > don't tell you the name of the module "that would be useful", yet the
>> > module's __file__ DOES give you information that you can usefully
>> > process, heuristically I assume, to infer a module name that IS useful?
>> So what module name do you import if C.__module__ is __main__?
> In this case, I would strongly suggest that raising an exception upon
> the attempt to marshal is better than trying to guess that the file
> holding the main script could later be innocuously imported from a
> different script, or, alternatively, that the same main script would be
> running when a future unmarshaling attempt is done.  "In the face of
> ambiguity, refuse the temptation to guess" is a sound principle.

Once you move the data to another system, pretty much anything you do
to try and figure out how to load the code that defines a class is
ambiguous. After all, it may not be present at all. The only way to
avoid ambiguity is to serialize the code.

>> > I just don't see it, which of course doesn't mean it can't be done, with
>> > sufficient evil ingenuity.  But since you're the one arguing that this
>> > case is important enough to be worth dwelling on,
>> I'm not dwelling on it, you are.  All I did was recommend using the
>> module name if you had one, and if not then the file name was your
>> best bet. You chose to ignore part of my statement to focus on the
>> part you disagreed with, because you thought what I had suggested in
>> the first place was a better idea. I pointed out this oversight on
>> your part, and you've been dwelling on it ever since.
> I don't see the history of this thread the same way as you do,
> apparently.

Given that this is netnews, that's not at *all* surprising.

> i.e., your post, to which I was replying, was about 3 hours later than
> my original one.  My original post said:

Ok, so you suggested it first. Congratulations. I didn't see them in
that order. I didn't reply to that post of yours. I replied to the OP
pointing out that the problem with __file__ being system-dependent. He
never suggested using module.

> so it seems incorrect to say that you had "suggested in the first place"
> the idea of using __module__; on the contrary, in a previous post of
> yours, the first one of yours on this thread, specifically:
>> How about adding Foo.__file__ to the serialized data?
> So, it seems to me that you're the one dwelling on the issue, because
> you made the original wrong suggestion, and after I corrected it,
> repeated and are now defending the gist of it (though not the obviously
> wrong idea of using a non-existent __file__ attribute of the Foo class).

I never did anything to defend it. As soon as the OP pointed out that
he'd didn't like __file__ because of the loss of system independence,
I suggested using the module, and mentioned that he might not have a
better choice than to use __file__ anyway. You overlooked the mention
of __module__ to complain that __file__ wasn't his best choice,
because he could use __module__. All I did was point out what you
overlooked, and have been answering your questions about it ever
since. If you don't think __file__ is such a good idea, you should
have said so in the first place. Instead, you asked questions about
it. Trying to help you out, I answered them. If trying to help someone
who seems to be having trouble understanding an issue is "dwelling on
the issue", well, I'm glad we have a newsgroup full of people who
dwell on issues.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Confused about namespaces

2005-11-18 Thread KvS
Hi all,

to start with, excuse me, I'm still learning programming alltogether,
probably I'm making some fundamental mistake here...

I have the files settings.py, GUIclasses.py and main.py in the same
directory. In the file main.py are the statements:

import settings
from GUIclasses import *

class Toepassing(wx.App):
def OnInit(self):
window = KFrame(None, "Testerdetest", (1000,900))
self.SetTopWindow(window)
window.Show(True)
return True

app = Toepassing(None)
app.MainLoop()

In the file GUIclasses.py I have the statements:

import wx
import wx.lib.mixins.listctrl  as  listmix

class KFrame(wx.Frame):
def __init__(self, parent, title, Size):
...some code...
self.lst = settings.attrLijst
some more code..

Now if I run the main.py file I get the error:

  File "G:\Programmeren\Codes contactenlijst\GUIclasses.py", line 40,
in __init_
_
self.lst = settings.attrLijst
NameError: name 'settings' is not defined

Why is this? Since "from GUIclasses import *" this KFrame is now at
"the lowest" namespace and should therefore be able to make use of any
variables living there, including "settings.*", no?

Thanks in advance!

- Kees

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


Re: Reading a file in same directory as code with relative path

2005-11-18 Thread [EMAIL PROTECTED]
Answer to a similar question:

http://groups.google.com/group/comp.lang.python/msg/c01f292d7926f393?hl=en&;

If you want a way that will work regardless if your module is run
interactively, imported, or just run by itself, this is a solution that
will always work:

:: \wherever\wherever\ (the directory your module is in,
obviously somewhere where PYTHONPATH can
see it)

 danmodule.py  (your module)

 danmodule_xml\(a subdirectory in the same directory as
your module;
it will only have 2 files in it)

:: __init__.py (an empty textfile in danmodule_xml\,
only here to make danmodule_xml\
work like a package)

:: data.xml(your xml file in danmodule_xml\)

Here is the Python code for loading the file:

#  #
import xml.dom.minidom
import os.path
import danmodule_xml

xml_data_path = os.path.split(danmodule_xml.__file__)[0]

xml_file_fullpath = os.path.join(xml_data_path, 'data.xml')

document = xml.dom.minidom.parse(xml_file_fullpath)
#  #

Obviously, if you have more than 1 xml files, just put them all in
"danmodule_xml\".

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


Re: Adding through recursion

2005-11-18 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Ben Finney <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > def add(x, y):
> > if x == 0:
> > print y
> > return y
> > else:
> > x -= 1
> > y += 1
> > add(x, y)
...
> def recursive_add(x, y):
> if x == 0:
> print y
> result = y
> else:
> x -= 1
> y += 1
> result = recursive_add(x, y)
> return result
> 
> I find this much less error-prone than hiding return statements in
> branches throughout the function; if the only return statement is at
> the very end of the function, it becomes much easier to read.

Well, it's sure clearer where it returns.  On the other
hand, now you have to analyze the block structure to
know that the 3rd line assignment is still going to be
in effect when you get to the return.  That's easy in
this case, of course, but make the structure more complex
and add a loop or too, and it can be hard.  Where if you
see a return statement, you know for sure.

State variables are analogous to goto in a way, similar
sort of spaghetti potential.  It may or may not help to
have all the strands come out at the same spot, if the
route to that spot could be complicated.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: examining python objects

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 14:05:05 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> __repr__ almost always only prints a summary of it's
> object, not the detailed internal structure that I want to
> see.  When it prints values, that are not pretty-printed,
> nor are the objects that constitute the value printed
> recursively.
>
> Writing my own __repr__() is emphatically what I don't
> want to do!  That is no better than debugging by inserting
> print statements, a technique from the 1980's.
>

It's still a good idea, though

> I am surprised (err, astounded actually) that a basic
> tool like this isn't available.  Besides debugging, I would
> think it would be very helpful to people leaning python.
>

All of this functionality is intrinsically available within Python -
it's a dynamic language and you can easily inspect an object directly
to see what it looks like. Try (pretty) printing the objects __dict__
or __slots__.

> Perhaps one of the Python IDEs contains something
> like this I could extract from it but I was hoping to shortcut
> what will be a time consuming search.
>

wxPython includes a graphical shell & namespace browser which you may
find useful.

> Ben Finney wrote:
> > [EMAIL PROTECTED] wrote:
> > > Is there a function/class/module/whatever I can use to look at
> > > objects?
> >
> > The repr() function is what you want.
> >
> > > I want something that will print the object's value (if any) in
> > > pretty-printed form, and list all it's attributes and their values.
> > > And do all that recursively.
> >
> > The repr() function returns what the object's __repr__ method returns.
> > You'll notice that the builtin container types (string, set, list,
> > dict, ...) will show the values of their referred objects also.
> >
> > Define the __repr__ method on your classes so that they show whatever
> > information you think is useful for debugging.
> >
> > --
> >  \   "If you go flying back through time and you see somebody else |
> >   `\   flying forward into the future, it's probably best to avoid eye |
> > _o__)contact."  -- Jack Handey |
> > Ben Finney
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing a class without knowing the module

2005-11-18 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:
   ...
> > How do you arrange a module so that its classes' __module__ attributes
> > don't tell you the name of the module "that would be useful", yet the
> > module's __file__ DOES give you information that you can usefully
> > process, heuristically I assume, to infer a module name that IS useful?
> 
> So what module name do you import if C.__module__ is __main__?

In this case, I would strongly suggest that raising an exception upon
the attempt to marshal is better than trying to guess that the file
holding the main script could later be innocuously imported from a
different script, or, alternatively, that the same main script would be
running when a future unmarshaling attempt is done.  "In the face of
ambiguity, refuse the temptation to guess" is a sound principle.


> > I just don't see it, which of course doesn't mean it can't be done, with
> > sufficient evil ingenuity.  But since you're the one arguing that this
> > case is important enough to be worth dwelling on,
> 
> I'm not dwelling on it, you are.  All I did was recommend using the
> module name if you had one, and if not then the file name was your
> best bet. You chose to ignore part of my statement to focus on the
> part you disagreed with, because you thought what I had suggested in
> the first place was a better idea. I pointed out this oversight on
> your part, and you've been dwelling on it ever since.

I don't see the history of this thread the same way as you do,
apparently.  I first posted to this thread in a post identified as:
"""
Date: Thu, 17 Nov 2005 17:28:56 -0800
Message-ID: <[EMAIL PROTECTED]>
"""
and later replied to a post of yours identified as:
"""
Date: Thu, 17 Nov 2005 23:27:45 -0500
Message-ID: <[EMAIL PROTECTED]>
"""
i.e., your post, to which I was replying, was about 3 hours later than
my original one.  My original post said:

> BEFORE the text you're commenting on?!), but anyway I think that using
> the class's __module__ rather than __file__ should be what you want.

so it seems incorrect to say that you had "suggested in the first place"
the idea of using __module__; on the contrary, in a previous post of
yours, the first one of yours on this thread, specifically:
"""
Date: Thu, 17 Nov 2005 19:10:39 -0500
Message-ID: <[EMAIL PROTECTED]>
"""
your ENTIRE suggestion -- what you "suggested in the first place" -- was
the entirely wrong:

> How about adding Foo.__file__ to the serialized data?

So, it seems to me that you're the one dwelling on the issue, because
you made the original wrong suggestion, and after I corrected it,
repeated and are now defending the gist of it (though not the obviously
wrong idea of using a non-existent __file__ attribute of the Foo class).

 
> Frankly, I thought you were brighter than that, have no idea why
> you're acting like this, and frankly don't think you need a tutor.  I
> figured this out by fooling around with the interpreter before posting
> in the first place, you certainly know enough to do the same.

"Before posting in the first place" (your post at 19:10 EST) you clearly
had not tested your suggestion (nor had you claimed to, until now).  In
any case, if your specific idea is that mucking around with the __file__
attribute of the __main__ module is a reasonable way to solve the
conumdrum of marshaling instances of classes defined in __main__ (which,
as per the first paragraph of this post, I dispute) it would have been
vastly preferable to say so in the first place, rather than expressing
this particular case as just an "If not" (wrt "You can use the module
name if you have it available") -- particularly since you DO have the
module name available for classes defined in __main__, it's just
suspicious and risky to use it in marshaling.  Incidentally, pickle DOES
just use the module name in marshaling even in this case -- the opposite
tack to what you suggest, and, in its own special way, almost as wrong,
IMHO (just guessing the other way, in the presence of obvious
ambiguity).  Still, pickle does take ONE precaution worth noticing: it
checks that the class it's marshaling is, in fact, the same object
that's available under that class's name from the module it belongs to
-- otherwise (e.g., for classes dynamically defined inside a function),
it raises a PicklingError.

As a general point, refusing to marshal data that strongly smells like
it will be hard or unlikely to unmarshal later is commendable prudence,
and I would recommend this general, prudent approach strongly.


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


Re: How to do "new_variable = (variable) ? True : False;" (php) on python?

2005-11-18 Thread Scott David Daniels
Peter Otten wrote:
> Daniel Crespo wrote:
>>new_variable = (variable) ? True : False;
>>in Python in one line?

> new_variable = variable

Of course to answer your actual question:

new_variable = variable and True or False

But you should consider that Peter has given
you a better answer than you think.


Don't try to force everything to the type you expect,
use things as they are; embrace duck-typing.

:-)

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write an API for a Python application?

2005-11-18 Thread Duncan Grisby
In article <[EMAIL PROTECTED]>,
Piet van Oostrum  <[EMAIL PROTECTED]> wrote:

>A more lightweight solution might be Ice. 
>It is architecturally similar to Corba, but with less overhead.

More lightweight and less overhead in what sense?  The performance
measurements I've seen show that Ice is significantly slower than many
CORBA implementations. If you mean more lightweight in terms of ease
of use, I don't see how. I quite agree that it's more lightweight in
terms of size of specification and difficulty for the ORB implementor,
but that's largely irrelevant to the users of the technology.

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: examining python objects

2005-11-18 Thread rurpy
__repr__ almost always only prints a summary of it's
object, not the detailed internal structure that I want to
see.  When it prints values, that are not pretty-printed,
nor are the objects that constitute the value printed
recursively.

Writing my own __repr__() is emphatically what I don't
want to do!  That is no better than debugging by inserting
print statements, a technique from the 1980's.

I am surprised (err, astounded actually) that a basic
tool like this isn't available.  Besides debugging, I would
think it would be very helpful to people leaning python.

Perhaps one of the Python IDEs contains something
like this I could extract from it but I was hoping to shortcut
what will be a time consuming search.

Ben Finney wrote:
> [EMAIL PROTECTED] wrote:
> > Is there a function/class/module/whatever I can use to look at
> > objects?
>
> The repr() function is what you want.
>
> > I want something that will print the object's value (if any) in
> > pretty-printed form, and list all it's attributes and their values.
> > And do all that recursively.
>
> The repr() function returns what the object's __repr__ method returns.
> You'll notice that the builtin container types (string, set, list,
> dict, ...) will show the values of their referred objects also.
>
> Define the __repr__ method on your classes so that they show whatever
> information you think is useful for debugging.
>
> --
>  \   "If you go flying back through time and you see somebody else |
>   `\   flying forward into the future, it's probably best to avoid eye |
> _o__)contact."  -- Jack Handey |
> Ben Finney

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


Re: Adding through recursion

2005-11-18 Thread Micah Elliott
On Nov 19, Ben Finney wrote:
...
> This is just one of many reasons why I advocate always having a
> *single* return statement, at the *end* of the function.

Agreed that it's a good *general* practice, but sometimes early exit
is useful and clear.

This is somewhat of a religious topic.  A good discussion is:
http://c2.com/cgi/wiki?SingleFunctionExitPoint

pychecker warns of fall-off-the-end functions.

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Los Angeles Python Users' Group, anyone?

2005-11-18 Thread mortenbagai
Great, thanks!

/M.

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


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread skip

Grant> If I allowed news posts to interrupt me, I'd never get anything
Grant> done.  I limit e-mail to things that really do require fairly
Grant> immediate attention.

Well, I do try to limit the number of things I pay attention to.  However,
as the "Python guy" at work, participating in this group and the python-dev
mailing list overlap my daytime duties.  There are a few other things I
watch as well (matplotlib, pygtk, moin, scipy, etc).  Running through all of
them in one place simplifies my life.  Last time I checked, most of Usenet
was crap (overrun with spam), so on those few occasions where I need
something I just use Google to search for help and post via Google or Gmane.
I never have to worry about NNTP.  I have no idea if my ISP (Comcast) even
provides NNTP access.

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


Re: Los Angeles Python Users' Group, anyone?

2005-11-18 Thread Grig Gheorghiu
[EMAIL PROTECTED] wrote:
> Hi,
>
> I was rifling through python.org to see if there was an existing Python
> user's group for the Los Angeles area. Doesn't seem like it, so maybe
> we should start one? I'm interested in helping with the coordination of
> activities etc.
>
> Since everybody living in greater L.A. area is likely to have
> superhuman tolerance for traffic and commuting times, I see no reason
> why an L.A users' group couldn't cover the whole
> LA/Valley/Burbank/Glendale/Pasadena/Long Beach/etc sprawl.
>
> Anyone interested, please email me at: m AT bagai DOT com
>
> Thanks!
>
> /Morten

Hi, Morten

I'm the organizer of the SoCal Piggies. Please subscribe to the mailing
list and you'll get all the messages regarding our next meetings. We're
planning to meet for dinner in December (probably Dec. 7th) at a
restaurant in Pasadena. Check out the mailing list archives for
details.

Hope to see you at our next meetings!

Grig
Grig

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Steve M
Another way to simulate the ternary operator is this:

a = (quantity > 90 and "It is very huge") or "The value is correct"

You have to be careful of semantics of 'and' and 'or'. But in this case
I wonder why you don't just test whether quantity is greater than 90
and assign the corresponding value to a, e.g., :

if quantity > 90:
 a = "It is huge"
else:
 a = "Time for tea."


Clarity is a virtue, and simulating ternary operator doesn't always
serve that end.

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


Re: os.popen('alias')

2005-11-18 Thread Lars Kellogg-Stedman
> import os
> for line in os.popen('alias').readlines():
>   print line
>
>
> No aliases are printed.
>
> I started python from an bash environment that had many aliases
> defined. I expected to see the list of aliases from within the
> interactive python shell. What could I do to see those aliases defined
> in the shell from where I started python?

You can't, really.  The 'alias' command is a shell built-in, not an external
command, so you can't meaningfully run it from a Python script (and any
aliases defined in your shell will probably not be available to Python).

Matters are complicated a little bit because when you use os.popen(),
your command line is actually passed to *a* shell, usually /bin/sh, so
the final command line looks like this:

  /bin/sh -c 'alias'

However, even if /bin/sh is actually bash, dotfiles such as .profile and
.bashrc aren't read when using the '-c' option.

If you really want to do something to your bash aliases with python, you
could pipe them into a python command:

  $ alias | python myscript.py

-- Lars

-- 
Lars Kellogg-Stedman <[EMAIL PROTECTED]>
This email address will expire on 2005-11-23.

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


Re: func(*params)

2005-11-18 Thread David Duerrenmatt
Great, this is exactly what I was looking for.

Thanks all of you for your immediate answer!




Nick Smallbone schrieb:
> David Duerrenmatt wrote:
> 
>>Hi there
>>
>>For some reasons, I've to use Python 1.5.2 and am looking for a workaround:
>>
>>In newer Python versions, I can call a function this way:
>>
>>func = some_function
>>func(*params)
>>
> 
> 
> I think the "apply" function is what you want:
> 
> apply(object[, args[, kwargs]]) -> value
> 
> Call a callable object with positional arguments taken from the tuple
> args, and keyword arguments taken from the optional dictionary kwargs.
> Note that classes are callable, as are instances with a __call__()
> method.
> 
> Deprecated since release 2.3. Instead, use the extended call syntax:
> function(*args, **keywords).
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: func(*params)

2005-11-18 Thread Nick Smallbone
David Duerrenmatt wrote:
> Hi there
>
> For some reasons, I've to use Python 1.5.2 and am looking for a workaround:
>
> In newer Python versions, I can call a function this way:
>
> func = some_function
> func(*params)
>

I think the "apply" function is what you want:

apply(object[, args[, kwargs]]) -> value

Call a callable object with positional arguments taken from the tuple
args, and keyword arguments taken from the optional dictionary kwargs.
Note that classes are callable, as are instances with a __call__()
method.

Deprecated since release 2.3. Instead, use the extended call syntax:
function(*args, **keywords).

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


Re: func(*params)

2005-11-18 Thread Peter Otten
David Duerrenmatt wrote:

> For some reasons, I've to use Python 1.5.2 and am looking for a
> workaround:
> 
> In newer Python versions, I can call a function this way:
> 
> func = some_function
> func(*params)
 
Use

apply(func, params) 

Peter

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


Re: check if com api is still available

2005-11-18 Thread Chris Mellon
On 11/18/05, Neil Hodgson <[EMAIL PROTECTED]> wrote:
> Hermann Maier:
>
> > i am using the com api of a program and if this program is shut down and
> > my program calls a method of the api, it crashs. that means, i need to
> > check, if the com server is still available, before i can call for it.
>
> The server should not shut down while clients have outstanding
> references to objects within it.
>

The Excel COM object has this behavior - if you call the Quit() method
or (if you're controlling an interactive instance) the excel window is
closed, further calls to the COM object will throw errors. I couldn't
find a solution to this other than to just make sure you didn't do
that. However, I didn't know about the ROT and maybe that will work.

> > but i would prefer a
> > solution that is more clean from the beginning. perhaps there is a
> > windows event that can tell me, wenn the other application, that hosts
> > the com server, is closed or perhaps i can do something with the guid of
> > the com server, maybe there is a call where i can check, if a certain
> > com server is available.
>
> All running COM servers should be in the "Running Object Table"
> (ROT). If you search the net for this term you will find code that can
> show what is in the ROT, so there must be an API.
>
> Neil
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


func(*params)

2005-11-18 Thread David Duerrenmatt
Hi there

For some reasons, I've to use Python 1.5.2 and am looking for a workaround:

In newer Python versions, I can call a function this way:

func = some_function
func(*params)

Then, the list/tuple named params will automatically be "expanded" and 
n=len(params) arguments will be submitted.

Python 1.5.2 doesn't support this kind of function call. I could use 
some workaround like:

func(params[0],params[1]...)

but since the number of items in params varies and depends on the mapped 
function "some_function", this isn't a good solution.

Another idea is to use exec(), don't know whether this is safe...

Any recommondations or tricks?


Thanks,
david
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding through recursion

2005-11-18 Thread Ben Finney
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)

To add to the other good advice in this thread:

This is just one of many reasons why I advocate always having a
*single* return statement, at the *end* of the function. I usually
start out writing my function setting a default return value, and the
return statement immediately below.

In your case, the default return value is None, so let's make that
explicit.

def recursive_add(x, y):
result = None
return result

Then, the rest of the function's responsibility is about changing that
default value if necessary.

def recursive_add(x, y):
result = None
if x == 0:
print y
result = y
else:
x -= 1
y += 1
recursive_add(x, y)
return result

With this structure, it becomes quickly obvious what's gone wrong: one
of the branches is not changing the default return value.

def recursive_add(x, y):
if x == 0:
print y
result = y
else:
x -= 1
y += 1
result = recursive_add(x, y)
return result

I find this much less error-prone than hiding return statements in
branches throughout the function; if the only return statement is at
the very end of the function, it becomes much easier to read.

-- 
 \"If you go to a costume party at your boss's house, wouldn't |
  `\ you think a good costume would be to dress up like the boss's |
_o__)   wife? Trust me, it's not."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Los Angeles Python Users' Group, anyone?

2005-11-18 Thread Matt

[EMAIL PROTECTED] wrote:
> Hi,
>
> I was rifling through python.org to see if there was an existing Python
> user's group for the Los Angeles area. Doesn't seem like it, so maybe
> we should start one? I'm interested in helping with the coordination of
> activities etc.
>
> Since everybody living in greater L.A. area is likely to have
> superhuman tolerance for traffic and commuting times, I see no reason
> why an L.A users' group couldn't cover the whole
> LA/Valley/Burbank/Glendale/Pasadena/Long Beach/etc sprawl.
>
> Anyone interested, please email me at: m AT bagai DOT com
>
> Thanks!
>
> /Morten

There is a SoCal python users' group:
http://lists.idyll.org/listinfo/socal-piggies
They meet in the Los Angeles area.

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


Re: Behaviour of enumerated types (was: Re: Immutable instances, constant values)

2005-11-18 Thread Bengt Richter
On Fri, 18 Nov 2005 23:43:10 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> wrote:

>Bengt Richter <[EMAIL PROTECTED]> wrote:
>> Ben Finney <[EMAIL PROTECTED]> wrote:
>> >I've recently packaged 'enum' in PyPI.
>> [...]
>> My notion of enum comes from (what I remember of) Pascal
>
>You might want to investigate the 'enum' package for my idea of how an
>enumerated type can work.
I guess I saw an earlier version, and got confused as to the goal, sorry.
I will look in PyPI.
>
>> which is basically an ordered set of names of integers forming a
>> type, and ord(one_of_the_names) gets you the index value.
>
>Getting a numeric index might be useful in a language such as Pascal,
>with no built-in dict or sequence types. In Python, where any
>immutable object can be a dict key, and any sequence can be iterated,
>it seems of no use.
Does your concept of enumeration not have a fixed order of a set of names?
If it does, what is more natural than using their index values as keys
to other ordered info? OTOH, the index values (and hence my enums) are[1] not
very good as unique dict keys, since they compare[2] promiscuously with each 
other
and other number types. Hm, maybe if hash were defined class-unique, e.g.,
def __hash__(self): return hash((int(self), type(self).__name__)
Ok, did that, _seems_ to work (fixed __repr__ too):
[1] were & [2] compared ;-)

 >>> from makeenum import makeEnum
 >>> Few = makeEnum('Few','zero one two three')
 >>> Few()
 Few('zero')
 >>> d = dict((Few(n), Few.names.index(n)) for n in Few.names)
 >>> d
 {Few('zero'): 0, Few('three'): 3, Few('one'): 1, Few('two'): 2}
 >>> d[1]
 Traceback (most recent call last):
   File "", line 1, in ?
 KeyError: 1
 >>> d[Few(1)]
 1

But still can work as integer:
 >>> 'ABC'[Few(1)]
 'B'
 >>> 'ABC'[Few('one')]
 'B'
 >>> 'ABC'[Few('two')]
 'C'

>
>> But what we have is named integers, much as True and False are built
>> in names for integer subtypes with value 1 and 0.
>
>That's an implementation detail; surely code shouldn't be expecting
>any particular relationship between integers and boolean values?
Au contraire, much code depends on it, e.g.,

 >>> def verboselen(s): return '%r has %d element%s'%(s, len(s), 
 >>> ('s','')[len(s)==1])
 ...
 >>> verboselen(range(3))
 '[0, 1, 2] has 3 elements'
 >>> verboselen(range(0))
 '[] has 0 elements'
 >>> verboselen(range(1))
 '[0] has 1 element'

 >>> type(len(range(3))==1)
 
 >>> type(len(range(3))==1).mro()
 [, , ]
 >>> int (len(range(3))==1)
 0
 >>> int (len(range(1))==1)
 1

>
>> So I'd say enums should also be int subtypes...
>
>Likewise, that seems best left as an implementation detail. Why expect
>any particular mapping to int values? Doing arithmetic or boolean
>logic on enumerated values seems against their purpose.
I guess I will have to look at your enum in PyPI to understand what
you mean by "their purpose" ;-)

To me the int correspondence is as expectable and natural as a,b,c=range(3)
(at least as a default) though I think different enumerations should be
different types. Note that the ordering of int values makes the instances
nicely sortable too, e.g.,

 >>> d.items()
 [(Few('zero'), 0), (Few('three'), 3), (Few('one'), 1), (Few('two'), 2)]
 >>> sorted(d.items())
 [(Few('zero'), 0), (Few('one'), 1), (Few('two'), 2), (Few('three'), 3)]

or more directly

 >>> d.keys()
 [Few('zero'), Few('three'), Few('one'), Few('two')]
 >>> sorted(d.keys())
 [Few('zero'), Few('one'), Few('two'), Few('three')]

Enumerations defined as monotonic but non-contiguous sequences of named int
values are conceivable too. They can be useful in defining bit masks with
distinguishable types, but that act like ints. Kind of a sparse enumeration.
Maybe I'll add that in.

But bottom line, I really thing the int base type is more than an implementation
detail. I think it's natural for an _ordered_ set of names ;-)

I'll go look at PyPI now ;-)

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


Re: check if com api is still available

2005-11-18 Thread Neil Hodgson
Hermann Maier:

> i am using the com api of a program and if this program is shut down and 
> my program calls a method of the api, it crashs. that means, i need to 
> check, if the com server is still available, before i can call for it.

The server should not shut down while clients have outstanding 
references to objects within it.

> but i would prefer a 
> solution that is more clean from the beginning. perhaps there is a 
> windows event that can tell me, wenn the other application, that hosts 
> the com server, is closed or perhaps i can do something with the guid of 
> the com server, maybe there is a call where i can check, if a certain 
> com server is available.

All running COM servers should be in the "Running Object Table" 
(ROT). If you search the net for this term you will find code that can 
show what is in the ROT, so there must be an API.

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


Re: examining python objects

2005-11-18 Thread Ben Finney
[EMAIL PROTECTED] wrote:
> Is there a function/class/module/whatever I can use to look at
> objects?

The repr() function is what you want.

> I want something that will print the object's value (if any) in
> pretty-printed form, and list all it's attributes and their values.
> And do all that recursively.

The repr() function returns what the object's __repr__ method returns.
You'll notice that the builtin container types (string, set, list,
dict, ...) will show the values of their referred objects also.

Define the __repr__ method on your classes so that they show whatever
information you think is useful for debugging.

-- 
 \   "If you go flying back through time and you see somebody else |
  `\   flying forward into the future, it's probably best to avoid eye |
_o__)contact."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Micah Elliott
On Nov 18, Grant Edwards wrote:
> There is an NNTP patch to allow you to use mutt to read Usenet
> via an NNTP server.

Yes, I'm aware of it; it's last (alpha) update was in 1999 and
it probably has some fleas. :-)

> Mutt users who don't do that seem to like slrn -- it has a very
> similar look and feel.

Cool!  Thanks for the info.  I might give it a try.

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Grant Edwards
On 2005-11-18, Micah Elliott <[EMAIL PROTECTED]> wrote:
> On Nov 18, [EMAIL PROTECTED] wrote:
>> Grant> Obligatory aside: I'm completely baffled why anybody would choose
>> Grant> the mailing list format over Usenet.  I don't even read mailing
>> Grant> lists via mailing lists.  I recommend gmane.org's NNTP server for
>> Grant> all your mailing list needs.
>> 
>> For the same reason I don't like web forums as a means of
>> communication.  I would much rather operate in an
>> interrupt-driven mode than have to remember to poll some
>> external service to get my daily helping of information.
>
> Agreed!

If I allowed news posts to interrupt me, I'd never get anything
done.  I limit e-mail to things that really do require fairly
immediate attention.

> I notice that a lot of people post here from google.

Ick! Posting to usenet from google.  Nasty.

> I did it too before I discovered the mailing list, which I now
> use because I haven't found a news reader that I like nearly
> as much as mutt.

There is an NNTP patch to allow you to use mutt to read Usenet
via an NNTP server.

Mutt users who don't do that seem to like slrn -- it has a very
similar look and feel.  One thing significant difference is
slrn's scoring facilities: there's nothing similar in mutt.

> It's quite nice to combine email and news into one.

I actually prefer to keep them separate.  for me, e-mail is for
stuff that "needs attention", and news is more of a background
thing that I glance through while waiting for a test to finish
or a make to complete.

> If you have any suggestions for console-based newsreaders, I'm
> all ears.

slrn is the definitive choice -- especially for a mutt user. :)

> I have tried to setup "tin" in the past but the voluminosity
> of its documentation made me give up.

I used tin for a couple years back in the early 90's, but I
find slrn much more efficient.

-- 
Grant Edwards   grante Yow!  My pants just went to
  at   high school in the Carlsbad
   visi.comCaverns!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Daniel Crespo
Hi Peter,

Expand your mind.

a = {'whatever': TernaryOperation(quantity>90,"It is very huge","The
value is correct")}

;-)

thanks for your advice anyway

Daniel

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


Re: Web-based client code execution

2005-11-18 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, Steve 
<[EMAIL PROTECTED]> writes
>AJAX works because browsers can execute javascript.  I don't know of a
>browser that can execute python.  Basically your stuck with java or
>javascript because everything else really isn't cross platform.

ActiveState do a version of Python that can run in a script tag like 
JavaScript and VBScript. This requires Windows Scripting Host. They also 
do a similar thing for Perl, not sure about TCL.

The syntax is along the lines of


Python goes here


I remember reading this about PerlScript and I'm pretty sure I'm correct 
in remembering there is a PythonScript. Anyway you are limited to 
ActiveState and Windows Scripting Host.

For pragmatic reasons I think you would be better concentrating on 
JavaScript for the Client and your language of choice 
Python/Ruby/Lua/whatever for the server part of AJAX.

Stephen
-- 
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html
Computer Consultancy, Software Development
Windows C++, Java, Assembler, Performance Analysis, Troubleshooting
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Micah Elliott
On Nov 18, [EMAIL PROTECTED] wrote:
> Grant> Obligatory aside: I'm completely baffled why anybody would choose
> Grant> the mailing list format over Usenet.  I don't even read mailing
> Grant> lists via mailing lists.  I recommend gmane.org's NNTP server for
> Grant> all your mailing list needs.
> 
> For the same reason I don't like web forums as a means of
> communication.  I would much rather operate in an interrupt-driven
> mode than have to remember to poll some external service to get my
> daily helping of information.

Agreed!

I notice that a lot of people post here from google.  I did it too
before I discovered the mailing list, which I now use because I
haven't found a news reader that I like nearly as much as mutt.  It's
quite nice to combine email and news into one.

If you have any suggestions for console-based newsreaders, I'm all
ears.  I have tried to setup "tin" in the past but the voluminosity of
its documentation made me give up.

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write an API for a Python application?

2005-11-18 Thread Piet van Oostrum
> Duncan Grisby <[EMAIL PROTECTED]> (DG) wrote:

>DG> To me, the situation sounds complex enough, especially with the need
>DG> for callbacks, that CORBA is an ideal solution. At the expense of a
>DG> small amount of boilerplate code, all the communication issues are
>DG> handled for you. In this day and age, why would you want to write code
>DG> that deals with sockets apart from the most specialist situations?

A more lightweight solution might be Ice. 
It is architecturally similar to Corba, but with less overhead. And
supports different programming languages and platforms.
But if your application is to be distributed on a non-GPL license you have
to pay.
That said, I think there is nothing wrong with using Corba for this kind of
thing. It has an additional advantage that it is a widely accepted standard.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


os.popen('alias')

2005-11-18 Thread Belebele
>From an interactive python shell, I execute the following:

import os
for line in os.popen('alias').readlines():
  print line


No aliases are printed.

I started python from an bash environment that had many aliases
defined. I expected to see the list of aliases from within the
interactive python shell. What could I do to see those aliases defined
in the shell from where I started python?

Thanks:

Belebele

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


Re: Yield in a wrapper function

2005-11-18 Thread Bengt Richter
On 18 Nov 2005 05:08:39 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>This works exactly as you would expect::
>
> from time import sleep
> def foo(on='ABC'):
>for e in list(on):
>sleep(1)
>yield e
>
>When I run this on the command line It takes about 3 seconds to
>complete and the first letter is shown after 1 second.
>But, how do I wrap the function somewhere else::
>
> from time import sleep
> def foo(on):
>for e in list(on):
>sleep(1)
>yield e
>
> def wrapper(x):
> if x < 0:
> return foo('ABC')
> else:
> return foo('XYZ')
>
>When I run this, variable three letters are shown and it takes 3
>seconds for the whole thing to complete. The problem is that the whole
>iteration is glogged up in the wrapper() function because the first
>letter is shown after 3 seconds and then all letters are shown at the
>same time.
>
>How do I wrap functions that return iterators? ...if possible.
>
Make the wrapper itself an iterable? E.g., is this the effect you wanted?

 >>> from time import sleep
 >>> def foo(on):
 ... for e in on:
 ... sleep(1)
 ... yield e
 ...
 >>> def wrapper(x):
 ... if x < 0:
 ... for e in foo('ABC'): yield e
 ... else:
 ... for e in foo('XYZ'): yield e
 ...
 >>> wrapper(-1)
 
 >>> import sys
 >>> for c in wrapper(-1): sys.stdout.write(c); sys.stdout.flush()
 ...
 ABC>>>
 >>> for c in wrapper(+1): sys.stdout.write(c); sys.stdout.flush()
 ...
 XYZ>>>

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


Type-checking unpickled objects

2005-11-18 Thread Gordon Airporte
I have this class, and I've been pickling it's objects as a file format 
for my program, which works great. The problems are a.) how to handle 
things when the user tries to load a non-pickled file, and b.) when they 
load a pickled file of the wrong class.

a. I can handle with a general exception I guess. I just tried to 
pickle.load() a .pyc and it failed with a 'KeyError' exception - however 
that works. It might do that every time, it might not.

Regarding b., if I type check I simply get the 'instance' type, which 
doesn't get me all of the way there because I might have an instance of 
the wrong class. I can't find any sort of __type__ attribute to set in 
the objects. Perhaps I should use __str__?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread skip

Grant> Obligatory aside: I'm completely baffled why anybody would choose
Grant> the mailing list format over Usenet.  I don't even read mailing
Grant> lists via mailing lists.  I recommend gmane.org's NNTP server for
Grant> all your mailing list needs.

For the same reason I don't like web forums as a means of communication.  I
would much rather operate in an interrupt-driven mode than have to remember
to poll some external service to get my daily helping of information.

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


Re: Web-based client code execution

2005-11-18 Thread Steve
You universally won't be able to do that with javascript, only with and
extension on firefox.  ActiveX will limit you to windows only with ie.
Which isn't bad you still get a 80% market share.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Grant Edwards
On 2005-11-18, Daniel Crespo <[EMAIL PROTECTED]> wrote:

> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...

The _PHP_ ternary operator (x?y:z)!  

Kids these days!

-- 
Grant Edwards   grante Yow!  It's so OBVIOUS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-18 Thread Paul Watson
Steve wrote:
> AJAX works because browsers can execute javascript.  I don't know of a
> browser that can execute python.  Basically your stuck with java or
> javascript because everything else really isn't cross platform.

Well, I guess the Grail browser could run Python, but I do not think I 
can go there.

I need READ access to the users local disk storage.  Can I do this in 
Javascript, or should I bite the bullet and turn to ActiveX?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Peter Otten
Daniel Crespo wrote:

> Oh... Well, thanks for that information.
> 
> I'll do this then:
> 
> def TernaryOperation(condition,true_part,false_part):
> if condition:
> return True-part
> else:
> return False-part
> 
> a = {'Huge': TernaryOperation(quantity>90,True,False)}

By the time it compiles it will do the same as

a = {"Huge": quantity>90}

Consider describing your actual problem and keep in mind that the "ternary
operator" is a means, not an end.

Peter

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


Re: Controlling windows gui applications from python

2005-11-18 Thread Paul Watson
tim wrote:
> Hi all, I'm almost as new to this list as to python so I hope I don't 
> get a "this has been answered a 100 times before" or anything...
> 
> Currently I am using a program named 'Macro Scheduler' for automating 
> programs that don't have a command line version.
> Its a simple scripting language that allows you to automate button 
> clicks, mouse movement, starting programs, checking the state of a 
> window, changing the focus, type text into an input field...etc.
> Is there a way to do these things from within Python?
> 
> Thanks
> Tim

If there is a Microsoft COM interface to your 'Macro Scheduler' program, 
then you can drive it from Python code.  See the win32com interface and 
get Mark Hammond's book "Programming Python on Win32," or something like 
that, from O'Reilly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Controlling windows gui applications from python

2005-11-18 Thread Simon Brunning
On 18/11/05, tim <[EMAIL PROTECTED]> wrote:
> Hi all, I'm almost as new to this list as to python so I hope I don't
> get a "this has been answered a 100 times before" or anything...
>
> Currently I am using a program named 'Macro Scheduler' for automating
> programs that don't have a command line version.
> Its a simple scripting language that allows you to automate button
> clicks, mouse movement, starting programs, checking the state of a
> window, changing the focus, type text into an input field...etc.
> Is there a way to do these things from within Python?



--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Sam Pointon
Daniel Crespo wrote:
> Hello to all,
>
> How can I do
>
> new_variable = (variable) ? True : False;
>
> in Python in one line?
>
> I want to do something like this:
>
> dic = {'item1': (variable) ? True-part : False-part}
>
> Any suggestions?
>
> Daniel

There's a trick using the short-circuiting boolean logic operators to
emulate the ternary operator in Python. Basically, you do
TEST and TRUE_PART or FALSE_PART

However, this fails if TRUE_PART evaluates to a False value; you end up
with FALSE_PART's value instead.

This is a trick/hack, though, and shouldn't really be used much - use
an if statement instead, or wait til 2.5 when an if expression is
coming in.

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Daniel Crespo
Oh... Well, thanks for that information.

I'll do this then:

def TernaryOperation(condition,true_part,false_part):
if condition:
return True-part
else:
return False-part

a = {'Huge': TernaryOperation(quantity>90,True,False)}

Thank you

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


Re: Web-based client code execution

2005-11-18 Thread Steve
AJAX works because browsers can execute javascript.  I don't know of a
browser that can execute python.  Basically your stuck with java or
javascript because everything else really isn't cross platform.

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


Re: Choose meaningful subjects for posts [was: Re: newb ?]

2005-11-18 Thread Grant Edwards
On 2005-11-18, Mike Meyer <[EMAIL PROTECTED]> wrote:

>>> http://www.catb.org/~esr/faqs/smart-questions.html#bespecific
>>> before you post your next question.

If I can't tell from the subject line what the thread is about, I almost
never read it.

>> Note also that the subject line on an existing thread can be changed,
>> though not everyone's software will track the changes, unfortunately. It's
>> always worth taking the time to make sure the subject line really does
>> describe the subject of your message
>
> [Since we're giving posting advice.]
>
> By the same token, don't use a reply to start a new thread. Some software
> *will* keep it in the thread, and if they had killed the thread, they won't
> see your posts.

They don't even have to kill the original thread. By just not expanding the
thread they won't see the "new" thread hidden inside the old one.

This problem seems to be especially prevelent in c.l.p. (as are fractured
threads). I think it's due to people who read the group via an e-mail
gateway (particularly the ones who get the digest service).

Obligatory aside: I'm completely baffled why anybody would choose the
mailing list format over Usenet.  I don't even read mailing lists via
mailing lists.  I recommend gmane.org's NNTP server for all your mailing
list needs.

-- 
Grant Edwards   grante Yow!  It's so OBVIOUS!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Controlling windows gui applications from python

2005-11-18 Thread tim
Hi all, I'm almost as new to this list as to python so I hope I don't 
get a "this has been answered a 100 times before" or anything...

Currently I am using a program named 'Macro Scheduler' for automating 
programs that don't have a command line version.
Its a simple scripting language that allows you to automate button 
clicks, mouse movement, starting programs, checking the state of a 
window, changing the focus, type text into an input field...etc.
Is there a way to do these things from within Python?

Thanks
Tim

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


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread gene tani

Mike Meyer wrote:
> "Daniel Crespo" <[EMAIL PROTECTED]> writes:
>
> > Hi!
> >
> > I would like to know how can I do the PHP ternary operator/statement
> > (... ? ... : ...) in Python...
> >
> > I want to something like:
> >
> > a = {'Huge': (quantity>90) ? True : False}
> >
> > Any suggestions?
>
> Lots of ways, depending on your exact needs. What's best for what you
> suggest is "a = {Huge : (False, True)[quantity > 90]}". Googling  the

http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

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


Re: Python on linux

2005-11-18 Thread Sybren Stuvel
John Abel enlightened us with:
> Here's one I used a while back.  Returns a dict containing details per 
> partition

This only gives information about actually mounted partitions. It
could be improved by checking /proc/partitions as well.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread Mike Meyer
"Daniel Crespo" <[EMAIL PROTECTED]> writes:

> Hi!
>
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}
>
> Any suggestions?

Lots of ways, depending on your exact needs. What's best for what you
suggest is "a = {Huge : (False, True)[quantity > 90]}". Googling  the
python newsgroup will turn up lots of others.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the PHP ternary operator equivalent on Python

2005-11-18 Thread David Wahler
Daniel Crespo wrote:
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}

Well, in your example the '>' operator already returns a boolean value
so you can just use it directly. Hoewver, I agree that there are
situations in which a ternary operator would be nice. Unfortunately,
Python doesn't support this directly; the closest approximation I've
found is:

>>> (value_if_false, value_if_true)[boolean_value]

This exploits the fact that False and True are converted to integers as
zero and one, respectively. The downside is that it's really ugly.
Also, it doesn't use minimal evaluation; in other words, if you try an
expression like:

>>> (None, func())[callable(func)]

You might think this would return the value of func() if it's callable,
and None otherwise. Unfortunately, func() is evaluated no matter what,
even if the condition is false.

Of course, you can always get around this by doing really cryptic stuff
with lambdas:

>>> (lambda: None, lambda: func())[callable(func)]()

... but by that point, you're better off just using an if/then/else.

-- David

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


Web-based client code execution

2005-11-18 Thread Paul Watson
What are the options?

The user to hits a web page, downloads code (Python I hope), execute it, 
and be able to return the results.  It needs to be able to go through 
standard HTTP so that it could be run from behind a corporate firewall 
without any other ports being opened.

Am I stuck doing an ActiveX control?

Yes, I know that downloading code and executing on the client machine is 
a security risk.  This will be for the employee's computers to connect. 
  This will not be a publicly available web page.

I have read some about AJAX.  Is there an APAX coming for Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do "new_variable = (variable) ? True : False; " (php) on python?

2005-11-18 Thread Peter Otten
Daniel Crespo wrote:

> How can I do
> 
> new_variable = (variable) ? True : False;
> 
> in Python in one line?

new_variable = variable

:-)

Peter
 

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


Re: path module / class

2005-11-18 Thread [EMAIL PROTECTED]
Hi Neil,

Neil Hodgson wrote:
[snip]
> There is no PEP yet but there is a wiki page.
> http://wiki.python.org/moin/PathClass
> Guido was unenthusiastic so a good step would be to produce some
> compelling examples.

I guess it depends on what is "compelling" :)

I've been trying to come up with some cases that I've run into where
the path module has helped.  One case I just came across was trying to
do the equivalent of 'du -s *' in python, i.e. get the size of each of
a directory's subdirectories.  My two implemenations are below:

import os
import os.path
from path import path

def du_std(d):
"""Return a mapping of subdirectory name to total size of files in
that subdirectory, much like 'du -s *' does.

   This implementation uses only the current python standard
   libraries"""
retval = {}
# Why is os.listdir() and not os.path.listdir()?
# Yet another point of confusion
for subdir in os.listdir(d):
subdir = os.path.join(d, subdir)
if os.path.isdir(subdir):
s = 0
for root, dirs, files in os.walk(subdir):
s += sum(os.path.getsize(os.path.join(root,f)) for f in
files)
retval[subdir] = s
return retval

def du_path(d):
"""Return a mapping of subdirectory name to total size of files in
   that subdirectory, much like 'du -s *' does.

   This implementation uses the proposed path module"""
retval = {}
for subdir in path(d).dirs():
retval[subdir] = sum(f.getsize() for f in subdir.walkfiles())
return retval

I find the second easier to read, and easier to write - I got caught
writing the first one when I wrote os.path.listdir() instead of
os.listdir().

Cheers,
Chris

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


  1   2   >