Re: Need help with OptionParser

2008-03-25 Thread Stargaming
On Tue, 25 Mar 2008 05:42:03 -0700, hellt wrote:
[snip]
> usage = "usage: %prog [options]"
> parser = OptionParser(usage)
> parser.add_option("-f", "--file", dest="filename",
> help="executable filename",
> metavar="FILE")
> parser.add_option("-b", "--bighosts",
>   action="store_true", dest="bighosts", default=False,
>   help="with big hosts  [default: %default]")
> (options, args) = parser.parse_args()
> if not options.bighosts:
> print parser.print_usage()

FWIW you should perhaps give a special error message rather than the 
generic help (something like "you need to specify bighosts, see --help 
for details").

If possible, you should use `args` rather than an option (they are, well, 
optional). But if your program takes a lot of mandatory arguments, using 
options in order to mix them at will might be fine.

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


Re: Immutable and Mutable Types

2008-03-17 Thread Stargaming
On Mon, 17 Mar 2008 16:03:19 +, Duncan Booth wrote:

> For the answer I actually want each asterisk substitutes for exactly one
> character.

Played around a bit and found that one:

Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20)
[GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 1//1
>>> if a is b: print('yes!')
...
>>> b
1
>>> type(b)

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


Re: Immutable and Mutable Types

2008-03-17 Thread Stargaming
On Mon, 17 Mar 2008 10:40:43 +, Duncan Booth wrote:
> Here's a puzzle for those who think they know Python:
> 
> Given that I masked out part of the input, which version(s) of Python
> might give the following output, and what might I have replaced by
> asterisks?
> 
 a = 1
 b = 
 if a is b: print 'yes!'
> ...
 b
> 1
 type(b)
> 

I know it! Using CPython 2.5.2a0, 2.6a1+ and 3.0a3+::

>>> b = type('type', (type,), {'__repr__': lambda self:
... ""})('int', (object,), {'__repr__': 
... lambda self:"1"})()
>>> b
1
>>> type(b)

>>> 1 is b
False

What's my prize?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About reading Python code

2008-03-16 Thread Stargaming
On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote:

> Hello. I wonder what's the effective way of figuring out how a piece of
> python code works.

If your Python code is well-written, it should be easy figuring out what 
it means by just reading it. For more complex programs, of course, this 
method can fail.

> With C I often find it very useful to be able to run
> the code in step mode and set breakpoints in a debugger so I can watch
> how the it executes, how the data change and how the code jumps from one
> function to another. But with Python, the debugger is a little
> primitive. The default IDLE doesn't even allow me to set a breakpoint.
> When the code is long, I am often lost in it.

IDLE is just, well, a batteries-included editor. There are many people 
(me included) who do *not* like it because it's so weak and doesn't have 
any real uses cases if your programs get sufficiently complex (because 
IDLE itself is sufficiently primitive).

You might be interested in *real* debuggers, such as the Python Debugger 
`PDB <http://docs.python.org/lib/module-pdb.html>`_. If you don't find 
its usage obvious, a quick google search just turned up a nice `tutorial 
<http://www.ferg.org/papers/debugging_in_python.html>`_.

You might find the `Python Profilers <http://docs.python.org/lib/
profile.html>`_ particularly interesting, `profile` for finding out which 
function sucks up the most calls/time, `trace` for more sophisticated 
stuff.
`pythontracer <http://code.google.com/p/pythontracer/>` sounds like a 
good combination of both.

> So I'm curious how to read code effectively. I agree that python code is
> clear, but when it becomes long, reading it can still be a hard work.

A common practice is just inserting `print` statements since it's so 
easy. If you think your debugging isn't temporary but could be useful and 
will be enabled every now and then, you could also use the `logging 
module <http://docs.python.org/lib/module-logging.html>`_ with the 
``DEBUG`` level.

There was a blog post recently about how to do this `generically for 
functions <http://wordaligned.org/articles/echo>`_.

> BTW. I think this problem also exists in other script languages.

FWIW, I think it's particularly easier in scripting languages to 
implement all kinds of tracing (apart from debugging, which is rather 
unpopular in Python) because you have one *extra* level (the interpreter) 
between your machine and your code.

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


Re: catching object

2008-03-12 Thread Stargaming
On Wed, 12 Mar 2008 01:05:06 +0100, Igor V. Rafienko wrote:

> Hi,
> 
> 
> I was wondering if someone could help me explain this situation:
> 
> h[1] >>> import inspect
> h[1] >>> inspect.getmro(ValueError)
> (, ,
>  , ,   'object'>)
> h[2] >>> try:
>   raise ValueError("argh")
> except object:
>   print "why not?"
>  
> Traceback (most recent call last):
>   File "", line 2, in 
> ValueError: argh
> 
> The question is, why isn't ValueError caught? It *does* inherit from
> object (albeit indirectly), and my understanding of the wording of
> CPython docs is that this guarantees "compatibility" (between what is
> being raised and what is being caught).

I think inheritance is meant in reference to the Exception tree here. So, 
the uppermost class is `BaseException`. Python 3 gives this exception 
when trying to handle `object`::

TypeError: catching classes that do not inherit from BaseException is 
not allowed

You are right, the wording is quite confusing here but that might be due 
to the crude situation of exceptions: All old-style classes (deprecated 
themselves) can be raised. Strings can still be raised but this is 
deprecated. New-style classes can be raised but only if they inherit (at 
least indirectly) from BaseException. I'd say: feel free to contribute 
patches. :-)

> So, why doesn't object match ValueError (or any other exception for that
> matter). I am aware of "except:", but in my particular situation it is
> eh... unsuitable.

Why so?

The only possible solution me and my crystal ball could come up with is 
that you're having a lot of old-style exceptions raised from some library 
you cannot modify. You cannot handle any common base class and don't want 
to handle every of the exceptions. If that's the case, just use a bare 
`except` and utilize `sys.exc_info`.

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


Re: Better way to negate a boolean list?

2008-02-10 Thread Stargaming
On Sun, 10 Feb 2008 08:46:24 +0100, David Trémouilles wrote:
[snip]
> I tried:
>  >>> map(not, boolean_list)
> but it seems that "not" is not a function.

`not` is not a function, indeed. It is a keyword, allowing you to write 
``not x`` instead of ``not(x)``. 

You can of course write a function that just returns its input negated 
and pass this function to `map`. Since Python comes with batteries 
included, there is such a function already in the `operator module 
`_::

import operator
map(operator.not_, boolean_list)
#   ^ underscore to distinguish from the keyword

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

Re: Naive idiom questions

2008-01-31 Thread Stargaming
On Thu, 31 Jan 2008 15:30:09 -0600, Terran Melconian wrote:
> * Is there a way to get headings in docstrings?
> 
> I want to create my own sections, like "OVERVIEW", "EXAMPLES",
> "AUTHORS", "BUGS", etc.  I can't figure out any way to do this.  In
> perldoc, I can easily use =head1, but I can't figure out the Python
> equivalent.  At first I thought I could use (re)structuredtext, but
> then it became apparent that pydoc(1) does not parse any of this
> markup.  Am I missing something, or is it just not possible to
> achieve this effect other than by writing separate, independent
> manpages?

I could imagine several solutions.

Do it like normal manpages, just use indentation::

OVERVIEW
So this is my script.

AUTHORS
Written by me. :-)

Use ReStructuredText -- it's readable even if it is not parsed by pydoc::

Overview


So this is my script.


Authors
===

Written by me.

Despite being readable even without transformations, you can use 
additional third-party packages to get nice and shiny documentation (HTML 
for most purposes). My favorite is Epydoc_, even though there are a whole 
lot of others (for example the tool used for the CPython docs, Sphinx, or 
just plain docutils_).

.. Epydoc: http://epydoc.sourceforge.net/
.. _docutils: http://docutils.sourceforge.net/

And, uh, if you abandon pydoc and roll your own docstring parser, you 
could basically use *any* markup you like. ``Overview``, for 
example.

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


Re: helper function in a class' namespace

2008-01-31 Thread Stargaming
On Thu, 31 Jan 2008 20:51:23 +0100, Helmut Jarausch wrote:

> Hi,
> 
> the following code works fine
> 
> def Helper(M) :
>return 'H>'+M

String concatenation is generally considered unpythonic, better use 
string interpolation::

'H> %s' % (M,)

> class A(object):
>def __init__(self,Msg) :
>  print Helper(Msg)
> 
> B=A('ZZ')

Watch out your names -- they could confuse other Python programmers 
introspecting your namespaces! Names bound to objects should generally be 
lowercase (argument ``msg``, object ``b``, argument ``m``, function 
``helper``). For details on what the Python community has agreed on is 
"good style," see the `Style Guide `_.

> but the Helper function is in the module's namespace.

Where's the problem? If it is "I don't want Helper to be visible", just 
use this convention: "Names beginning with an underscore are private. 
Better keep your fingers off."

> I'd like to put it into class A's namespace. Note, the Helper function
> doesn't need access to any instance attributes.
> 
> The first variant
> 
> class A(object):
>def Helper(M) :
>  return 'H>'+M
>def __init__(self,Msg) :
>  print Helper(Msg)
> 
> doesn't work since Python is looking for a global function Helper (why?)

Because in the scope of the ``__init__`` function, the name ``Helper`` is 
not bound. It then jumps out to the global scope.

> The alternative
> 
> class A(object):
>def Helper(M) :
>  return 'H>'+M
>def __init__(self,Msg) :
>  print A.Helper(Msg)
> 
> doesn't work either since now the first argument to A.Helper must be
> 'A'.
> 
> So, isn't it possible to have a helper function in the namespace of a
> class without (the overhead of) passing a 'self' or a 'cls' parameter?

Of course it is! You can decorate certain functions with the 
`staticmethod `_ 
wrapper, which will do exactly what you wanted::

class A(object):
@staticmethod
def helper(m):
return 'H>%s' % (m,)
def __init__(self, msg):
print A.helper(msg) # or self.helper


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


Re: How to refer to the current module?

2008-01-07 Thread Stargaming
On Mon, 07 Jan 2008 05:21:42 -0800, Mike wrote:

> I want to do something like the following (let's pretend that this is in
> file 'driver.py'):
> 
> #!/bin/env python
> 
> import sys
> 
> def foo():
> print 'foo'
> 
> def bar(arg):
> print 'bar with %r' % arg
> 
> def main():
> getattr(driver, sys.argv[1])(*sys.argv[2:])
> 
> if __name__=='__main__':
> main()
> 
> 
> Essentially what I'm trying to get at here is dynamic function
> redirection, like a generic dispatch script.  I could call this as
> 
> python driver.py foo
> 
> or
> 
> python driver.py bar 15
> 
> and at any time later I can add new functions to driver.py without
> having to update a dispatch dict or what-have-you.
> 
> The problem is, 'driver' doesn't exist in main() line 1.  If I 'import
> driver' from the command line, then getattr(driver, ...) works, but it's
> not bound here.
> 
> Is there any way around this?  Can I somehow scope the 'current module'
> and give getattr(...) an object that will (at run time) have the
> appropriate bindings?
> 
> Thanks in advance for all advice!
> 
> Mike

`__main__` (after you did ``import __main__``) could be an option as 
well. But I'd prefer a custom dictionary for your dispatch, rather than 
some magic with the module's names.

See http://docs.python.org/ref/programs.html for details on __main__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing built-in exception types

2007-12-14 Thread Stargaming
On Tue, 11 Dec 2007 12:51:52 -0800, Nishkar Grover wrote:

> I'm trying to replace a built-in exception type and here's a simplified
> example of what I was hoping to do...
> 
> 
>  >>> import exceptions, __builtin__
>  >>>
>  >>> zeroDivisionError = exceptions.ZeroDivisionError

I don't know why you're fiddling that much with the names, 
`ZeroDivisionError` is a builtin name. If you do this to avoid 
overwriting the base classes, consider the following example::

   >>> class A(object): pass
   ...
   >>> class B(A): pass
   ...
   >>> A_backup = A
   >>> A_backup is A
   True
   >>> class A(object): pass
   ...
   >>> A_backup is A
   False
   >>> B.__base__ is A
   False
   >>> B.__base__ is A_backup
   True

The names really just point to an object. Once the resolution from a name 
to a real object is done, you can reuse the name.

>  >>> class Foo(zeroDivisionError):
> ... bar = 'bar'
> ...
>  >>>
>  >>> exceptions.ZeroDivisionError = Foo
>  >>> ZeroDivisionError = Foo
>  >>> __builtin__.ZeroDivisionError = Foo
>  >>>
>  >>> try:
> ... raise ZeroDivisionError
> ... except ZeroDivisionError, e:
> ... print e.bar
> ...
> bar
>  >>>
>  >>> try:
> ... 1/0
> ... except ZeroDivisionError, e:
> ... print e.bar
> ...
> Traceback (most recent call last):
>File "", line 2, in ?
> ZeroDivisionError: integer division or modulo by zero
>  >>>
>  >>>

The object that ZeroDivisionError points to in your code is *not* the 
raised exception.

> Notice that I get my customized exception type when I explicitly raise
> ZeroDivisionError but not when that is implicitly raised by 1/0. It
> seems like I have to replace that exception type at some lower level,
> but I'm not sure how/where. Does anyone know of a way to do this?

The obvious question is: What are you trying to do?

Remember that you can always catch an exception in an `except` clause and 
perform whatever action you want, eg. raise *another* exception.

If you just want to change error representations (I doubt that you really 
need it, tho), you might be interested in overwriting `sys.excepthook 
`_.

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


Re: Changing argument value

2007-12-14 Thread Stargaming
On Thu, 13 Dec 2007 22:52:56 +0100, Bruno Desthuilliers wrote:

> flyfree a écrit :
[snip]
>> What is the difference between "y = [3,4]" and "y[0]=3 y[1] =4 "
> 
> In the first case, you rebind the local name y to a new list object -
> and since the name is local, rebinding it only affects the local
> namespace. In the second case, you mutate the list object (bound to the
> local name y) passed to the function. The point to remember is that in
> Python, all variables are references to objects, but names (including
> params) are local.
> 
> HTH

Even though you have the assignment operator *in both cases*, it does 
**not** issue the same thing. 

As Bruno pointed out, in the first case ``y = [3,4]`` it is *rebinding* 
the name `y`. When used with slice notation, the assignment operator 
tells the object bound to y, "Hey, change your item with name/number 0 to 
3, please." This can succeed but it doesn't have to. Raw assignments 
always succeed.

(You could also make assignments of y[0] result in whatever you want, a 
SystemExit for example; not so with pure assignments of y! The behaviour 
of assignments cannot be influenced in any way.)

If you're interested in the special methods Python uses there, `Emulating 
container types `_ might be interesting for you.

To sum up, the assignment operator has multiple meanings depending on its 
left-hand-side operand.

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

Re: Job Offer: Python Ninja or Pirate!

2007-12-14 Thread Stargaming
On Tue, 11 Dec 2007 08:57:16 -0800, George Sakkis wrote:

> On Dec 10, 11:07 pm, Stargaming <[EMAIL PROTECTED]> wrote:
>> On Mon, 10 Dec 2007 19:27:43 -0800, George Sakkis wrote:
>> > On Dec 10, 2:11 pm, Stargaming <[EMAIL PROTECTED]> wrote:
[snip]
>> >> Even though I do not qualify for the job, I came up with this
>> >> () code (modified list values for demonstration, mixed
>> >> together from previous post and original task):
>>
>> >> print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__
>> >> ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse
>> >> (__import__('urllib').urlopen('http://api.etsy.com/feeds/
>> >> xml_user_details.php?id=%d'%i)).getElementsByTagName('city')
>> >> [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729,
>> >> 729
>>
[snip]
>>
>> > Alas, it's not:
>>
>> > AttributeError: 'module' object has no attribute 'dom'
[snip]
>> Heh, yes. I did the same error as the participant before me -- test it
>> in a premodified environment. A fix is easy, __import__
>> 'xml.dom.minidom' instead of 'xml'. :-)
> 
> Closer, but still wrong; for some weird reason, __import__ for modules
> in packages returns the top level package by default; you have to use
> the 'fromlist' argument:
> 
>>>> __import__('xml.dom.minidom') is __import__('xml')
> True
> 
>>>> __import__('xml.dom.minidom', fromlist=True)
>  minidom.pyc'>
> 
> 
> George

No, it's perfectly right::

>>> __import__('xml.dom.minidom').dom.minidom


You can observe the change pretty well in `sys.modules`::

>>> __import__('xml')

>>> import sys
>>> sys.modules.keys()

The result will be a few core modules and the module `xml`. When 
importing `xml.dom.minidom`, though, this imports a lot more files::

>>> __import__('xml.dom.minidom')

>>> import sys
>>> sys.modules.keys()

Among them, there are `xml`, `xml.dom` and `xml.dom.minidom`. Having 
these modules imported, `__import__('xml.dom.minidom').dom.minidom` 
becomes a perfectly valid access to the xml/xml.dom packages.

So, your check is correct, importing xml.dom.minidom and xml both give a 
reference to `xml` but the import machinery is invoked to import its 
contents, as well, when explicitly told to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Job Offer: Python Ninja or Pirate!

2007-12-10 Thread Stargaming
On Mon, 10 Dec 2007 19:27:43 -0800, George Sakkis wrote:

> On Dec 10, 2:11 pm, Stargaming <[EMAIL PROTECTED]> wrote:
>> On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote:
>>
>> [snip]
>>
>> >> Problem: In the dynamic language of your choice, write a short
>> >> program that will:
>> >>  1. define a list of the following user ids 42346, 77290, 729 (you
>> >>  can
>> >> hardcode these, but it should
>> >> still work with more or less ids)
>> >>  2. retrieve an xml document related to each user at this url
>> >>  "http://
>> >> api.etsy.com/feeds/xml_user_details.php?id="
>> >>  3. retrieve the data contained in the city element from each xml
>> >> document
>> >>  4. keep a running total of how many users are found in each city 5.
>> >>  display the total count of users living in each city
>> [snip]
>>
>> > i wanted to make it a one liner, but i had to import modules :(
>>
>> > import sys, xml, urllib
>>
>> > dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city,
>> > num in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city
>> > for city in
>> > ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/
feeds/
>>
>> xml_user_details.php?id='
>>
>> > + str(id)).read()).getElementsByTagName('city')[0].childNodes +
>> > [(lambda t: (setattr(t, 'data', 'no city'),
>> > t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace('  ', ' ')
>> > for id in [71234, 71234, 71234, 71234, 71234, 71234,
>> > 42792])]])]][0])]
>>
>> I suggest `__import__` in such cases.
>>
>> Even though I do not qualify for the job, I came up with this ()
>> code (modified list values for demonstration, mixed together from
>> previous post and original task):
>>
>> print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__
>> ('itertools').groupby(sorted(__import__('xml').dom.minidom.parse
>> (__import__('urllib').urlopen('http://api.etsy.com/feeds/
>> xml_user_details.php?id=%d'%i)).getElementsByTagName('city')
>> [0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729,
>> 729
>>
>> I still find this rather readable, though, and there is no bad side-
>> effect magic! :-)
>>
>> Output should be:
>>
>> | Chicago: 3
>> | Fort Lauderdale: 1
>> | Jersey City And South Florida: 1
>> | New York: 1
> 
> Alas, it's not:
> 
> AttributeError: 'module' object has no attribute 'dom'
> 
> Here's a working version, optimized for char length (one line, 241
> chars):
> 
> import urllib as U,elementtree.ElementTree as
> E;c=[E.parse(U.urlopen('http://api.etsy.com/feeds/xml_user_details.php?
> id=%d'%u)).findtext('//city')for u in
> 71234,729,42346,77290,729,729];print'\n'.join('%s: %s'%
> (i,c.count(i))for i in set(c))
> 
> George

Heh, yes. I did the same error as the participant before me -- test it in 
a premodified environment. A fix is easy, __import__ 'xml.dom.minidom' 
instead of 'xml'. :-)

;-is-cheating'ly yours,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to program custom syntax to python prompt? >> I want to edit matrices.

2007-12-10 Thread Stargaming
On Mon, 10 Dec 2007 16:54:08 -0800, mosi wrote:

> Python matrices are usually defined with numpy scipy array or similar.
> e.g.
 matrix1 = [[1, 2], [3, 4], [5, 6]]
> I would like to have easier way of defining matrices, for example:
 matrix = [1, 2; 3, 4; 5, 6]
> 
 matrix =
> [ 1, 2;
>   3, 4;
>   5, 6;]
> 
> Any ideas how could this be done? The ";" sign is reserved, the "[ ]" is
> used for lists.

You could have some class `Matrix` with a constructor taking a string, as 
in ``Matrix("[1, 2; 3, 4; 5, 6]")``. A very naive parser could just strip 
trailing/leading brackets and all spaces, split on ';', split again on 
',', done.

> Also, how to program custom operations for this new "class?" matrix ???
> 
> For example:
 matrix + 2
> [ 3, 4;
>   5, 6;
>   7, 8;]
> 
> Possibly with operator overloading?

Yes, by simply overloading __add__ et al. See http://docs.python.org/ref/
specialnames.html for details (certainly, "Emulating numeric types" 
should be interesting to you).

> I appreciate all your comments, directions, pointers. mosi

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


Re: Job Offer: Python Ninja or Pirate!

2007-12-10 Thread Stargaming
On Mon, 10 Dec 2007 16:10:16 +0200, Nikos Vergas wrote:

[snip]
>> Problem: In the dynamic language of your choice, write a short program
>> that will:
>>  1. define a list of the following user ids 42346, 77290, 729 (you can
>> hardcode these, but it should
>> still work with more or less ids)
>>  2. retrieve an xml document related to each user at this url "http://
>> api.etsy.com/feeds/xml_user_details.php?id="
>>  3. retrieve the data contained in the city element from each xml
>> document
>>  4. keep a running total of how many users are found in each city 5.
>>  display the total count of users living in each city
[snip]
> 
> i wanted to make it a one liner, but i had to import modules :(
> 
> import sys, xml, urllib
> 
> dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num
> in set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for
> city in
> ((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/
xml_user_details.php?id='
> + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda
> t: (setattr(t, 'data', 'no city'),
> t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace('  ', ' ') for
> id in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])]

I suggest `__import__` in such cases. 

Even though I do not qualify for the job, I came up with this () 
code (modified list values for demonstration, mixed together from 
previous post and original task):

print '\n'.join('%s: %d'%(x,len(list(y))) for x,y in __import__
('itertools').groupby(sorted(__import__('xml').dom.minidom.parse
(__import__('urllib').urlopen('http://api.etsy.com/feeds/
xml_user_details.php?id=%d'%i)).getElementsByTagName('city')
[0].lastChild.data.title() for i in (71234, 729, 42346, 77290, 729, 
729

I still find this rather readable, though, and there is no bad side-
effect magic! :-)

Output should be:

| Chicago: 3
| Fort Lauderdale: 1
| Jersey City And South Florida: 1
| New York: 1

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


Re: why it is invalid syntax?

2007-11-22 Thread Stargaming
On Thu, 22 Nov 2007 03:24:48 -0800, cokofreedom wrote:

> On Nov 22, 10:58 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> 2007/11/22, Stef Mientki <[EMAIL PROTECTED]>:
>>
>>
>>
>> > alf wrote:
>> > > Hi,
>>
>> > > I wonder why it is an invalid syntax:
>>
>> > >  >>> if 1: if 1: if 1: print 1
>> > >   File "", line 1
>> > > if 1: if 1: if 1: print 1
>>
>> > > or
>>
>> > >  >>> if 1: for i in range(10): print i
>> > >   File "", line 1
>> > > if 1: for i in range(10): print i
>>
>> > > I would expect one could nest :
>>
>> > Although I agree it might be quit unreadable for normal programmers,
>> > people who are used to writing math formula, (i.e. MatLab), this is
>> > not true.
>>
>> > Here another interesting one, that is accepted:
>>
>> >  self.nodes.extend ( [ ONode(shape,n,self) \
>> >for n in range(shape.Parent.N_Outputs)
>> >\ if shape.Type_Outputs[n] == type ] )
>>
>> That is a list comprehension
>>
>>
>>
>> > cheers,
>> > Stef
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> --
>> -- Guilherme H. Polo Goncalves
> 
> So acceptable usage (though disgusting :P) would be
> 
> while 1: print 'hello'; print 'goodbye'; exec(rm -rf *)

Nope::

exec(rm -rf *)
 ^
SyntaxError: invalid syntax

Even the syntactically correct ``exec("rm -rf *")`` would make your 
computer explode. Should we introduce this as a shortcut to `break`? ;-)

SCNR,
stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to pass a function name and its arguments inside the arguments of other function?

2007-11-03 Thread Stargaming
On Sat, 03 Nov 2007 02:21:30 +, jmborr wrote:

> I need something like this:
> 
> 1:  superfoo( non-keyword-args, keyword-args, methodname, *kargs,
> *kwargs):
> 2:   """non-keyword-args  and  keyword-args are arguments that 3:   
>apply to superfoo, while *kargs and **kwargs are arguments
> 4:   that apply to methodname. See below""" 5:  
> object=someClass()
> 6:   result=getattr(object,methodname)(*kargs,**kwargs) 7:  
> return result
> 
> The problem is: how can I pass both arguments for superfoo and
> methodname in line 1: ? Is it possible? -Jose

I don't really understand the problem (could you give some (fictional) 
working sample how you plan to use this and leave out the line numbers 
for better readability?) but perhaps using traditional tuples and dicts 
instead of */** unpacking would be enough? Like::

superfoo(fooargs=(1,2,3), fookwargs={'foo': 'bar},
 objargs=('a', 'b'), objkwargs={'x': 5})

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


Re: Can local function access local variables in main program?

2007-11-02 Thread Stargaming
On Sat, 03 Nov 2007 07:18:17 +, Sullivan WxPyQtKinter wrote:

> I am confused by the following program:
> 
> def f():
> print x
> x=12345
> f()
> 
> result is:
>>>>
> 12345

If python can't discover x in your current scope and you do not bind to 
it there, it will automatically access that global name x.

> however:
> def f():
> print x
> x=0
> 
> x=12345
> f()
> 
> result is:
> Traceback (most recent call last):
>   File "...\test.py", line 5, in ?
> f()
>   File "...\test.py", line 2, in f
> print x
> UnboundLocalError: local variable 'x' referenced before assignment

Here, you *do* assign to x in this scope so this is essentially the same 
as the following (without any function scope)::

print x
x = 12345

This can't work since you haven't used x when you try to print it.

You can make this work using the `global` statement::

>>> def foo():
... global x
... print x
... x = 0
...
>>> x = 12345
>>> print x
12345
>>> foo()
12345
>>> print x
0

See more in the `lexical reference about the global statement .

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


Re: tuples within tuples

2007-10-26 Thread Stargaming
On Fri, 26 Oct 2007 14:26:24 -0600, Michael L Torrie wrote:

> [EMAIL PROTECTED] wrote:
[snip]
>>>> ('tagA', None, [('tagB', None, ['bobloblaw], None)], None)
   ^
Syntax error behind ``'bobloblaw``.

>>> "C" isn't a tuple in your example either. It is a one-element
>>> list
>>> (the single element INSIDE the list is a tuple whose third element is
>>> a list containing a non-terminated string -- so the entire structure
>>> is invalid)
>>>
>>>
>> i'm not sure what u mean with "the entire structure is invalid"...
>> that's exactly what I got while parsing...
> 
> Your structure is correct.  Dennis just didn't read all the matching
> parens and brackets properly.

He certainly is -- *you* are misreading *him*. The nit he's picking is 
the non-terminated string (quotation mark/apostrophe missing).

Nit-picking'ly,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pydoc script.py vs. pydoc scriptpy

2007-10-22 Thread Stargaming
On Sat, 20 Oct 2007 15:02:26 +, BartlebyScrivener wrote:

> On Debian Etch, if ~/mypyscripts is in my bash PATH and also in
> PYTHONPATH, I get the following pydoc behaviors. Maybe this is
> intentional. I'm just checking to be sure I don't have something
> misconfigured in my environment.
> 
> If I have two scripts or modules  in ~/mypyscripts: one script.py and
> one scriptpy (no extension), and do:
> 
> $>pydoc script
> 
> I get the documentation strings for script.py.
> 
> However, if I do:
> 
> $>pydoc scriptpy
> 
> I get no doc strings, even if I am in the ~/mypyscripts directory, error
> message:
> "no Python documentation found for 'scriptpy'"
> 
> Instead I must do:
> 
> $>pydoc ~/mypyscripts/scriptpy
> 
> even though ~/mypyscripts is in both PATH and PYTHONPATH
> 
> Took me awhile to sort this out. Is this the way pydoc is supposed to
> work?
> 
> thanks,
> 
> rpd

>From the pydoc documentation:

The argument to pydoc can be the name of a function, 
module, or package, or a dotted reference to a class, 
method, or function within a module or module in a 
package. If the argument to pydoc looks like a path 
(that is, it contains the path separator for your 
operating system, such as a slash in Unix), and refers 
to an existing Python source file, then documentation 
is produced for that file.

Since `script` is a valid module name in your case, referencing 
script.py, pydoc uses this file. `scriptpy` is no valid module name and 
thus, does not work.

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


Re: class vs type

2007-10-19 Thread Stargaming
On Fri, 19 Oct 2007 12:21:25 -0400, Colin J. Williams wrote:

> Hrvoje Niksic wrote:
>> "Colin J. Williams" <[EMAIL PROTECTED]> writes:
>> 
>>> In Python Types and Objects, Shalabh Chaturvedi says (in the Python
>>> 3.0 documentation - New Style Classes)
>>>
>>> "The term class is traditionally used to imply an object created by
>>> the class statement. However, classes are now synonymous with types.
>>> Built-in types are usually not referred to as classes. This book
>>> prefers using the term type for both built-in and user created types."
>>>
>>> Do we need two different words to describe what is essentially the
>>> same thing?
>> 
>> We don't, not anymore, which is why the author chooses the word "type"
>> for both in the last sentence.
> In this case, why do we continue to use the word class to generate a
> type?
[snip]
> Doesn't Python 3 provide an opportunity to move away from discussions
> about new_style vs old-style?  This an opportunity to treat old-style
> as a historical artefact, not requiring current explanation.


So, do we have to decide between 'instance' and 'object' as well?

Old-style classes *are* deprecated in favor of new-style classes 
(whoops!) but the term 'class' is still valid (IMO). It's a common phrase 
in the OO-world and removing it from a Python programmer's vocabulary 
(what essentially wouldn't work so well, I suspect) won't help.

If you're speaking about just the syntax, well okay, this could be 
sensible in some unification-focussed vocabulary-minimalistic manner. But 
combining the class _statement_ and the type _expression_ would 
essentially change class definitions into expressions.

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


Re: C++ version of the C Python API?

2007-10-19 Thread Stargaming
On Fri, 19 Oct 2007 17:37:29 -0500, Robert Dailey wrote:

> Hi,
> 
> Is there a C++ version of the C Python API packaged with python 2.5? It
> would be nice to have a OOP approach to embedding python in C++. It
> would also be a bonus if this C++ Python API cleaned up a lot of the
> messy code involved in embedding python.
> 
> Thanks.

Perhaps, the remark about `C++ extensions`_ or `Embedding in C++`_ in the 
`Extending and Embedding`_ docs (described on doc.python.org as a 
"tutorial for C/C++ programmers") can help.

Depending on your level of embedding, those random annotations spread 
over the extending docs, found with a little patience and ctrl+f, might 
help:

  * "In C++, the operators new and delete are used with essentially the 
same meaning and we'll restrict the following discussion to the C case." 
-- `1.10 Reference counts <http://docs.python.org/ext/refcounts.html>`_
  * "Note that PyMODINIT_FUNC declares the function as void return type, 
declares any special linkage declarations required by the platform, and 
for C++ declares the function as extern "C"." -- `1.4 The Module's Method 
Table and Initialization Function <http://docs.python.org/ext/
methodTable.html>`_

Cheers,
Stargaming

.. _C++ extensions: http://docs.python.org/ext/cplusplus.html
.. _Embedding in C++: http://docs.python.org/ext/embeddingInCplusplus.html
.. _Extending and embedding: http://docs.python.org/ext/ext.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-18 Thread Stargaming
On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote:
[snip]
> 
> Note that there's also the reverse() function that returns a reverse
> iterator over any sequence, so you could also do:
> 
> li = list('allo')
> print ''.join(reverse(li))
> 

Note this certainly should've been `reversed()`, with a trailing 'd'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic and lazy import

2007-10-16 Thread Stargaming
On Tue, 16 Oct 2007 13:16:50 +, Alexandre Badez wrote:

> Hye everyone,
> 
> I'm would like to do something a bit tricky.
> 
> I would like when I do something like to create a __init__ package's
> (here calle my_package) file witch make an action when we try to import
> something in this package...
> 
> Quiet like __getattribute__ work for a class, I would like this kind of
> behaviour for a whole module or a package
> 
> be a bit clearer:
> I've got a normal package/module/class (whathever) where I do something
> like:
> 
> from my_package import my_module
> 
> (but in the my_package I've got only: my_package / __init__.py
> 
> And in the __init__ of my my_package something like __getattribute__
> (but for a module) that would return something for my_module
> 
> I know, that I can do something like charging everything "before" in
> __init__ like:
> my_module = the_thing_I_want
> 
> But I need it to be lazy (because I may have many module witch could be
> very awful...).
> 
> Any idea ?
> Is it possible ?

Depending on the exact complexity of your needs and exact use case just 
inserting some code on top of every module could suffice. To reduce 
boilerplate, if the task you're trying to realize is pretty generic for 
every module, you could insert another module hiding this code and used 
like this::

from .modregister import init
init(__name__)

If you really have to _create_ modules dynamically, follow the advice 
given earlier in this thread.

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


Re: Observer implementation question ('Patterns in Python')

2007-10-12 Thread Stargaming
On Fri, 12 Oct 2007 16:55:05 -0700, James Stroud wrote:

[snip]
> The use of __iadd__ & __isub__ as described in the article allows a neat
> shorthand, but does not function correctly in the context of new style
> classes.
> 
> James

But still, this call on a descriptor::

obj.descr += val

is resolved into::

descr.__get__(obj, obj.__class__).__iadd__(val)

under the condition that ``descr.__get__``'s return value supports 
`__iadd__`. After this is fully evaluated, `__set__` gets issued (as in 
``descr.__set__(obj, descr_get_iadd_stuff_here)``).

Besides, you could perfectly do this without any descriptors at all::

class E(object):
def __iadd__(self, val):
print "__iadd__(%s, %s)" % (self, val)
class C(object):
e = E()
c = C()
c.e += 42
# __iadd__(<__main__.E object at 0x...>, 42)

Adding `__call__` to this implementation should be easy.

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


Re: Declarative properties

2007-10-12 Thread Stargaming
On Thu, 11 Oct 2007 18:58:44 +0200, Bruno Desthuilliers wrote:
[snip]

Your implementation seems particularly broken. You do not return anything 
from `name()`, hereby removing name as an attribute (or: replacing it 
with its return value -- None). You should return ``property(**locals())
`` (or ``property(fget=fget, fset=fset, ...)``, whatever you like).

I'm going to point out a few other mistakes first:

> class Toto(object):
>def __iinit__(self, name):

Typo here: __init__

>  self.name = name
>@apply
>def name():
>  def fget(self):
>print "getting %s.name" % self
>return self._name
>  def fset(self, val):
>print "setting %s.name to %s" % (self, val) 
>self._name = name

It should be `val`, not `name`, huh? And, as mentioned above, the return 
value is missing.

>def say_hello(self):
>  print "Hello, my name is %s" % self.name

A fixed implementation could be something along these lines::

>>> class Toto(object):
...def __init__(self, name):
...  self.name = name
...@apply
...def name():
...  def fget(self):
...print "getting %s.name" % self
...return self._name
...  def fset(self, val):
...print "setting %s.name to %s" % (self, val)
...self._name = val
...  return property(**locals())
...def say_hello(self):
...  print "Hello, my name is %s" % self.name
...
>>> t = Toto("bruno")
setting <__main__.Toto object at 0xb792f66c>.name to bruno
>>> t.say_hello()
getting <__main__.Toto object at 0xb792f66c>.name
Hello, my name is bruno
>>> t.name
getting <__main__.Toto object at 0xb792f66c>.name
'bruno'
>>> t.name = "jon"
setting <__main__.Toto object at 0xb792f66c>.name to jon
>>> t.say_hello()
getting <__main__.Toto object at 0xb792f66c>.name
Hello, my name is jon

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


Re: struct.unpack less than 1 byte

2007-10-10 Thread Stargaming
On Wed, 10 Oct 2007 03:42:15 -0700, John Machin wrote:

> On Oct 10, 8:15 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> 2007/10/10, cprogrammer <[EMAIL PROTECTED]>:
>> > i need to read from a file a struct like this [1byte, 12bits, 12bits]
>> > reading 1 byte or more is not a problem ... but the 12 bits values
>> > are ...
>>
>> 12bits, 12bits == 3 byes
> 
> and 8 + 12 + 12 = 32 :-)
[snipped bitfiddling]

Or, if you're doing more of those parsing tasks (or just dislike bit 
shifting), you could have a look into `construct`_::

>>> from construct import *
>>> foo = BitStruct("foo", 
... Octet("spam"), # synonym for BitField("spam", 8) 
... BitField("ham", 12), 
... BitField("eggs", 12)
    ... )
>>> foo
Buffered('foo')
>>> foo.parse("\xff\xff\xff\xff")
Container(eggs = 4095, ham = 4095, spam = 255)

Cheers,
Stargaming

.. _construct: http://construct.wikispaces.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: supplying password to subprocess.call('rsync ...'), os.system('rsync ...')

2007-10-05 Thread Stargaming
On Fri, 05 Oct 2007 08:37:05 -0700, timw.google wrote:

> On Oct 5, 10:33 am, "timw.google" <[EMAIL PROTECTED]> wrote:
>> Hi
>>
>> I want to write a python script that runs rsync on a given directory
>> and host. I build the command line string, but when I try to run
>> subprocess.call(cmd), or p=subprocess.Popen(cmd, shell=True),or
>> os.system(cmd), I get prompted for my login password. I expected this,
>> but when I try to give my password, it's echoed back to the terminal
>> and the special characters in the password is (I think) getting
>> interpreted by the shell (zsh)
>>
>> I can't ssh w/o supplying a password. That's the way the security is
>> set up here.
>>
>> How do I use python to do this, or do I just have to write a zsh
>> script?
>>
>> Thanks.
> 
> I wrote a zsh script to do what I wanted, but I'd still like to know how
> to do it in Python.

`subprocess.Popen` has a keyword argument called `stdin` -- what takes 
the password, I guess. Assigning `subprocess.PIPE` to it and using 
`Popen.communicate` should do the trick. 

Check the documentation at http://docs.python.org/lib/module-
subprocess.html for details.

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


Re: Adding behaviour for managing "task" dependencies

2007-10-02 Thread Stargaming
On Tue, 02 Oct 2007 14:28:35 +, m.pricejones wrote:

> Hi,
> 
> I'm currently writing an animation pipeline in Python which is a system
> for controlling the flow of work and assets for a team of people working
> on a computer animated film. The system will be fairly large with a
> database backend.
> 
> One particular problem that I'd like to address is the need for managing
> dependent tasks. Often you need to process one particular set of
> information before starting on another so when you batch them all
> together and send them off to a set of computers to process you need
> some way of formulating the dependencies. This preferably ends up
> looking a lot like a Makefile in the end with syntax a bit like:
> 
> task task_name (dependencies):
> commands to complete the task
> ...
> 
> Where the dependencies are a list of other tasks that need to be
> completed first.
> 
> However I'd really like to do it in Python, but I'm thinking I'd might
> need to extend Python a bit in order to achieve the new syntax. I've
> seen attempts to do this within the Python syntax (Scons and buildIt)
> and I'm not a big fan of the way it ends up looking. I've worked at a
> place that has written it's own language to handle that sort of thing
> but then you end up with a language that is good for that but rubbish at
> everything else. 

Doesn't seem too bad if you just want to write down dependencies. Better 
have one tool/language doing it's job perfectly than having a big monster 
tool doing lots of jobs pretty bad.

This is also sometimes called domain-specific languages or `language 
oriented programming <http://www.onboard.jetbrains.com/is1/articles/04/10/
lop/>`_.

> Python seems like a good basis if I could tweak it slightly.
> 
> One particular point that interests me is the idea of maintaining
> compatibility with Python modules so you still have all the
> functionality. 

If you disagreed with my statements above, that's a good point. Would 
make deserialization of those nearly-Makefiles easier, too.

> This makes me think of the "from __future__ import ..."
> statements which, if I understand them correctly, can introduce new
> syntax like the with_statement, whilst still maintaining compatibility
> with older modules?

I might be wrong here but AFAIK those `__future__` imports just set some 
'compiler' flags. The documentation isn't saying much about the treatment 
of those statements but I guess they're handled internally (since 
__future__.py doesn't seem to do anything at all). See the `module 
documentation <http://docs.python.org/lib/module-future.html>`_ for 
details.
 
> Is this correct? Can anyone write a syntax changing module or is
> __future__ a hard coded special case? I realise I'll have to get into
> the C side of things for this. Are there other approaches to this that I
> really should be considering instead?

Syntax (as in: grammar) is compiled into the python binary. You can 
change the python source (as it's free) and recompile but, FWIW, I would 
not suggest this. You're _forking_ CPython then and well, this would be 
an additional project to maintain (merging all updates, fixes, releases 
into your fork etc.).

`PyPy <http://codespeak.net/pypy/>`_ could be slightly easier to adjust 
but still: extra project.

Another approach could be `Logix <http://livelogix.net/logix/>`_. It's an 
"alternate front-end for Python" with the ability to change its syntax on-
the-fly. I don't know how actively maintained it is, though.

> Any thoughts would be most appreciated, though I would like to stress
> that I don't think Python should support the syntax I'm proposing I'd
> just like to know if I can extend a copy of it to do that.

As stated above, there are several ways to change Python to support the 
syntax you want but hey, why do you need this? As far as I understood 
you, you want to use *normal* python functions and add dependencies to 
them. First thing popping into my mind is a simple function eg. ``depends
(source, target)`` or ``depends(target)(source)``. The second example 
would have the advantage of adapting neatly into the decorator syntax::

def early_task():
foo()

@depends(early_task)
def late_task():
bar()

The wrapping `depends` function could decide whether `early_task` is done 
already or not (and invoke it, if neccessary) and finally pass through 
the call to `late_task`.

This is just an example how you could use existing syntax to modelize 
dependencies, there are other ways I guess.

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


Re: Combine two dictionary...

2007-10-01 Thread Stargaming
On Mon, 01 Oct 2007 10:24:39 -0700, Abandoned wrote:

> Hi..
> dict1={1: 4,  3: 5}... and 2 millions element dict2={3: 3,  8: 6}... and
> 3 millions element
> 
> I want to combine dict1 and dict2 and i don't want to use FOR because i
> need to performance.
> 
> I'm sorry my bed english.
> King regards..

If mutation of one dict is okay, use the `update` method. As in::

dict1.update(dict2) # will update dict1 with dict2's items

Create a copy of one dictionary if you do not want to mutate them.
See http://docs.python.org/lib/typesmapping.html#l2h-294 for details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Using fractions instead of floats

2007-10-01 Thread Stargaming
On Sun, 30 Sep 2007 20:10:05 -0700, Andres Riofrio wrote:

[snip]
>>From what I've read, seems that the principal reason for rejecting the
> PEP is that there was not much need (enthusiasm)... Well, then I have a
> question: Is there a way to make 5/2 return something other than an
> integer? I can do:
> class int(int):
>   def __add__(self, other):
> pass
> but that will only work if I do int(5)/int(2)...
> 
> (setting __builtin__.int=int doesn't work, either)
> 
> What I'd like is to be able to implement what I put in the proposal, as
> I don't think it's a really big language change...
[snip]

You could make up an example implementation by using fractionizing_int
(1) / fractionizing_int(3) (or whatever name you come up with).

I don't know of any particularly nice way to Just Let It Work anywhere in 
python (perhaps some ugly byte code hacks, automatically wrapping ints). 
So, you would have to implement it in C if you want to propose this for 
CPython. And that's no 5 minute task, I guess.

Still, having this `int` behaviour working globally would include those 
previously mentioned irrational numbers (but Pi is rational in any 
visualization anyways, so FWIW that wouldn't be too much of a blockade). 
But where would you put normal integer division then? 
Introducing a new type seems best to me.

You could, as well, try to implement this in PyPy. If this would hit the 
broad masses is another question, though. ;)

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


Re: Select as dictionary...

2007-10-01 Thread Stargaming
On Mon, 01 Oct 2007 09:57:46 -0400, J. Clifford Dyer wrote:

> On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote
> regarding Select as dictionary...:
>> 
>> aia.execute("SELECT id, w from list") links=aia.fetchall()
>> print links
>> 
>> and result
>> [(1, 5), (2,5)...] (2 million result)
>> 
>> I want to see this result directly as a dictionary:
>> 
>> {1: 5, 2: 5 .}
>> 
>> How do i select in this format ?
>> 
> Try this:
> 
> aia.execute("SELECT id, w from list") 
> links=aia.fetchall()
> linkdict = dict()
> for k,v in links:
> linkdict[k] = v
> print linkdict

Besides using the already pointed out DB adapters, you can easily 
transform a list of items into a dictionary with the `dict` constructor::

>>> links = [(1, 5), (2, 5), (3, 10)]
>>> dict(links)
{1: 5, 2: 5, 3: 10}

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


Re: New to python

2007-09-29 Thread Stargaming
On Sat, 29 Sep 2007 21:20:10 -0700, Googy wrote:

> I am new to python...
> 
> The programming language i know well is C Can any one recommend me the
> good ebook for beginners. I have loads of ebooks but i am not able to
> decide which to start with which book. Also i am learning XML so later
> on i can switch to books on Python and XML but initially which book to
> read??
> 
> Please help...

Generically, `A byte of Python`_ and `Dive into Python`_ are pretty 
common. ABOP has a few comments for C programmers as well, AFAIK.

If you already got a few (e)books, you should perhaps just look through 
all of them and then, sequentially, read them.

.. _A byte of Python: http://www.byteofpython.info/download/
.. _Dive into Python: http://www.diveintopython.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can I run pythons IDLE from a command line??

2007-09-23 Thread Stargaming
On Sat, 22 Sep 2007 17:53:09 +0200, Thomas Jollans wrote:

> On Saturday 22 September 2007, [EMAIL PROTECTED] wrote:
>> Hi,
>> Is their a version of pythons IDLE that will run in a dos command line?
>> The reason is that I would like to be able to run python code
>> interactively from my parable by connecting to my desktop using remote
>> command line or a telnet program.
> 
> The Python interpreter should do fine. If your PATH environment variable
> is set up correctly, just run "python", otherwise it's somewhere in your
> Python installation directory.

If you don't want to miss IDLE's advantages, `IPython `_ might be interesting for you.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-21 Thread Stargaming
On Fri, 21 Sep 2007 23:44:00 -0400, Carl Banks wrote:

> Anyone with me here?  (I know the deadline for P3 PEPs has passed; this
> is just talk.)
> 
> Not many people are bit-fiddling these days.

Why did we invent the `binary literals`_ (0b101) then?
  
> One of the main uses of
> bit fields is flags, but that's not often done in Python because of
> keyword arguments and dicts, which are lot more versatile.  Another
> major use, talking to hardware, is not something oft done in Python
> either.

Talking to hardware, parsing files or network streams and all this stuff 
where you cannot rely on 8 bit encoding so well.

> It seems like this occasional usage wouldn't justify having built-in
> operators on its own.  And with the int/long unification, it makes a bit
> less sense to think of integers as a bit field.  Python has these
> operators because of its heritage, but Python continues to move away
> from the bad habits of its ancestors (integer division and so on), and I
> wonder if this isn't another one.

Heh, ``0b1 / 0b11`` would be 0.1 then. Particularly 
funny. ;)

> Of course I'm not suggesting to get rid of bitwise operations
> altogether; just make them builtin functions: "x & 1" becomes
> "bitwise_and(x,1)" and so on.
>
> Is it worth it to make such a change?  It would remove a lot of
> operators (11 by my count), vastly simplifying syntax,  Which, IMHO, is
> no small thing.  New numerical types would have fewer operations to
> support.  And let's face it: unlike arithmetic opertaions, there's not a
> lot of different meanings for bit operations. And it would also, um,
> make new special characters available *cough*.

You're right about the simplification here perhaps. But nobody is forced 
to either learn or use (please, don't invert this argument justifying "we 
can implement any feature then -- don't use it if you don't like it!" ;)) 
them. But it's just a little bit sugar -- like, say, decorators -- and I 
like that.
 
> Obviously, how widespread their usage is would matter.  But keep in mind
> it would also be easy to convert the code automatically, because the
> Python parser could reliably find all bitwise operations reliably.  (The
> problem would be types that overloaded them to be something other than
> bitwise operations: I'm looking at you, set.  That could very well be a
> deal breaker.  I've never approved of things with completely different
> meanings being deliberately overloaded to have the same spelling; this
> is one reason why.)

A quick `google code search`_ failed but IMO those operators give you 
some freedom to make *your* classes more syntactical-sugar'ly. ``<<`` is 
used in PyParsing, as far as I know.

> If anyone says, "But that takes away an easy test for oddness (x&1)!",
> or, "But you can multiply powers of two using left shift!  Isn't that
> cool?", I'm not buying it.  Those are gimmicks.  Arithmetic operations
> should be done with arithmetic operators.  The bitwise operators make
> the code much less readable, especially to people unfamiliar with this
> usage.

Full acknowledgement! But in bit-wise environments, they can be 
particularly useful.

> the-above-pun-was-intended-ly yr's,
> 
> Carl Banks

.. _binary literals: http://www.python.org/dev/peps/pep-3127/
.. _google code search: http://www.google.com/codesearch?hl=en&lr=&q=lang%
3Apython+%3C%3C+%3E%3E+%7E+%26+%5C%7C+%5C%5E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frange() question

2007-09-20 Thread Stargaming
On Thu, 20 Sep 2007 09:08:17 -0400, George Trojan wrote:

> A while ago I found somewhere the following implementation of frange():
> 
> def frange(limit1, limit2 = None, increment = 1.):
>  """
>  Range function that accepts floats (and integers). Usage:
>  frange(-2, 2, 0.1)
>  frange(10)
>  frange(10, increment = 0.5)
>  The returned value is an iterator.  Use list(frange) for a list.
>  """
>  if limit2 is None:
>  limit2, limit1 = limit1, 0.
>  else:
>  limit1 = float(limit1)
>  count = int(math.ceil(limit2 - limit1)/increment) return (limit1 +
>  n*increment for n in range(count))
> 
> I am puzzled by the parentheses in the last line. Somehow they make
> frange to be a generator:
>  >> print type(frange(1.0, increment=0.5))
> 
> But I always thought that generators need a keyword "yield". What is
> going on here?
> 
> George

Consider the following:

def foo():
yield 1
def bar():
return foo()

Still, ``type(bar())`` would be a generator.

I don't want to tell you anything wrong because I don't know how 
generators are implemented on the C level but it's more like changing 
foo's (or frange's, in your example) return value.

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


Re: boolean operations on sets

2007-08-06 Thread Stargaming
On Mon, 06 Aug 2007 14:13:51 +, Flavio wrote:

> Hi, I have been playing with set operations lately and came across a
> kind of surprising result given that it is not mentioned in the standard
> Python tutorial:
> 
> with python sets,   intersections  and unions are supposed to be done
> like this:
> In [7]:set('casa') & set('porca')
> Out[7]:set(['a', 'c'])
> 
> In [8]:set('casa') | set('porca')
> Out[8]:set(['a', 'c', 'o', 'p', 's', 'r'])
> 
> and they work correctly. Now what is confusing is that if you do:
> 
> In [5]:set('casa') and set('porca')
> Out[5]:set(['a', 'p', 'c', 'r', 'o'])
> 
> In [6]:set('casa') or set('porca')
> Out[6]:set(['a', 'c', 's'])
> 
> The results are not what you would expect from an AND  or OR operation,
> from the mathematical point of view! aparently the "and" operation is
> returning the the second set, and the "or" operation is returning the
> first.

That might be, because `and` and `or` are not mathematical in Python (at 
least not as you think). All the operator bits, e.g. `|` and `&`, are 
overloadable. You can just give them any meaning you want.

The `and` and `or` operator, though, are implemented in Python and there 
is no way you can make them behave different from how they do it by 
default. It has been discussed to remove this behaviour or make them 
overloadable as well but this hasn't made it far, as far as I remember.

> If python developers wanted these operations to reflect the traditional
> (Python) truth value for data structures: False for empty data
> structures and True otherwise, why not return simply True or False?

Because in the most cases, returning True of False simply has no 
advantage. But returning the actual operands has been of fairly large 
use, e.g. for replacing the if expression ("ternary operator") ``THEN if 
COND else DEFAULT`` with ``COND and THEN or DEFAULT`` (which has some bad 
corner cases, though).

> So My question is: Why has this been implemented in this way? I can see
> this confusing many newbies...

Hmm, you could be right there. But they shouldn't be biased by default 
boolean behaviour, then, anyways.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Something in the function tutorial confused me.

2007-08-06 Thread Stargaming
On Mon, 06 Aug 2007 11:13:45 +, Alex Popescu wrote:

> Stargaming <[EMAIL PROTECTED]> wrote in news:46b6df49$0$26165
> [EMAIL PROTECTED]:
> 
[snip]
>> 
>> You're just unluckily shadowing the name `y` in the local scope of
> your
>> function. Your code snippet could be rewritten as::
>> 
>>   def f(x, y=None):
>> if y is None: my_y = []
>> else: my_y = y
>> my_y.append(x)
>> return my_y
>> 
>> HTH,
>> Stargaming
> 
> For the given example this will continue to print:
> 
>> print f(23)  # prints [23]
>> print f(42)  # prints [42]
> 
> so this doesn't solve/explain OP's initial question. A previous post has
> already clarified the reasons for seeing this normal behavior.
> 
> bests,
> ./alex

If it keeps normal behaviour, that's exactly what it ought to explain. In 
his local scope, there is an `y`, having the value of f.func_defaults. 
Because it's harder to see "hey, in some cases, y vanishes, in some it 
survives", I invented the new local reference `my_y` -- which should be 
clear to go away after completion of the function body.

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


Re: Something in the function tutorial confused me.

2007-08-06 Thread Stargaming
On Sun, 05 Aug 2007 23:50:24 -0700, Lee Fleming wrote:

> Hello,
> I have a simple question. Say you have the following function:
> 
> def f(x, y = []):
> y.append(x)
> return y
> 
> print f(23)  # prints [23]
> print f(42)  # prints [23, 42]
> 
> As far as I understand, the default value y, an empty list, is created
> when the def statement evaluates. With this thought in mind, the above
> calls
> to f make sense.
> 
> But this, the code that "fixes" the list accumulation confounds me: def 
> f(x, y=None):
> if y is None: y = []
> y.append(x)
> return y
> 
> print f(23)  # prints [23]
> print f(42)  # prints [42]
> 
> Why didn't the second call to f, f(42) return [23, 42]? As I understand
> it, y is only None at the beginning of f(23). Then y changes from None
> to 23. When f ends, doesn't y still have 23 in it,
> just as it did in the first function I discussed? And if y has 23 in it,
> won't the second call to f not execute what's in the if statement?
> 
> In other words, what's going on here? How is it that y accumulates
> argument values between function calls in the first function, but
> doesn't in the second one?

You're just unluckily shadowing the name `y` in the local scope of your 
function. Your code snippet could be rewritten as::

  def f(x, y=None):
if y is None: my_y = []
else: my_y = y
my_y.append(x)
return my_y

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


Re: Auto run/Timer

2007-08-04 Thread Stargaming
On Sat, 04 Aug 2007 08:27:05 +, Rohan wrote:

> Hello,
> I would like my script to run once a week with out any external
> interference.
> More like a timer. Can it be done in python or should some other shell
> scripting be used.
> If anyone knows anything please let me know.

`cron` should be your way to go, IMO. `/etc/cron.weekly/` might be a 
starting point (copy your script into this directoy).

And, yes, it can be done using pure Python (but I wouldn't do it). See 
`threading.Timer `_.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a dict trick

2007-08-02 Thread Stargaming
On Thu, 02 Aug 2007 06:32:11 +, james_027 wrote:

> hi
> 
> for example I have this dictionary
> 
> dict = {'name':'james', 'language':'english'}

First of all, this is a bad name because it shadows (overwrites) the 
reference to the builtin constructor, `dict`.

> value = 'sex' in dict and dict['sex'] or 'unknown'
> 
> is a right pythonic of doing this one? I am trying to get a value from
> the dict, but if the key doesn't exist I will provide one.

If you're using using Python 2.5, you could do this without `and`/`or` 
trickery::

>>> d['name'] if 'name' in d else 'unknown'
'james'
>>> d['sex'] if 'sex' in d else 'unknown'
'unknown'

But there are more elegant ways. For example, the `get` method::

>>> d.get('name', 'unknown')
'james'
>>> d.get('sex', 'unknown')
'unknown'

See the `Python Library Reference, 3.8: Mapping types ` for more information on 
`dict` methods.

Or you could use the `collections.defaultdict <http://docs.python.org/lib/
defaultdict-objects.html>` type (new in 2.5, too), which I consider most 
elegant::

>>> from collections import defaultdict
>>> d2 = defaultdict(lambda:'unknown', d)
>>> d2['name']
'james'
>>> d2['sex']
'unknown'

HTH,
Stargaming

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


Re: Assertion in list comprehension

2007-08-01 Thread Stargaming
On Wed, 01 Aug 2007 11:28:48 -0500, Chris Mellon wrote:

> On 8/1/07, beginner <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> Does anyone know how to put an assertion in list comprehension? I have
>> the following list comprehension, but I want to use an assertion to
>> check the contents of rec_stdl. I ended up using another loop which
>> essentially duplicates the functions of list comprehension. It just
>> look like a waste of coding and computer time to me.
>>
>> I just wish I could put the assertions into list comprehensions.
>>
>> x=[(rec_stdl[0].st/1.0,
>> rec_stdl[0].cl,
>> rec_stdl[0].bb,
>> rec_stdl[0].bo,
>> rec_stdl[1].bb,
>> rec_stdl[1].bo,
>> rec_stdl[0].ex
>>)
>>for rec_stdl in rec_by_ex if len(rec_stdl)==2
>> ]
>>
>> #duplicated loop
>> if __debug__:
>> for rec_stdl in rec_by_ex:
>> l=len(rec_stdl)
>> assert(l<=2 and l>0)
>> if l==2:
>> assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P")
>> assert(rec_stdl[0].ex==rec_stdl[1].ex)
>> assert(rec_stdl[0].st==rec_stdl[1].st)
>> assert(rec_stdl[0].cp==rec_stdl[1].cp)
> 
> First: All your asserts are wrong. Assert is a statement, not a
> function. These specific ones will behave as expected, but it's easy to
> accidentally write ones that always pass this way.

Could you come up with an example? I can only think of accidentally 
injecting a comma, what would create a (true, in a boolean context) tuple.

And, well, if you're only using () for readabilty, this might sometimes 
look messy when calling assert with the extended syntax::

  assert(False), "error text"

Where one could expect the construction of a tuple.

> Secondly: This is a waste of code, because if __debug__ is not defined
> asserts will be skipped by the compiler. You could use the same loop
> block for both branches.

Well, the `assert` isn't there for no reason, but if you're serious about 
it, `raise` could be better.

> Thirdly: This sort of testing is precisely what unit tests and/or
> doctests are for.

Huh? What beginner is doing there seems more like input validation than 
testing. Unit or doctests are meant for testing (and in case of doctests, 
showing) whether a function works as expected.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python end of file marker similar to perl's __END__

2007-08-01 Thread Stargaming
On Wed, 01 Aug 2007 06:56:36 -0400, Steve Holden wrote:

> Stargaming wrote:
>> On Wed, 01 Aug 2007 05:44:21 +, Michele Simionato wrote:
>> 
>>> On Aug 1, 5:53 am, beginner <[EMAIL PROTECTED]> wrote:
>>>> Hi All,
>>>>
>>>> This is just a very simple question about a python trick.
>>>>
>>>> In perl, I can write __END__ in a file and the perl interpreter will
>>>> ignore everything below that line. This is very handy when testing my
>>>> program. Does python have something similar?
>>> I wished from something like that. What you can do at the moment, is
>>> to comment or triple quote the code you don't want to run.
>> 
>> Or, if in a function body, you could insert a `return` statement. When
>> in top-level code, invoking `sys.exit` (or exit/quit) can do the trick.
>> A ``raise Exception`` might help, too, but could be kinda distracting
>> sometimes.
>> 
>> So, there is no general purpose solution as perl has it (I guess that
>> __END__ works everywhere at least), rather different solutions for
>> different cases.
> 
> I think you have missed the point. A return statement or call to
> sys.exit() doesn't remove the requirement that the rest ofthe source
> file be legal Python. In a Perl program you can put anything you like
> after __END__.
> 
> regards
>   Steve

That was my point actually. No, there is no such general purpose solution 
as in perl, but if he just wanted to quit execution (to, eg., not commit 
changes to his database), this would be the way to go. Multiline strings 
are the other way to include (nearly) arbitrary data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python end of file marker similar to perl's __END__

2007-07-31 Thread Stargaming
On Wed, 01 Aug 2007 05:44:21 +, Michele Simionato wrote:

> On Aug 1, 5:53 am, beginner <[EMAIL PROTECTED]> wrote:
>> Hi All,
>>
>> This is just a very simple question about a python trick.
>>
>> In perl, I can write __END__ in a file and the perl interpreter will
>> ignore everything below that line. This is very handy when testing my
>> program. Does python have something similar?
> 
> I wished from something like that. What you can do at the moment, is to
> comment or triple quote the code you don't want to run.

Or, if in a function body, you could insert a `return` statement. When in 
top-level code, invoking `sys.exit` (or exit/quit) can do the trick. A 
``raise Exception`` might help, too, but could be kinda distracting 
sometimes.

So, there is no general purpose solution as perl has it (I guess that 
__END__ works everywhere at least), rather different solutions for 
different cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Stargaming
On Mon, 30 Jul 2007 11:00:14 -0500, Edward K Ream wrote:

>> The problem is because you are trying to represent a Python
> program as a Python string literal, and doing it incorrectly.
> 
> Yes, that is exactly the problem.  Thanks to all who replied.  Changing
> changing '\n' to '\\n' fixed the problem.

Raw strings (r'this \n will stay') might help, too. See http://
docs.python.org/ref/strings.html#l2h-14
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about math module notation

2007-07-26 Thread Stargaming
On Thu, 26 Jul 2007 15:54:11 -0400, brad wrote:

> How does one make the math module spit out actual values without using
> engineer or scientific notation?
> 
> I get this from print math.pow(2,64): 1.84467440737e+19
> 
> I want this:
> 18,446,744,073,709,551,616
> 
> I'm lazy... I don't want to convert it manually :)

Explicitly converting it to `int` works for me. (Without the 3-digit-
block notation, of course.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scope PyQt question

2007-07-26 Thread Stargaming
On Thu, 26 Jul 2007 06:41:44 -0700, dittonamed wrote:

> Code pasted below ->
> 
> Can anyone out there suggest a way to access the object "p" thats
> started in playAudio() from inside the stopAudio()? I need the object
> reference to use QProcess.kill() on it. The code sample is below. Thanks
> to anyone who helps out =)
> 
> More comments in the code below  -->
> 
> 
> from qt import *
> 
> class Form2(QMainWindow):
> def __init__(self,parent = None,name = None,fl = 0):
> QMainWindow.__init__(self,parent,name,fl) self.statusBar()
> 
> def playAudio(self):
> p = QProcess(self, 'player')
> playcmd = '/usr/bin/play'
> filename = 'song.ogg'
> p.addArgument(playcmd)
> p.addArgument(filename)
> p.start()
> 
> def stopAudio(self):
> ''' #This is just to show that i can "see" the object, though
> i
>#dont know how to "access" it
>#the output shows the QProcess object by name... # but how do
>i reference it??
> allobjs = list(QObject.objectTrees()) for obj in allobjs:
> objName = QObject.name(obj)
> if objName == 'Form2':
> print QObject.children(obj)
> '''
> 
> QProcess.kill(NEED THE REFERENCE HERE)

Answering from a non-Qt point of view (ie. I don't know if there were 
cleaner ways using Qt stuff), you have to bind p somewhere not local to 
the function. Any attribute of `self` (that's hopefully not used by 
QMainWindow) should be fine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword argument 'from'; invalid syntax

2007-07-25 Thread Stargaming
On Thu, 26 Jul 2007 12:08:40 +1000, Steven D'Aprano wrote:

> On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote:
> 
>> I have tried to prepare a dict and then passing it to the method
>> afterwards:
> d = {'person': 'user', 'from': vorgestern}
> magnolia.bookmarks_find(d)
>> : bookmarks_find() takes exactly 1
>> argument (2 given)
>> 
>> I'm out of ideas so help is greatly appreciated!
> 
> Try this:
> 
> magnolia.bookmarks_find(**d)
> 
> although I suspect that will probably raise an exception as well.
> Judging by the error message, it looks like bookmarks_find() takes only
> a single argument, which I imagine would be the "self" instance
> automatically provided at runtime.

Could be bookmarks_find(person, **other), unpacking other manually.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cls & self

2007-07-25 Thread Stargaming
On Thu, 26 Jul 2007 03:07:56 +, james_027 wrote:

> hi,
> 
> is cls & self the same thing?
> 
> I have seen something like
> 
> class A:
> def dosomething(cls):
>#doing something
> 
> How is cls & self differ? How is it use?
> 
> Thanks
> james

First, you have to understand that the choice of this name is *completely 
arbitrary*. You could call it self, cls, this, bogus, helloworld or 
whatsoever. The important thing is just: The first argument is (by 
default) the instance.

Amongst python developers, many things aren't enforced by the language 
(eg. implicit `this` referencing the instance, as in other languages) but 
by conventions. It's just way more convenient to call it `self` always. 
We call it `cls` when speaking about classmethods. Your method there 
might have been headed by a line containing [EMAIL PROTECTED]

See http://docs.python.org/lib/built-in-funcs.html#l2h-16 for classmethod 
and http://docs.python.org/tut/node11.html#SECTION001140 
for this conventional stuff (paragraph "Often, the first argument ...").

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


Re: Reading files, splitting on a delimiter and newlines.

2007-07-25 Thread Stargaming
On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote:

> On Jul 25, 10:46 am, [EMAIL PROTECTED] wrote:
>> Hello,
>>
>> I have a situation where I have a file that contains text similar to:
>>
>> myValue1 = contents of value1
>> myValue2 = contents of value2 but
>> with a new line here
>> myValue3 = contents of value3
>>
>> My first approach was to open the file, use readlines to split the
>> lines on the "=" delimiter into a key/value pair (to be stored in a
>> dict).
>>
>> After processing a couple files I noticed its possible that a newline
>> can be present in the value as shown in myValue2.
>>
>> In this case its not an option to say remove the newlines if its a
>> "multi line" value as the value data needs to stay intact.
>>
>> I'm a bit confused as how to go about getting this to work.
>>
>> Any suggestions on an approach would be greatly appreciated!
> 
> I'm confused. You don't want the newline to be present, but you can't
> remove it because the data has to stay intact? If you don't want to
> change it, then what's the problem?
> 
> Mike

It's obviously that simple line-by-line filtering won't handle multi-line 
statements.

You could solve that by saving the last item you added something to and, 
if the line currently handles doesn't look like an assignment, append it 
to this item. You might run into problems with such data:

  foo = modern maths
  proved that 1 = 1
  bar = single

If your dataset always has indendation on subsequent lines, you might use 
this. Or if the key's name is always just one word.

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


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Stargaming
On Wed, 25 Jul 2007 15:46:58 +, beginner wrote:

> On Jul 25, 10:19 am, Stargaming <[EMAIL PROTECTED]> wrote:
>> On Wed, 25 Jul 2007 14:50:18 +, beginner wrote:
[snip]
>>
>> > Another question is how do I pass a tuple or list of all the
>> > aurgements of a function to the function. For example, I have all the
>> > arguments of a function in a tuple a=(1,2,3). Then I want to pass
>> > each item in the tuple to a function f so that I make a function call
>> > f(1,2,3). In perl it is a given, but in python, I haven't figured out
>> > a way to do it. (Maybe apply? but it is deprecated?)
>> >>> def foo(a, b, c): print a, b, c
>> ...
>> >>> t = (1, 2, 3)
>> >>> foo(*t)
>>
>> 1 2 3
>>
>> Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
>> current/tut/node6.html#SECTION00674
>>
>> > Thanks,
>> > cg
>>
>> HTH,
>> Stargaming
> 
> Hi Stargaming,
> 
> I know the * operator. However, a 'partial unpack' does not seem to
> work.
> 
> def g():
>   return (1,2)
> 
> def f(a,b,c):
>   return a+b+c
> 
> f(*g(),10) will return an error.

http://docs.python.org/ref/calls.html

> Do you know how to get that to work?

Well, there are several ways to solve this. You could either invoke f(*g
() + (10,)). Might be a bit nasty and unreadable, though. Or you could 
just change your function f to accept them in reversed order (f(10, *g) 
should work) or convert g() to return a dictionary like {'b': 1, 'c': 2} 
and use f(10, **g). But if your function f's hugest use case is being 
called with g(), changing f to accept something and g's result (tuple) -- 
unpacking it inside f -- might be better.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a list/tuple and Call a function with tuples

2007-07-25 Thread Stargaming
On Wed, 25 Jul 2007 14:50:18 +, beginner wrote:

> Hi,
> 
> I am wondering how do I 'flatten' a list or a tuple? For example, I'd
> like to transform[1, 2, (3,4)] or [1,2,[3,4]] to  [1,2,3,4].

A recursive function, always yielding the first element of the list, 
could do the job. See the ASPN Python Cookbook for a few implementations.
http://aspn.activestate.com/ASPN/search?
query=flatten§ion=PYTHONCKBK&type=Subsection

> Another question is how do I pass a tuple or list of all the aurgements
> of a function to the function. For example, I have all the arguments of
> a function in a tuple a=(1,2,3). Then I want to pass each item in the
> tuple to a function f so that I make a function call f(1,2,3). In perl
> it is a given, but in python, I haven't figured out a way to do it.
> (Maybe apply? but it is deprecated?)

>>> def foo(a, b, c): print a, b, c
...
>>> t = (1, 2, 3)
>>> foo(*t)
1 2 3

Have a look at the official tutorial, 4.7.4 http://www.python.org/doc/
current/tut/node6.html#SECTION00674

> Thanks,
> cg

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


Re: Recursive lists

2007-07-24 Thread Stargaming
On Tue, 24 Jul 2007 02:14:38 -0700, mizrandir wrote:

> Can someone tell me why python doesn't crash when I do the following:
> 
 a=[]
 a.append(a)
 print a
> [[...]]
 print a[0][0][0][0][0][0][0]
> [[...]]
> 
> How does python handle this internally? Will it crash or use up lot's of
> memory in similar but more complicated cases?

It should be like you pointing your finger at yourself and yelling I 
guess. Just a reference, no new object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From D

2007-07-24 Thread Stargaming
On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote:

> There are various things I like about the D language that I think Python
> too may enjoy. Here are few bits (mostly syntactical ones):
> 
> 1) (we have discussed part of this in the past) You can put underscores
> inside number literals, like 1_000_000, the compiler doesn't enforce the
> position of such underscores, so you can also put them like this:
> 1_00_000. You can put them in literals of decimals, binary, hex, etc. I
> think it's quite useful, because when in Python code I have a line like:
> for i in xrange(100):
> I need some time to count the zeros, because the lower levels of my
> visual systems can't count/group them quickly (perceptually). While in a
> syntax like:
> for i in xrange(1_000_000):
> my eyes help me group them at once.

Sounds like a good thing to be but the arbitrary positioning doesnt make 
any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6).
 
> 2) Base 2 number literals, and base 2 "%b" printing with the writefln.
> Base-2 numbers are less common in Python code, but once in a while I use
> them. For example:
> import std.stdio;
> void main() {
>   auto x = 0b0100_0011;
>   writefln("%b", x);
>   writefln("%.8b", x);
>   writefln(x);
> }
> Prints:
> 111
> 0111
> 67

Accepted. http://www.python.org/dev/peps/pep-3127/#abstract

> 3) All string literals are multi line. So you can write: a = "how are
> you";
> There's no need for """ """.

Well, I think it's just better to recognize visually. If you read ``foo = 
"""...``, it's clear you can skip the next few lines because they're most 
likely a chunk of data, not program code. Single quotation mark makes 
clear this is just a very small token in the whole line. (Yes, there may 
be exceptions, there may be syntax highlighting.)

> 4) With D I have created an xsplit() generator, and from my tests it's
> quite faster than the split(), expecially if the string/lines you want
> to split are few hundred chars long or more (it's not faster if you want
> to split very little strings). So I think Python can enjoy such string
> method too (you can probably simulate an xsplit with a regular
> expression, but the same is true for some other string methods too).

Yea, that's a good idea -- fits into the current movement towards 
generator'ing everything. But (IIRC) this idea came up earlier and there 
has been a patch, too. A quick search at sf.net didn't turn up anything 
relevant, tho.

> Bye,
> bearophile

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


Re: Itertools question: how to call a function n times?

2007-07-19 Thread Stargaming
Matthew Wilson schrieb:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
> 
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
> 
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
> 
> phrase = list()
> for i in random.randint(1, 5):
> 
> phrase.append(random.choice(wordlist))
> 
> It just seems slow. 
> 
> All advice welcome.
> 
> TIA
> 
> Matt
> 

You could do it either using the previously suggested list comprehension 
way or, if you don't need to have all choices in memory at once, use 
generator expressions. They're basically like list comprehensions, 
except that you wrap them into parentheses (), not brackets [].

phrase = (random.choice(wordlist) for i in xrange(random.randint(1, 5)))

You loose the ability to slice it directly (eg. phrase[3]), though. (See 
itertools.islice for a way to do it.)

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


Re: NoneType object not iterable

2007-07-13 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> Hi!
> My code is
> 
>  > db = {}
>  >
> 
>> def display():
>> keyList = db.keys()
>> sortedList = keyList.sort()
>> for name in sortedList:
>> line = 'Name: %s, Number: %s' % (name, db[name])
>> print line.replace('\r', '')
> 
> 
> And it gives following error:
> 
>> for name in sortedList:
>> TypeError: 'NoneType' object is not iterable
> 
> 
> How can sortedList variable turn into NoneType? I just don't get it...

It does not turn into something. The `sort()` method just works "in 
place", i. e. it will mutate the list it has been called with. It 
returns None (because there is no other sensible return value).

For you, that means: You don't have to distinguish between keyList and 
sortedList. Just call ``.sort()`` on keyList and it will just work.

HTH,
Stargaming

P.S. same information is in the docs: 
http://docs.python.org/lib/typesseq-mutable.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most efficient way to evaluate the contents of a variable.

2007-07-12 Thread Stargaming
bdude schrieb:
> Hey, I'm new to python and am looking for the most efficient way to
> see if the contents of a variable is equal to one of many options.
> 
> Cheers,
> Bryce R
> 

if var in ('-h', '--hello', '-w', '--world'):
 pass

Most maintenance-efficient, that is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bool behavior in Python 3000?

2007-07-12 Thread Stargaming
Steven D'Aprano schrieb:
> On Wed, 11 Jul 2007 08:04:33 +0200, Stargaming wrote:
> 
> 
> 
>>No, I think Bjoern just wanted to point out that all those binary 
>>boolean operators already work *perfectly*. You just have to emphasize 
>>that you're doing boolean algebra there, using `bool()`.
>>"Explicit is better than implicit."
> 
> 
> 
> So we should always write things explicitly like:
> 
> if bool(bool(some_condition) is True) is True:
> first_line = str(some_string).split(str("\n"))[int(0)]
> n = int(int(len(list(some_list))) + int(1))
> elif bool(bool(some_condition) is False) is True:
> f = float(math.sin(float(6.0)/float(math.pi)))
> 
> instead of the less explicit code. I'll try to remember that, thank you
> for the advice.
> 
> 
> 

You're missing like 400 bool(...) is True constructs there! Fatal error, 
recursion depth reached. Aww!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bool behavior in Python 3000?

2007-07-11 Thread Stargaming
Alan Isaac schrieb:
> Miles wrote:
> 
>> What boolean operation does '-' represent?
> 
> 
> Complementation.
> And as usual, a-b is to be interpreted as a+(-b).
> In which case the desired behavior is
> False-True = False+(-True)=False+False = False

I always thought, at least in a Python context, A-B would trigger 
A.__sub__(B), while A+(-B) triggers A.__add__(B.__neg__()). A better 
choice could be A+~B (A.__add__(B.__invert__())) because it's always 
unary (and IMO slightly more visible).

> In response to Stargaming, Steve is making
> a point about the incoherence of certain arguments,
> not proposing an implementation.

Why should it be incoherent? Bjoern is pointing out an important aspect 
of how Python handles binary algebra (correctly). In contrast, Steven 
tries to invert his argument. Following, I showed why Steven's proof is 
wrong because his implementation fails at some aspects where the current 
one works. So I cannot see how Bjoern's argument is either wrong or not 
relevant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bool behavior in Python 3000?

2007-07-11 Thread Stargaming
Alan Isaac schrieb:
> Stargaming wrote:
> 
>> I think Bjoern just wanted to point out that all those binary boolean 
>> operators already work *perfectly*. 
> 
> 
> 
>>>> bool(False-True)
> 
> True
> 
> But reread Steven.
> 
> Cheers,
> Alan Isaac

What would you expect this operation to return then?
The * and + operations described in the previously mentioned document 
(http://en.wikipedia.org/wiki/Two-element_Boolean_algebra) work as you'd 
expect them to do, if you explicitly state "hey, this should be a 
boolean algebra operation". And that's okay in my opinion. If you could 
describe what's wrong about that result, we could probably help better.

Steven just suggests another (IMO totally unrelated) implementation of 
bool types. A point that Bjoern does not even touch here. Besides, his 
implementations fails at the * operation.

Bjoern does not (sorry, if I say anything wrong, Bjoern) say the current 
behaviour is right or wrong. He just says that you can make Python aware 
of boolean algrebra utilizing `bool()` easily.

bool-ly,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bool behavior in Python 3000?

2007-07-10 Thread Stargaming
Steven D'Aprano wrote:
> On Tue, 10 Jul 2007 23:42:01 +0200, Bjoern Schliessmann wrote:
> 
> 
>>Alan G Isaac wrote:
>>
>>
>>>My preference would be for the arithmetic operations *,+,-
>>>to be given the standard interpretation for a two element
>>>boolean algebra:
>>>http://en.wikipedia.org/wiki/Two-element_Boolean_algebra
>>
>[bool(True+True), bool(True+False)]
>>
>>[True, True]
>>
>>Works for me, or did I misunderstand you?
> 
> 
> It seems to me that you deliberately misunderstood him. Why else would you
> type-cast the integers 2 and 1 to bools to supposedly demonstrate that
> there's nothing wrong with operations between bools returning ints?
[snip]

No, I think Bjoern just wanted to point out that all those binary 
boolean operators already work *perfectly*. You just have to emphasize 
that you're doing boolean algebra there, using `bool()`.
"Explicit is better than implicit."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an object instance by only having one of its attribute values

2007-07-08 Thread Stargaming
[EMAIL PROTECTED] wrote:
> Hello all,
> 
> Imaybe someone can help me with this question.
> Is there a direct way of accessing an object instance, if all I know
> is the value of one of its attributes?
> The object is part of a list of objects, and I would like to pick the
> object directly by using this attribute value, instead of going
> through the list and checking if each objects attribute value is the
> one I am looking for.
> 
> Thank you in advance
> 

Okay, imagine you got a bunch of small packets (presents or something 
similiar). You want to get rid of the lightest one. You cannot see 
weights, so, what you're doing is basically measuring the weight of 
*every single packet*, compare and pick. No way around.

There might be some ways not having to touch *each* object, if you 
precompute some results. So, in the example above, you could divide the 
packets into two categories, "more than 50 lbs" and "less than 50 lbs", 
for example. I think binary trees might be interesting here but touching 
every object would be way easier.

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


Re: newbie-question

2007-07-03 Thread Stargaming
TK wrote:
> how can I implement a socket timeout?

Risking an inadequate answer (since your description was not that 
detailled, try to express a little more exact!), I can suggest 
http://starship.python.net/crew/theller/pyhelp.cgi to browse the 
documentation. If you enter "timeout", the first match will be a good 
pointer. Look through the socket manual 
(http://docs.python.org/lib/module-socket.html) for timeout.

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


Re: howto run a function w/o text output?

2007-06-22 Thread Stargaming
dmitrey schrieb:
> hi all,
> I have a
> y = some_func(args)
> statement, and the some_func() produces lots of text output. Can I
> somehow to suppress the one?
> Thx in advance, D.
> 

Either rewrite it or pipe sys.stdout to some other file-like object but 
your console while running it. The StringIO 
(http://docs.python.org/lib/module-StringIO.html) module might help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try/except with multiple files

2007-06-22 Thread Stargaming
Matimus wrote:
> It depends, what are you going to do if there is an exception? If you
> are just going to exit the program, then that works fine. If you are
> going to just skip that file, then the above wont work. If you are
> going to return to some other state in your program, but abort the
> file opening, you might want to close any files that were opened. The
> closing can be taken care if in the except block, but you will have to
> know which ones opened successfully.
> 
> In general I would do something like this for multiple files:
> 
> [code]
> filenames = ["fname1","fname2","fname3"]
> for fn in filenames:
> try:
> f = open(fn)
> except IOError:
> # handle exception
> #do something with f
> [/code]
> 
> But, that might not work for you if the files aren't homogeneous (each
> have similar contents). If the files have distinctly different
> purposes, I would just wrap them each in their own try/except block.
> 
> I rambled a bit there, but I hope it helps.
> 
> Matt
> 

Heh, reminded me of http://worsethanfailure.com/Articles/Code-Reuse.aspx 
at the first glance. SCNR.

To add something on-topic, I'd just stick with the "one try for all 
files" option if your need is really "Try to open all files, if *at 
least one* of them fails, recover/abort/foobar/...".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the names of python keywords and functions

2007-06-22 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> I am trying to make a program for 3D modelling with "programming".And
> I want make my own program commands,
> 
> for example when user type code in my program:
> 
> "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD),
> 
> my program must write this code in some user file, but my
> 
> program must read this command like: "import os".How
> 
> can I do something like that??
> 
>Please, HELP ME somebody!!!
> 

Besides your request is sorta weird (languages are mostly meant to give 
a ruleset of expressions, not a framework of mutability, at least the 
more widespread ones), Python does not support something like this out 
of the box. There have been several discussions about such features and 
they were all abandoned due to unification.

You can, of course, follow the "normal" track to implement any language 
and write a parser, lexer, compiler and whatever. Tools like 
`pyparsing`_ or `PLY`_ might help you (there are much more).
Though, there *is* a mutable codeset of Python called `Logix`_. As far 
as I glanced at it, it is pretty mutable and might fit your needs perfectly.

Ah, and if you perhaps remove the leading << there, this might be pretty 
much implementable by overloading __rshift__ at your koristiti object.

HTH,
Stargaming

.. _pyparsing: http://pyparsing.wikispaces.com/
.. _PLY: http://www.dabeaz.com/ply/ply.html
.. _Logix: http://livelogix.net/logix/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to set a class inheritance at instance creation?

2007-05-29 Thread Stargaming
glomde schrieb:
> Hi I wonder if you can set what subclass a class should
> have at instance creation.
> 
> The problem is that I have something like:
> 
> class CoreLang():
> def AssignVar(self, var, value):
>  pass
> 
> class Lang1(CoreLang):
>  def AssignVar(self, var, value):
>   return var, "=", value
> 
> class Lang2(CoreLang):
>  def AssignVar(self, var, value):
>   return var, "<=", value
> 
> class WriteStruct():
>  def Generate(self, vars):
> for var in vars:
>  print self.AssignVar()
> 
> The problem is that I want  WriteStruct to sometimes be a subclass of
> Lang1 and sometimes
> of Lang2.
> In the above example I could but the Generate Method in CoreLang. But
> in my real
> example I also want to able to subclass WriteStruct to be able to easy
> customize WriteStruct.
> Which I wouldnt be able to do if it was a method in CoreLang.
> 
> So in code I would like to write something like:
> 
> WriteStruct(Lang1).Generate(vars)
> 
> Even better would be that if I in the Lang1 class could
> just do WriteStruct().Generate(vars) and Lang1 class would
> magically make WriteStruct a subclass of itself.
> 
> 
> Cheers,
> 
> /T
> 

If you really need to inherit at runtime, you could utilize `type()`.

 >>> def foo(self, blah):
...   print self, blah
...
 >>> attrs = {'foo': foo}
 >>> cls = type('MyCls', (object,), attrs)
 >>> cls().foo(4)
<__main__.MyCls object at 0x009E86D0> 4

Changing ``object`` (the tuple contains all bases) will change the 
parent. But, better stick to previous solutions. :)

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


Re: [Fwd: Re: managed lists?]

2007-05-21 Thread Stargaming
Jorgen Bodde schrieb:
> Hi Bruno,
> 
> Thanks for your answer.
> 
> Well what I am after is a list of relations to some class type. And in
> that list I do not wish to have accidentally put ints, strings, only
> one type of object, or interface. Now I can make the list interface
> safe, but it is only meant for relational purposes only. So to
> illustrate:
> 
> Song <>>> Tab
> Song <>--->> Tuning
> 
> I want a "tabs" collection only consisting of Tab objects. They are
> very specific so "mimicing" a tab interface is not something that will
> be done anytime soon.
> 
> I'm a traditional C++ programmer, and maybe I go through some
> transitional phase I don't know but exposing my list as read /
> (over)write property to the "outside world" being the rest of my
> object model, is just asking for problems. So this "strong" typed list
> will ensure me at "add" time the exception occurs, rather then
> somewhere in my applciation who knows much later that something blows
> up because the "object" from that list is retrieved and something
> unpredictable goes wrong. Is that so weird to do? As I said earlier I
> am a python newbie, I love the language, but the fact it can blow up
> at unpredictable times, gives me shivers.
> 
>> Everything in Python is an object. Including integers. And there's no
>> 'char' type in Python.
> 
> 
> The array type by the way says in the API that it can be constructed
> with a simple type like a char as in a "c" type, an int as in a "i"
> type etc..
> 
> See here:
> 
> http://www.python.org/doc/1.5.2p2/lib/module-array.html
> 
> So what I understand it's purpose is creating a buffer of some kind of
> a fixed type to maybe communicate with other DLL's or objects that
> require such a thing.
> 
> As I said, I might be going through a transitional phase, but exposing
> my relation list as simply a list class where all kinds of objects can
> be dumped in, seems too much for me at this point ;-)
> 
> Thanks,
> - Jorgen

Consider this: Who should add wrong-typed objects (see Bruno's post for 
reasons why you shouldn't care about types, anyways) to your list, when 
not you yourself? And if the programmer makes something wrong, he should 
fix it immediately. What happens if your application throws some error 
like "invalid type added to ObjectList"? Users won't unterstand it, so 
the intended audience is you again.

Good night,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python in a path that contains a blank

2007-05-21 Thread Stargaming
Konrad Hinsen schrieb:
> I am trying to install Python from sources in my home directory on a  
> Mac cluster (running MacOS X 10.4.8). The path to my home directory  
> contains a blank, and since the installation procedure insists on  
> getting an absolute path for the prefix, I cannot avoid installing to  a 
> path whose name contains a blank. Python does not seem to be  prepared 
> for this, as it uses only the part before the blank,  resulting in 
> numerous error messages.
> 
> Does anyone know a workaround?
> 
> Thanks,
>   Konrad.
> 

You could give /foo/bar\ baz/ham or "/foo/bar baz/ham" (either escaping 
the blanks or wrapping the path in quotation marks) a try. I can't 
verify it either, just guess from other terminals' behaviour.

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


Re: alternative to eclipse [ python ide AND cvs ]

2007-05-17 Thread Stargaming
yomgui schrieb:
> Hi,
> 
> Eclipse is just not really working on linux 64 bit
> (I tried ubuntu and centos, it is freesing and crashing
> and extremly slow)
> 
> I use eclipse for python and cvs, what is "the" good alternative ?
> 
> thanks
> 
> yomgui

Well, basically any editor that features plugins IMO. Although this 
sounds much like a "which editor is the best?" question (what will 
enrage us even more than non-ASCII identifiers ), I'd suggest Vim.

It is available at almost all platforms I guess (linux 64 bit should be 
*no* problem at all). You can make it match your personal editing 
preferences (I recently got in touch with the `:map` command -- 
wonderful one), extend it (there are lots of plugins as for example 
snippetsEmu that allows some Textmate-like autocompletion) and let it 
work with CVS (never tried it but a `search for CVS`_ yields dozens of 
results).

Ah -- and it works with python very well. Lots of plugins again, good 
highlighting, indentation support, built-in python shell (when compiled 
with +python).
(If you're going to give it a try, put something like ``autocmd FileType 
python map  :w:!python "%"`` into your .vimrc to get the 
IDE-feeling (F5 for write+execute) back in.)

Regards,
Stargaming

.. _search for CVS: 
http://www.vim.org/scripts/script_search_results.php?keywords=cvs&script_type=&order_by=rating&direction=descending&search=search
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A new project.

2007-05-17 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> I am interested in organizing and taking part in a project that would
> create a virtual world much like the one described in Neal
> Stephenson's 'Snow Crash'.  I'm not necessarily talking about
> something 3d and I'm not talking about a game either.  Like a MOO,
> only virtual.  And each 'user' is allocated space with which they are
> free to edit in any way, within the confines of that space.  I know
> Second Life and others come to mind when you think of this, but
> Frankly Second Life came off as sloppy to me.  I want people to be
> able to code their own objects and environments with the ease of
> Python.
> 
> I don't know forget the suggestions, anything is on the table, but
> there are just so many half-hearted and weak commercial attempts at
> this I feel that it's time to get Python involved in the game and do
> it right.
> 
> If anyone has any interest, ideas, comments or otherwise, e-mail me.
> If some interest is shown we'll start a board, a site, an IRC channel
> or whatever we have to do to meet and get the ball rolling. :)
> 
> Thanks.
> 

IMO, this sounds pretty interesting. Got any sources set up yet? 
Thinking of this as something like a "community effort" sounds nice.

Interestedly,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a number to binary?

2007-05-17 Thread Stargaming
Lyosha schrieb:
> On May 17, 4:40 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> 
>>On May 17, 2007, at 6:33 PM, Lyosha wrote:
>>
>>
>>>Converting binary to base 10 is easy:
>>>
>>>>>>int('', 2)
>>>
>>>255
>>
>>>Converting base 10 number to hex or octal is easy:
>>>
>>>>>>oct(100)
>>>
>>>'0144'
>>>
>>>>>>hex(100)
>>>
>>>'0x64'
>>
>>>Is there an *easy* way to convert a number to binary?
>>
>>def to_base(number, base):
>>'converts base 10 integer to another base'
>>
>>number = int(number)
>>base = int(base)
>>if base < 2 or base > 36:
>>raise ValueError, "Base must be between 2 and 36"
>>if not number:
>>return 0
>>
>>symbols = string.digits + string.lowercase[:26]
>>answer = []
>>while number:
>>number, remainder = divmod(number, base)
>>answer.append(symbols[remainder])
>>return ''.join(reversed(answer))
>>
>>Hope this helps,
>>Michael
> 
> 
> That's way too complicated...  Is there any way to convert it to a one-
> liner so that I can remember it?  Mine is quite ugly:
> "".join(str((n/base**i) % base) for i in range(20) if n>=base**i)
> [::-1].zfill(1)
> 

Wrote this a few moons ago::

   dec2bin = lambda x: (dec2bin(x/2) + str(x%2)) if x else ''

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


Re: omissions in python docs?

2007-05-17 Thread Stargaming
Anthony Irwin wrote:
> 7stud wrote:
> 
>> On May 17, 7:23 pm, 7stud <[EMAIL PROTECTED]> wrote:
>>
>> By the way, have the python doc keepers ever visited the php docs?  In
>> my opinion, they are the best docs of any language I've encountered
>> because users can add posts to any page in the docs to correct them or
>> post code showing how to get around various idiosyncrasies when using
>> the functions.
>>
> 
> Hi,
> 
> I also like the php docs and love that you can type any function into 
> the search at php.net and the documentation just comes up and there is 
> example code and then user comments also.
> 

For searching, we got at least pyhelp.cgi_.

HTH,
Stargaming

.. _pyhelp.cgi: http://starship.python.net/crew/theller/pyhelp.cgi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is wsgi ready for prime time?

2007-05-17 Thread Stargaming
Ron Garret wrote:
> The wsgiref module in Python 2.5 seems to be empty:
> 
> [EMAIL PROTECTED]:~/Sites/modpy]$ python
> Python 2.5 (r25:51908, Mar  1 2007, 10:09:05) 
> [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> 
import wsgiref
dir(wsgiref)
> 
> ['__builtins__', '__doc__', '__file__', '__name__', '__path__']
> 
> 
> So... is wsgi considered ready for production use, or is it still on the 
> bleeding edge?  And if the former, which implementation should one use?
> 
> rg

 >>> help(wsgiref)
Help on package wsgiref:

NAME
 wsgiref - wsgiref -- a WSGI (PEP 333) Reference Library

DESCRIPTION
 Current Contents:

 * util -- Miscellaneous useful functions and wrappers

 * headers -- Manage response headers

 * handlers -- base classes for server/gateway implementations

 * simple_server -- a simple BaseHTTPServer that supports WSGI

 * validate -- validation wrapper that sits between an app and a server
   to detect errors in either

 To-Do:

 * cgi_gateway -- Run WSGI apps under CGI (pending a deployment 
standard)

 * cgi_wrapper -- Run CGI apps under WSGI

 * router -- a simple middleware component that handles URL traversal

PACKAGE CONTENTS
 handlers
 headers
 simple_server
 util
 validate

Reading the documentation can be useful sometimes. Recommending 
http://docs.python.org/lib/module-wsgiref.html, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which is more pythonic/faster append or +=[]

2007-05-10 Thread Stargaming
Alex Martelli schrieb:
> 7stud <[EMAIL PROTECTED]> wrote:
>...
> 
>>>.append - easy to measure, too:
>>>
>>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)'
>>>100 loops, best of 3: 1.31 usec per loop
>>>
>>>brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]'
>>>100 loops, best of 3: 1.52 usec per loop
>>>
>>>Alex
>>
>>Why is it necessary to copy L?
> 
> 
> If you don't, then L gets longer and longer -- to over a million
> elements by the end of the loop -- so we're measuring something that's
> potentially very different from the problem under study, "what's the
> best way to append one item to a 3-items list".
> 
> That's important to consider for any microbenchmark of code that changes
> some existing state: make sure you're measuring a piece of code that
> _overall_ does NOT change said existing state in a cumulative way,
> otherwise you may be measuring something very different from the issue
> of interest.  It's maybe the only important caveat about using "python
> -mtimeit".
> 
> 
> Alex
>  

Cannot reproduce that. Consider the following:

$ python -mtimeit "L=range(3)" "L.append(1); print len(L)"
4
4
[...]
4
1000 loops, best of 3: [...]

Doesn't seem like copying is really neccessary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get type methods?

2007-05-03 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> Hello!
> 
> If I do
> 
> import uno
> localContext=uno.getComponentContext()
> 
> then localContext is of type 
> I guess it's a new type provided by PyUNO extension.
> localContext.__class__ is None
> Is there any way to list all methods of that new type, via Python C
> API or through interpreter (other then dir(localContext) )?

What's wrong about `dir()`?

> What I want is to call localContext's methods like in the tutorial
> example:
> 
> x=MyClass()
> MyClass.f(x)

I'd prefer::

   x = MyClass()
   x.f()

> 
> Thank you,
> Dmitri
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lazy evaluation: overloading the assignment operator?

2007-05-02 Thread Stargaming
sturlamolden wrote:
> Python allows the binding behaviour to be defined for descriptors,
> using the __set__ and __get__ methods. 

AFAIK, __getattribute__ calls them *explicitly*.

> I think it would be a major
> advantage if this could be generalized to any object, by allowing the
> assignment operator (=) to be overloaded.

> 
> One particular use for this would be to implement "lazy evaluation".
> For example it would allow us to get rid of all the temporary arrays
> produced by NumPy.
> 
> For example, consider the expression:
> 
[snip]
> 
>  y = a * b + c * d
> 
> would then result in something like this:
> 
> tmp1 = LazyExpr('__mul__',a,b) # symbolic representation of "a * b"
> tmp2 = LazyExpr('__mul__',c,d) # symbolic representation of "c * d"
> tmp3 = LazyExpr('__add__',tmp1,tmp1) # symbolic "a * b + c * d"
> del tmp1
> del tmp2
> y = tmp3 # tmp3 gets evaluated as assignment is overloaded
> 
To allow lazy evaluation, you need overloading of the assignment 
operator? Where should you overload it? y is less than None when you do 
that assignment. I don't really see the need for overloading here. 
Following the binding rules, __mul__ would (even without any hackery) be 
evaluated before __add__.

> 
> Should there be a PEP to overload the assignment operator? 

If -- after this discussion -- community seems to like this feature, you 
could try to come up with some patch and a PEP. But not yet.

> In terms of
> syntax, it would not be any worse than the current descriptor objects
> - but it would make lazy evaluation idioms a lot easier to implement.

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


Re: Having problems accepting parameters to a function

2007-05-01 Thread Stargaming
rh0dium schrieb:
> Hi Experts!!
> 
> I am trying to get the following little snippet to push my data to the
> function func().  What I would expect to happen is it to print out the
> contents of a and loglevel.  But it's not working.  Can someone please
> help me out.
> 
> ---
> #!/usr/bin/env python
> 
> import random
> 
> def func(*args, **kwargs):
>print kwargs.get('a', "NOPE")
>print kwargs.get('loglevel', "NO WAY")
> 
> def main():
>b = []
>for x in range(5):
>   b.append({'a':random.random(), "loglevel":10})
> 
>for y in b:
>   apply(func,y)
> 
> # First attempt - didn't work
> # for y in b:
> #   func(y)
> 
> if __name__ == '__main__':
>main()
> 
``apply()`` is deprecated -- use the asterisk-syntax_ instead.

 >>>> dic = {'a': 5, 'loglevel': 10}
 >>> def foo(*args, **kwargs):
...   print kwargs
...
 >>> foo(**dic)
{'a': 5, 'loglevel': 10}

So, your first attempt was close -- just two signs missing. :-)

HTH,
Stargaming

.. _asterisk-sytax: 
http://docs.python.org/tut/node6.html#SECTION00674
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SPE

2007-04-26 Thread Stargaming
Glich schrieb:
> Is SPE open source? I want to try to implement a windows compiler into
> the GUI using py2exe.
> 
> thanks!
> 
> -Glich
> 
Aye. The `Checkout Manual 
<http://pythonide.blogspot.com/2007/02/how-to-download-latest-spe-from_26.html>`_,
`WebSVN <http://svn.berlios.de/wsvn/python/spe/trunk/_spe/>`_ and 
`Submit a patch <http://developer.berlios.de/patch/?group_id=4161>` are 
likely to help you.

Greetings,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generalized range

2007-04-26 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> I need to create ranges that can start and end with real numbers.
> Searching this newsgroup brought me to a function that I then modified
> as follows:
> 
> def myRange(iMin, iMax=None, iStep=1):
Just as a sidenote: it is not common to prefix your names with its type. 
  It could change at any time and min, max, step would be clear, too. IMO.
> """Extends range to real numbers. Wherever possible, use Python's
> range .
>In other cases, make the behavior follow the spirit of Python's
> range """
If you want to stick to the "normal" range-implementation, myRange 
should consider an one-argument-call as transmission of iMax.
>epsilon = 1.e-8
I can't really say if your attempt using an epsilon-environment is good. 
I think just increasing a "counter" from iMin to iMax should be fine, 
achieving more precision by making computations fuzzy -- i don't know, 
perhaps it's very good. I wouldn't do it.
If you like to care about precision, you should have a look at the 
`decimal module <http://docs.python.org/lib/module-decimal.html>`_.
> 
> if iMax == None and iStep == 1:
> return range(int(iMin))
> 
> elif type(iMin).__name__.lower()  in ('int', 'long') and \
>  type(iMax).__name__.lower()  in ('int', 'long') and \
>  type(iStep).__name__.lower() in ('int', 'long') and iStep !=
> 0:
> return range( iMin, iMax, iStep)
Ouchie! *That* is a bad one. Checking for a name of an object is neither 
safe nor good nor common. A better way would be directly comparing 
type(yourobject) with int/long/float/anytype. See 
http://docs.python.org/lib/comparisons.html for details on comparisons.
Another way of type-checking in python is doing something like ``if 
isinstance(iMin, (int, long))``. Would work for subclasses, too.
> 
> elif iMin <= iMax and iStep > 0:
> return [ iMin+i*iStep for i in range( int(math.ceil((iMax -
> iMin - epsilon)/iStep)) )]
> 
> elif iMin >= iMax and iStep < 0:
> return [ iMin+i*iStep for i in range(-int(math.ceil((iMin -
> iMax + epsilon)/iStep)) )]
> 
Will eat your memory. See below.
> else:
> raise ValueError, 'Cannot construct a range with steps of size
> ' + str(iStep) + ' between ' + str(iMin) + ' and ' + str(iMax)
In Python, it is common to use string interpolation instead. Like::
   print 'Hello from %d to %d' % (iMin, iMax)
Read `String Formatting Operations 
<http://docs.python.org/lib/typesseq-strings.html>`_ in the manual for 
details.
> 
> 
> The one part of  my implementation that has me a bit queasy (i.e.
> works in my current application, but I can see it misbehaving
> elsewhere) is the addition/subtraction of a fixed epsilon to ensure
> that my rounding goes the right way. A clean implementation would
> modify epsilon based on the achievable level of precision given the
> particular values of iMax, iMin and iStep. I suspect this requires a
> detailed understanding of the implementation of floating point
> arithmetic, 
I think so, too. That's why it is a bad idea, IMO.
> and would appreciate hearing any thoughts you might have
> on gilding this lily.
> 
> Sincerely
> 
> Thomas Philips
> 

I'd recommend you to have a look into `generators 
<http://docs.python.org/ref/yield.html>`_, it is what `xrange 
<http://docs.python.org/lib/built-in-funcs.html#l2h-80>`_ uses. You 
don't put all numbers into your memory ("precompute them") but behave a 
little bit lazy and compute them whenever the user needs the next one. I 
expect Google to have lots of example implementations of range as a 
generator in python for you. :-)

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


Re: Suggestion: str.itersplit()

2007-04-22 Thread Stargaming
subscriber123 schrieb:
> On Apr 21, 8:58 am, Dustan <[EMAIL PROTECTED]> wrote:
> 
>>>From my searches here, there is no equivalent to java's
>>
>>StringTokenizer in python, which seems like a real shame to me.
>>
>>However, str.split() works just as well, except for the fact that it
>>creates it all at one go. I suggest an itersplit be introduced for
>>lazy evaluation, if you don't want to take up recourses, and it could
>>be used just like java's StringTokenizer.
>>
>>Comments?
> 
> 
> That would be good, because then you could iterate over strings the
> same way that you iterate over files:
> 
> for line in string.itersplit("\n"):
> ## for block ##
> 
> 

 >>> block = """Hello world.
... This is a comment.
... With a few more lines."""
 >>> for line in block.split("\n"):
...   print line
...
Hello world.
This is a comment.
With a few more lines.
 >>> for line in block.splitlines(): # could even use this one here
...   print line
...
Hello world.
This is a comment.
With a few more lines.

Iterators would just speed up the whole thing and be more pythonic 
(since development goes straight into the direction of converting all 
and everything into iterators).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error when trying to pass list into function.

2007-04-02 Thread Stargaming
erikcw schrieb:
> Hi,
> 
> I'm getting the following error when I try to pass a list into a
> function.
> 
> My List: crea =[(u'218124172', u'536', u'32394'), (u'218320282',
> u'1323', u'77931')]
> 
> Traceback (most recent call last):
>   File "wa.py", line 118, in ?
> curHandler.walkData()
>   File "wa.py", line 49, in walkData
> self.results[parent][child]['results'] = self.calculate(crea)
> #pass in list of tuples
> TypeError: calculate() takes exactly 1 argument (2 given)
> 
> def calculate(dta):
> #stub
> 
> How can I make this work?
> 
> Thanks!
> Erik
> 
The first argument to a method (a function bound to an instance) is 
always the instance itself. (I assume you *have* a method here because 
you call self.calculate(crea), what will itself call 
SomeClass.calculate(self, crea).)

For further information, consult the python tutorial 
http://docs.python.org/tut/node11.html#SECTION001140.

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


Re: #!/usr/bin/env python > 2.4?

2007-03-22 Thread starGaming
On Mar 22, 5:23 pm, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote:
> > I don't see any problem with::
>
> > if version_info[0] <= 2 and version_info[1] < 4:
> > raise RuntimeError()
>
> What if the version number is 1.5?

Ah, now I get your problem. OK.

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


Re: #!/usr/bin/env python > 2.4?

2007-03-22 Thread starGaming
On Mar 21, 11:11 pm, Sander Steffann <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Op 21-mrt-2007, om 20:41 heeft [EMAIL PROTECTED] het volgende
> geschreven:
>
>
>
> > On Mar 21, 11:07 am, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> >> In article <[EMAIL PROTECTED]>, Stargaming wrote:
> >>> from sys import version_info
> >>> if version_info[0] < 2 or version_info[1] < 4:
> >>>  raise RuntimeError("You need at least python2.4 to run this
> >>> script")
>
> >> That'll fail when the major version number is increased (i.e.
> >> Python 3.0).
>
> >> You want:
>
> >>   if sys.hexversion < 0x020400f0:
> >> ... error ...
>
> > Yes, it was intended to be and 'and' instead of an 'or'.
>
> If you make it an 'and' it will not raise the exception on version
> like 1.5 or 2.3... If you realy want to use version_info, you'll have
> to do something like:
>
> if version_info[0] < 2 or (version_info[0] == 2 and version_info[1] <
> 4):
> raise RuntimeError
>
> - Sander


I don't see any problem with::

if version_info[0] <= 2 and version_info[1] < 4:
raise RuntimeError()

Huh?

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


Re: #!/usr/bin/env python > 2.4?

2007-03-21 Thread starGaming
On Mar 21, 11:07 am, Jon Ribbens <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>, Stargaming wrote:
> > from sys import version_info
> > if version_info[0] < 2 or version_info[1] < 4:
> >  raise RuntimeError("You need at least python2.4 to run this script")
>
> That'll fail when the major version number is increased (i.e. Python 3.0).
>
> You want:
>
>   if sys.hexversion < 0x020400f0:
> ... error ...

Yes, it was intended to be and 'and' instead of an 'or'.

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


Re: How to copy a ClassObject?

2007-03-20 Thread Stargaming
Karlo Lozovina schrieb:
> Karlo Lozovina <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> 
> 
>>how would one make a copy of a class object? Let's say I have:
>>  class First:
>>name = 'First'
>>
>>And then I write:
>>  tmp = First
> 
> 
> Silly me, posted a question without Googling first ;>. This seems to be 
> the answer to my question:
> 
> import new
> class First:
> name = 'First'
> tmp = new.classobj('tmp', (First,), {})
> 
> After this, tmp is a copy of First, and modifying tmp.name will not affect 
> First.name.
> 
> P.S.
> If my code is somehow mistaken and might not function properly in all 
> cases, please correct me. 
> 
> Bye,
> klm.
> 
Leave out the `new` module and use `type()` (exactly the same call as to 
`new.classobj`) to achieve the same effect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/env python > 2.4?

2007-03-20 Thread Stargaming
rh0dium schrieb:
>>Python usually installs so the latest version gets linked as
>>/usr/bin/python. HTere's no need to bind your scripts to a particular
>>version.
>>
>>regards
> 
> 
> True - but that entirely depends on your path.  Example:
> 
> Redhat (RHEL3) ships with python2.3 in /usr/bin
> Adding an 2.5 version to /usr/local/bin
> 
> set PATH=/usr/local/bin:/usr/bin
> 
> "python" - will use 2.5
> 
> Conversely if you:
> set PATH=/usr/bin:/usr/local/bin
> 
> "python" - will use 2.3
> 
> but if I wanted to ensure I was using 2.5 I would simply type
> python2.5  I want to ensure that the python version I am using is at
> lease 2.4
> 
> 
> 

#!/usr/bin/env python

and

from sys import version_info
if version_info[0] < 2 or version_info[1] < 4:
 raise RuntimeError("You need at least python2.4 to run this script")

IMO you shouldn't struggle with it too hard. If the user's python 
version is not appropriate, don't hack its interpreter mechanism to do 
the work you need. Anyways, you should not check for specific python 
versions but for modules/APIs/builtins whatever and *then* you may raise 
an exception pointing the user to the fact that is python version does 
not fit your needs.

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


Re: print and softspace in python

2007-03-14 Thread Stargaming
Phoe6 schrieb:
> print and softspace in python
> In python, whenever you use >>>print statement it will append a
> newline by default. If you don't want newline to be appended, you got
> use a comma at the end (>>>print 10,)
> When, you have a list of characters and want them to be printed
> together a string using a for loop, there was observation that no
> matter what there was space coming between the characters. No split
> or  join methods helped.

Huh?
 >>> x = ['h', 'i', '!']
 >>> print ''.join(x)
hi!

I don't see any problem there. In the most cases you could also build up 
a string accumulatedly.


>>>>list1=['a','b','c']
>>>>for e in list1:
> 
>print e,
> a b c
> 
>>>># Without whitespace it will look like.
>>>>print "abc"
> 
> abc
> 
> The language reference says that print is designed to output a space
> before any object. And some search goes to find and that is controlled
> by softspace attribute of sys.stdout.
> Way to print without leading space is using sys.stdout.write()
> 
"Note: This attribute is not used to control the print statement, but to 
allow the implementation of print to keep track of its internal state."""
> 
>>>>import sys
>>>>for e in list1:
> 
>   sys.stdout.write(e)
> abc
> 
> Reference manual says:
> A space is written before each object is (converted and) written,
> unless the output system believes it is positioned at the beginning of
> a line. This is the case (1) when no characters have yet been written
> to standard output, (2) when the last character written to standard
> output is "\n", or (3) when the last write operation on standard
> output was not a print statement. (In some cases it may be functional
> to write an empty string to standard output for this reason.)
> 
> Question to c.l.p
> Am Not getting the last part as how you will write  a empty string and
> use print  not appending  blank space in a single line. 
I'd guess they think about print "",;print "moo" (print a blank string, 
do not skip line, print another one) to preserve the "softspace". As far 
as I get your problem, you don't really have to think about it.
> Am not getting
> the (In some cases... ) part of the reference manual section. Please
> help.
> 

Use the join-idiom correctly.

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


Re: New to Python

2007-03-12 Thread Stargaming
Bert Heymans schrieb:
> On Mar 12, 3:02 am, Alberto Vieira Ferreira Monteiro
> <[EMAIL PROTECTED]> wrote:
> 
>>Hi, I am new to Python, how stupid can be the questions I ask?
>>
>>For example, how can I add (mathematically) two tuples?
>>x = (1,2)
>>y = (3,4)
>>How can I get z = (1 + 3, 2 + 4) ?
>>
>>Alberto Monteiro
> 
> 
> 
> Alberto -
> 
> List comprehesion, no doubt about it:
> 
z = [k+p for k,p in (x, y)]
z
> 
> [3, 7]
> 
> - Bert
> 

Since 1+3 is not really (only if you use rally bad approximations) 3 
(neither 2+4 is 7!), i'd rather prefer using zip:
 >>> x = (1,2)
 >>> y = (3,4)
 >>> [k+p for k,p in (x,y)] # wrong one
[3, 7]
 >>> [k+p for k,p in zip(x,y)] # zip-version
[4, 6]

What your's is doing is unpacking the contents of x first to k and p and 
adding them to each other and afterwards doing the same with y's contents.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any better code to initalize a list of lists?

2007-03-11 Thread Stargaming
Donald Fredkin schrieb:
> John wrote:
> 
> 
>>For my code of radix sort, I need to initialize 256 buckets. My code
>>looks a little clumsy:
>>
>>radix=[[]]
>>for i in range(255):
>>   radix.append([])
>>
>>any better code to initalize this list?
> 
> 
> radix = [[[]]*256][0]
> 

 >>> x = [[[]]*256][0]
 >>> x
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], 
[], [], ...
 >>> x[0].append(1)
 >>> x
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], 
[1], [1], ...

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


Re: New to Python

2007-03-05 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> I am trying to get a program to add up input from the user to get to
> the number 100 using a loop.  However, I am having some issues.  Here
> is what I have so far.  I know I am just trying to hard, but I am
> stuck.  Thank you for any help.
> 
> print "We need to count to 100"
> 
> high_number = 100
> total = 0
> 
> number = input("Enter your first number ")
> sum = number + total
> while sum < high_number:
> print "Not there yet..."
> number = input("Enter another number ")
> 
> print "We are there!!!"
> 

Just reading the error messages would be a good start. You assign `sum` 
to `number + total` but as I see it there's no `number` so far. You have 
to increment some variable with the user's input. (`sum += input(..)`)
Additionally, `total` and `number` seem pretty redundant. You only need 
two variables, one containing the targeted number, one the current progress.
By the way, input() is considered pretty evil because the user can enter 
arbitrary expressions. It is recommended to use raw_input() (till Python 
3.0), in your case e. g. int(raw_input()) wrapped in a try-except block.
HTH,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question

2007-03-05 Thread Stargaming
Tommy Grav schrieb:
> Hi list,
> 
>this is somewhat of a newbie question that has irritated me for a  
> while.
> I have a file test.txt:
> 
> 0.3434  0.5322 0.3345
> 1.3435  2.3345 5.3433
> 
> and this script
> lines = open("test.txt","r").readlines()
> for line in lines:
>(xin,yin,zin) = line.split()
>x = float(xin)
>y = float(yin)
>z = float(zin)
> 
> Is there a way to go from line.split() to x,y,z as floats without  
> converting
> each variable individually?
> 
> Cheers
>Tommy

For this case, there are list comprehensions (or map, but you shouldn't 
use it any longer):

 >>> a = "0.3434  0.5322 0.3345"
 >>> b = a.split()
 >>> map(float, b)
[0.34338, 0.53221, 0.33452]
 >>> [float(x) for x in b]
[0.34338, 0.53221, 0.33452]

I think it should be easy to apply this to your example above.

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


Re: worker thread catching exceptions and putting them in queue

2007-03-05 Thread Stargaming
Paul Sijben schrieb:
> All,
> 
> in a worker thread setup that communicates via queues is it possible to
> catch exceptions raised by the worker executed, put them in an object
> and send them over the queue to another thread where the exception is
> raised in that scope?
> 
> considering that an exception is an object I feel it ought to be
> possible, however I do not see how to go about it.
> 
> does anyone have a pointer towards the solution?
> 
> Paul

You're right, even exceptions are objects in Python. For further 
studies, read http://docs.python.org/lib/module-exceptions.html

You can catch an exception like this:
try:
   worker.do_some_work_that_may_raise_an_exception()
except Exception, e:
   # the first argument is the type of error you want to handle
   # it is Exception here, the baseclass of all computation exceptions
   # the second argument is the variable (name) where you want to save
   # the specific exception raised to
   # it's 'e' here, a common shortcut for exception
   exception_handler.handle(e)
   # notice that you can pass e around as you like

For further information on exceptions and how to handle them, read 
chapter 8 of the tutorial, especially starting from 8.3: 
http://docs.python.org/tut/node10.html#SECTION001030

P.S. I don't know if what I told still applies to Python 3.0 -- a lot of 
changes are upcoming related to exception raising and handling.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (beginners question) howto set self.field4.subfield8='asdf'?

2007-02-19 Thread Stargaming
[EMAIL PROTECTED] wrote:
> Thx
> but is there any simpleir way, if using not class, but just struct (or
> something like that, MATLAB equivalent for that one)?

Use this::

 >>> A = type('', (), {})
 >>> a = A()
 >>> a
<__main__. object at 0x009E8490>
 >>> a.foo = 42
 >>> a.foo
42

But perhaps using this (with a better name) would be more sensible 
(according to readability)::

 >>> class B: pass
...
 >>> b = B()
 >>> b.foo = 42
 >>> b.foo
42

> I'm thinking of rewriting some optimization solvers (non-smooth,
> constrained, with (sub)gradients or patterns provided by user) to
> Python and I don't know currently is it possible to easy convert
> things like
> prob = [];
> prob.advanced.ralg.hs = 1 (so in this line all subfields are
> generating automatically in MATLAB or Octave)

Perhaps something like this would be suitable::

 >>> class Autocreating(object):
...   def __getattr__(self, attr):
... if hasattr(self, attr)
...   setattr(self, attr, Autocreating())
... return getattr(self, attr)
...
 >>> a = Autocreating()
 >>> a.foo = 42
 >>> a.foo
42
 >>> a.hello.world = 23
 >>> a.hello
<__main__.Autocreating object at 0x...>
 >>> a.hello.world
23

But this is perhaps not a good way because it's way too implicite.

> I have huge amount of such lines, and implementing separate class for
> each one is unreal.

You don't have to implement a separate class for *each one*. Use one 
class for every attribute, you can reuse it. But perhaps something like 
a dict is better for your purposes, anyways.

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


Re: randomly generate n of each of two types

2007-02-11 Thread Stargaming
Alan Isaac schrieb:
> I need access to 2*n random choices for two types
> subject to a constraint that in the end I have
> drawn n of each.  I first tried::
> 
> def random_types(n,typelist=[True,False]):
> types = typelist*n
> random.shuffle(types)
> for next_type in types:
> yield next_type
> 
> This works but has some obvious costs.
> To avoid those I considered this instead::
> 
> def random_types(n,typelist=[True,False]):
> type0, type1 = typelist
> ct0, ct1 = 0,0
> while ct0+ct1<2*n:
> if random.random() < ((n-ct0)/(2*n-ct0-ct1)):
> next_type = type0
> ct0 += 1
> else:
> next_type = type1
> ct1 += 1
> yield next_type
> 
> Does this seem a good way to go?  Comments welcome.

I think there's any easier way using random's function `shuffle`.

 >>> from random import shuffle
 >>> def randomly(n, types):
...   types *= n
...   shuffle(types)
...   for x in types: yield x
...
 >>> randomly(1, [True, False])

 >>> list(randomly(1, [True, False]))
[True, False]
 >>> list(randomly(2, [True, False]))
[True, False, True, False]
 >>> list(randomly(4, [True, False]))
[False, True, False, False, False, True, True, True]

You can even do this with an arbitrary number of choices:
 >>> list(randomly(2, [True, False, None, NotImplemented]))
[NotImplemented, None, NotImplemented, False, False, None, True, True]

Notice that this method works in-place, ie
 >>> a = [True, False]
 >>> list(randomly(2, a))
[False, False, True, True]
 >>> a # a changed!
[False, False, True, True]

This can be changed by creating a copy, though.

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


Re: from... import...

2007-02-02 Thread Stargaming
[EMAIL PROTECTED] schrieb:
> what's the from ... import keyword use for?
> for example - from contenttype import getContentType
> 
> import os
> import sys
> import getopt
> import types
> import re
> import pprint
> import logging
> from contenttype import getContentType
> 
> In Java what kind of statement is similar this?
> 
> thanks

http://docs.python.org/ref/import.html ("The first form of" and 
following, sixth paragraph)

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


Re: where has Stani's Py Editor gone?

2007-01-31 Thread Stargaming
John Pote schrieb:
> Hi everyone,
> 
> Been trying to get the latest version of Stani's Python Editor the last few 
> days. But I cannot get any response out of 'pythonide.stani.be'. Anyone know 
> what's happened?
> 
> Ta much,
> 
> John Pote 
> 
> 

http://developer.berlios.de/project/showfiles.php?group_id=4161
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random passwords generation (Python vs Perl) =)

2007-01-29 Thread Stargaming
NoName schrieb:
> Perl:
> @char=("A".."Z","a".."z",0..9);
> do{print join("",@char[map{rand @char}(1..8)])}while(<>);
> 
> !!generate passwords untill U press ctrl-z
> 
> 
> 
> Python (from CookBook):
> 
> from random import choice
> import string
> print ''.join([choice(string.letters+string.digits) for i in 
> range(1,8)])
> 
> !!generate password once :(
> 
> who can write this smaller or without 'import'?
> 

If you really want a hack, here it is:

while 1:print 
''.join(__import__('random').choice(__import__('string').letters+'1234567890') 
for x in xrange(8)),;n=raw_input()

This is a one-liner (though mail transmission may split it up), no 
import statements. If someone can come up with an even smaller version, 
feel free to post. :)

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


Re: howto redirect and extend help content ?

2007-01-28 Thread Stargaming
Stef Mientki schrieb:
> I'm making special versions of existing functions,
> and now I want the help-text of the newly created function to exists of
> 1. an extra line from my new function
> 2. all the help text from the old function
> 
> # the old function
> def triang(M,sym=1):
> """The M-point triangular window.<== old help text
> """
> 
> 
> # the new function
> def chunked_triang(M):
> """ Chunked version of "triang"  <== the extra line
> """
> 
>  >>> help(chunked_triang)
> # should give something like
> 
> chunked_triang(M)<== the new definition
> Chunked version of "triang"  <== the extra line
> The M-point triangular window.   <== old help text
> 
> Is that possible ?
> 
> 
> thanks,
> Stef Mientki

Don't you think your users can follow this easy reference theirselves?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: from future module!!!!!!!

2007-01-28 Thread Stargaming
lee schrieb:
> Guys whats the from future module in python?thanks
> 

http://docs.python.org/lib/module-future.html

It's a module with that "future changes" may be activated (currently 
such as the with_statement, what isn't in the "2.5 standard" so far).

BTW, it's not the 'from future' module, it's just the 'future' (or 
'__future__') module. The 'from' clause is a keyword in python used for 
imports in the module namespace.

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


  1   2   >