Re: Naming conventions for functions and methods

2014-07-08 Thread Arnaud Delobelle
On 8 July 2014 15:59, pyt...@bdurham.com wrote:

 Looking for your opinions on how you name your functions and methods. 
 Example: I have a function that hashes a file. I could name this function 
 hash_file() or file_hash(). The 1st naming convention sounds more natural, 
 the 2nd naming convention allows one to group related functions together by 
 the object being acted on. PEP-8 doesn't appear to offer guidance in this 
 area. Thoughts? Malcolm

If you want to group related functions together, I would suggest
putting them in a module, e.g. 'fileutils'.  I'd still go for hashfile
for the function name though.

-- 
Arnaud
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: socket programming

2013-05-06 Thread Arnaud Delobelle
On 6 May 2013 17:05, Chris Angelico ros...@gmail.com wrote:

 I've never used Twisted, so I can't say how good it is. All I know is
 that what I learned about socket programming in C on OS/2 is still
 valid on Windows and on Linux, and in every language I've ever used
 (bar JavaScript and ActionScript, which are deliberately sandboxed and
 thus don't have direct socket calls available). So take your pick: Go
 with Twisted, and bind yourself to a particular library, or go with
 BSD sockets, and do the work yourself. Like everything else in
 programming, it's a tradeoff.

OTOH Twisted can handle much more than socket programming. On the
third hand Twisted has its own learning curve as well...

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


Re: My gui

2013-04-24 Thread Arnaud Delobelle
On 24 April 2013 18:53, Chris “Kwpolska” Warrick kwpol...@gmail.com wrote:
 On Wed, Apr 24, 2013 at 7:08 PM, Daniel Kersgaard
 danielkersga...@gmail.com wrote:
 Today, being the last day of lectures at school, my instructor ran briefly 
 through Tkninter and GUIs. I'd been looking forward to this particular 
 lesson all semester, but when I got home and copied a sample program from my 
 textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  
 is the code from my program. I'm not sure if this is appropriate, but 
 suggestions are helpful.

 import tkinter
 import tkinter.messagebox

 class MyGui:
 def _init_(self):
 self.main_window = tkinter.Tk()

 self.top_frame = tkinter.Frame(self.main_window)
 self.bottom_frame = tkinter.Frame(self.main_window)

 self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a 
 distance in Kilometers: ')
 self.kilo_entry = tkinter.Entry(self.top_frame, width = 10)

 self.prompt_label.pack(side = 'left')
 self.kilo_entry.pack(side = 'left')

 self.calc_button = tkinter.Button(self.bottom_frame, text = 
 'Convert', command = self.convert)

 self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', 
 command = self.main_window.destroy)

 self.calc_button.pack(side = 'left')
 self.quit_button.pack(side = 'left')

 self.top_frame.pack()
 self.bottom_frame.pack()

 tkinter.mainloop()

 def convert(self):
 kilo = float(self.kilo_entry.get())

 miles = kilo * 0.6214

 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is 
 equal to ' + str(miles) + 'miles.')

 poop = MyGui()

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

 poop?  Seriously?  You aren’t serious about that copying, right?

 Your code seems to be missing a lot of important stuff.  You don’t
 inherit from tkinter.Frame.  Compare your program to the sample “Hello
 world!” program:

His class is not a frame, it's just a container for the tkinter code.
It's a bit unusual but it looks correct to me (apart from the single
underscores in __init__() as spotted by Ned Batchelder).

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


Re: name lookup failure using metaclasses with unittests

2013-04-11 Thread Arnaud Delobelle
On 11 April 2013 07:43, Ulrich Eckhardt ulrich.eckha...@dominolaser.com wrote:

 The second question that came up was if there is a way to keep a metaclass
 defined inside the class or if the only way is to provide it externally.

Yes, using metaclasses!  I wouldn't recommend it though.  Here's a
proof of concept:

class MyType(type):
def __new__(meta, name, bases, attrs):
try:
metaclass = attrs.pop('__metaclass__')
except KeyError:
return type.__new__(meta, name, bases, attrs)
else:
return metaclass(name, bases, attrs)

class MyObject(metaclass=MyType):
pass


 class Test(MyObject):
... def __metaclass__(name, bases, attrs):
... print(Test metaclass)
... return MyType(name, bases, attrs)
...
Test metaclass

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


Re: extract HTML table in a structured format

2013-04-10 Thread Arnaud Delobelle
On 10 April 2013 09:44, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,

 I wonder if there is a nice way to extract a whole HTML table and have the
 result in a nice structured format. What I want is to have the lifetime
 table at the bottom of this page:
 http://en.wikipedia.org/wiki/List_of_Ubuntu_releases (then figure out with a
 script until when my Ubuntu release is supported).

 I could do it with BeautifulSoup or lxml but is there a better way? There
 should be :)

Instead of parsing HTML, you could just parse the source of the page
(available via action=raw):

--
import urllib2

url = (
'http://en.wikipedia.org/w/index.php'
'?title=List_of_Ubuntu_releasesaction=raw'
)

source = urllib2.urlopen(url).read()

# Table rows are separated with the line |-
# Then there is a line starting with |
potential_rows = source.split(\n|-\n|)

rows = []

for row in potential_rows:
# Rows in the table start with a link (' [[ ... ]]')
if row.startswith( [[):
row = [item.strip() for item in row.split(\n|)]
rows.append(row)
--

 import pprint
 pprint.pprint(rows)
[['[[Warty Warthog|4.10]]',
  'Warty Warthog',
  '20 October 2004',
  'colspan=2 {{Version |o |30 April 2006}}',
  '2.6.8'],
 ['[[Hoary Hedgehog|5.04]]',
  'Hoary Hedgehog',
  '8 April 2005',
  'colspan=2 {{Version |o |31 October 2006}}',
  '2.6.10'],
 ['[[Breezy Badger|5.10]]',
  'Breezy Badger',
  '13 October 2005',
  'colspan=2 {{Version |o |13 April 2007}}',
  '2.6.12'],
 ['[[Ubuntu 6.06|6.06 LTS]]',
  'Dapper Drake',
  '1 June 2006',
  '{{Version |o | 14 July 2009}}',
  '{{Version |o | 1 June 2011}}',
  '2.6.15'],
 ['[[Ubuntu 6.10|6.10]]',
  'Edgy Eft',
  '26 October 2006',
  'colspan=2 {{Version |o | 25 April 2008}}',
  '2.6.17'],
  [...]
]


That should give you the info you need (until the wiki page changes too much!)

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


Re: Unicode issue with Python v3.3

2013-04-10 Thread Arnaud Delobelle
On 10 April 2013 09:28, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Tue, 09 Apr 2013 23:04:35 -0700, rusi wrote:
[...]
 I think it is quite unfair of you to mischaracterise the entire community
 response in this way. One person made a light-hearted, silly, unhelpful
 response. (As sarcasm, I'm afraid it missed the target.) Two people made
 good, sensible responses -- and you were not either of them.

Enough already with the thought police.

It was me who made the silly reply to the guy who was ranting about
everything being broken, giving us nothing to help in on, ending his
message in an edifying and in my judgement, largely rhetorical
Suggestions?.  So I gave him some silly suggestions (*not* intended
to be sarcasm), and I'm not apologising for it.  At least I'm not
presuming to take the moral high ground at every half-opportunity.

Recently I gave a very quick reply to someone who was wondering why he
couldn't get the docstring from his descriptor - I didn't have the
time to expand because two of my kids had jumped on my knees almost as
soon as I'd got on the computer.  I decided to post the reply anyway
as I thought it would give the OP something to get started on and
nobody else seemed to have replied so far - but I got remonstrated for
not being complete enough in my reply!  What is that about?

AFAIK, this is not Python Customer Service, but a place for people who
are interested in Python to discuss problems and *freely* exchange
thoughts about the language and its ecosystem.  Over the year I've
posted the occasional silly message but I think my record is
overwhelmingly that I've tried to be helpful, and when I've needed
some help myself, I've got some great advice.  My first question on
this list was answered by Alex Martelli and nowadays I get most
excellent and concise tips from Peter Otten - thanks, Peter! If
there's one person on this list I don't want to offend, it's you!

So here's to lots more good and bad humour on this list, and the
occasional slightly un-pc remark even!

Cheers,

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


Re: Python pdb bug, followed by bug in bugs.python.org

2013-04-09 Thread Arnaud Delobelle
On 9 April 2013 16:25,  donaldcal...@gmail.com wrote:
 I am I've developed an application in Python 3.3.1 (on an up-to-date 64-bit 
 Arch Linux system) and am attempting to use pdb to debug it. I am getting 
 incorrect stack traces. I've made up a little 10-line program that 
 illustrates the problem and I attempted to register on the bug-tracker site, 
 unsuccessfully, to file a bug report. I followed the link in the email and 
 got a broken form error message when I attempted to log in to the 
 bug-tracker. I then tried replying to the verification email, and got some 
 other form of brokenness in reply.

 Suggestions?

Python is well known for being a bug-free language, so from your
account I think that the most likely explanation is that you may have
acquired by accident some special mutant powers that introduce bugs
into the software that you come in contact with.  Therefore, my
suggestion is that you stay clear of any computer equipment from now
on, as you may cause hazards for yourself and others.

Others may be able to elaborate further.

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


Re: Splitting of string at an interval

2013-04-08 Thread Arnaud Delobelle
On 8 April 2013 14:21, Roy Smith r...@panix.com wrote:

 For a while, I was rabidly(*) into TDD (Test Driven Development).  The
 cycle I was using was, Write a specification of a behavior, write a
 (failing) test for that behavior, then write the least possible amount
 of code to make the test pass.  Lather, Rinse, Repeat, Ship

 The least possible part is important.  It makes sure the cycles stay
 short (ideally, just a few minutes), and that you don't write any code
 for which you don't have tests.

The least amount of code is often also not the best in terms of time
or space complexity.  Does this mean you have to write tests for time
and space complexity as well?  That's interesting, but I don't know of
tools to help do that (time complexity seems easy enough, but space
complexity seems tougher to me).

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


Re: Splitting of string at an interval

2013-04-08 Thread Arnaud Delobelle
On 8 April 2013 17:20, Chris Angelico ros...@gmail.com wrote:
 On Tue, Apr 9, 2013 at 1:37 AM, Roy Smith r...@panix.com wrote:
 I can't help point out, however, that if your initial implementation is to 
 have your code return a constant, it's pretty likely to be an optimum 
 solution in both time and space :-)

 Likely, but not certain.

 # 1
 def fifty_stars():
   return **

 # 2
 fifty_stars=lambda **50

There's a whole competition about writing the smallest program which
outputs the song 99 bottles of beer:

http://codegolf.com/99-bottles-of-beer

Cheers,

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


Re: How to do a Lispy-esque read?

2013-04-08 Thread Arnaud Delobelle
On 8 April 2013 08:45,  zeta.con...@gmail.com wrote:
 Suppose I want to read an object from some stream. How do I do it?

 For example, if the input stream contained the text:
 [1, # python should ignore this comment
 2]

 and I do a read on it, I should obtain the result
 [1, 2]

You might be interested in code.compile_command()
(http://docs.python.org/2/library/code.html)

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


Re: How to subclass a family

2013-04-08 Thread Arnaud Delobelle
On 8 April 2013 10:44, Antoon Pardon antoon.par...@rece.vub.ac.be wrote:
 Here is the idea. I have a number of classes with the same interface.
 Something like the following:

 class Foo1:
 def bar(self, ...):
 work
 def boo(self, ...):
 do something
 self.bar(...)

 What I want is the equivallent of:

 class Far1(Foo1):
 def boo(self, ...)
 do something different
 if whatever:
 self.bar(...)
 else:
 Foo1.boo(self, ...)

 Now of course I could subclass every class from the original family
 from Foo1 to Foon but that would mean a lot of duplicated code. Is
 there a way to reduce the use of duplicated code in such circumstances?


(Python 3)
--
class Foo1:
def bar(self):
print('Foo1.bar')
def boo(self, whatever):
print('Foo1.boo', whatever)
self.bar()

# class Foo2: ...(I'll let you define this one)

class DifferentBoo:
def boo(self, whatever):
print('DifferentBoo.boo', whatever)
if whatever:
self.bar()
else:
super().boo(whatever)

class Far1(DifferentBoo, Foo1): pass
# class Far2(DifferentBoo, Foo2): pass

--
 foo = Foo1()
 foo.bar()
Foo1.bar
 foo.boo(1)
Foo1.boo 1
Foo1.bar
 far = Far1()
 far.bar()
Foo1.bar
 far.boo(0)
DifferentBoo.boo 0
Foo1.boo 0
Foo1.bar
 far.boo(1)
DifferentBoo.boo 1
Foo1.bar

HTH,

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


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 10:50, Helmut Jarausch jarau...@skynet.be wrote:
 Hi,

 I'm trying to port a class to Python3.3 which contains

 class  Foo :
 
 def to_binary(self, *varargs, **keys):


 
 self.to_binary = new.instancemethod(to_binary, self, self.__class__)

`self` isn't bound in this lexical scope (the class scope).  Or is
your indentation incorrect?  However, if this statement was within the
`to_binary` method, then `to_binary` wouldn't be bound so I can't make
a reasonable guess.

 # Finally call it manually
 return apply(self.to_binary, varargs, keys)

[...]

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


Re: Newbie to python. Very newbie question

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 20:23, Ian Foote i...@feete.org wrote:
 I'm surprised no one has suggested:

 import math
 sum( x*x for x in range(1, int(math.sqrt(100)), 2))

Yeah! And I'm surprised no one came up with:

 from itertools import count, takewhile
 sum(takewhile((100).__gt__, filter((2).__rmod__, map((2).__rpow__, 
 count(1)
165

:)

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


Re: __doc__ string for getset members

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 19:02, Nick Gnedin ngne...@gmail.com wrote:

 Folks,

 I am writing an extension where I follow the guide on the web
 (http://docs.python.org/3.3/extending/newtypes.html#generic-attribute-management).
 I have an object declared,

 struct Object
 {
 PyObject_HEAD
 };

 and a member set through tp_getset mechanism,

 PyGetSetDef ObjectGetSet[] =
 {
 {mem, (getter)MemGet, (setter)MemSet, mem-doc-string, NULL},
 {NULL}  /* Sentinel */
 };

 My question is - how do I access the doc string mem-doc-string supplied in
 the PyGetSetDef structure? If I type

 print(obj.mem.__doc__)

 then the __doc__ string for the result of a call to MemGet(...) is printed,
 not the doc string supplied in the PyGetSetDef structure.


That's not how Python works.  You won't be able to get the docstring
of a descriptor this way.  You need to do it from the class.  The
behaviour you observe is normal and cannot be overriden.

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


Re: __doc__ string for getset members

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 21:38, Nick Gnedin ngne...@gmail.com wrote:

 Arnaud,

 Thanks for the answer. I understand that I cannot access the docstring as an
 attribute of a getter, but what did you mean when you said You need to do
 it from the class? I am still confused - is there a way to get that
 docstring or not?

 Nick


Please reply on-list

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


Re: is operator versus id() function

2013-04-05 Thread Arnaud Delobelle
On 5 April 2013 14:49, Candide Dandide c.cand...@laposte.net wrote:
 Until now, I was quite sure that the is operator acts the same as the id 
 builtin function, or, to be more formal, that o1 is o2 to be exactly 
 equivalent to id(o1) == id(o2). This equivalence is reported in many books, 
 for instance Martelli's Python in a Nutshell.

 But with the following code, I'm not still sure the equivalence above is 
 correct. Here's the code :


 #
 class A(object):
 def f(self):
 print A

 a=A()
 print id(A.f) == id(a.f), A.f is a.f
 #


 outputing:

 True False

 So, could someone please explain what exactly the is operator returns ? The 
 official doc says :

 The ‘is‘ operator compares the identity of two objects; the id() function 
 returns an integer representing its identity (currently implemented as its 
 address).

And the doc is right!

 Af = A.f
 af = a.f
 print id(Af) == id(af), Af is af
False False

You've fallen victim to the fact that CPython is very quick to collect
garbage.  More precisely, when Python interprets `id(A.f) == id(a.f)`,
it does the following:

1. Create a new unbound method (A.f)
2. Calculate its id
3. Now the refcount of A.f is down to 0, so it's garbage collected
4 Create a new bound method (a.f) **and very probably use the same
memory slot as that of A.f**
5 Calculate its id
6 ...

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


Re: extending class static members and inheritance

2013-04-02 Thread Arnaud Delobelle
On 2 April 2013 14:27, Fabian PyDEV py...@hotmail.com wrote:
 Hi All,

 I have a question.

 Let says I have the following two classes:

 class Base(object):
 __mylist__ = [value1, value2]

 def somemethod(self):
 pass


 class Derived(Base):
 __mylist__ = [value3, value4]

 def anothermethod(self):
 pass




 what I would like to accomplish is that the class Derived has the member 
 __mylist__ extended or merged as [value1, value2, value3, value4].

 Is there anyway I could accomplish this?

 I was thinking on accomplishing this as follows:


 class Derived(Base):
 __mylist__ = Base.__mylist__ + [value3, value4]

 def anothermethod(self):
 pass


 Is there a better way? Perhaps a decorator?

class Base(object):

mybits = [value1, value2]

@classmethod
def mylist(cls):
return sum((getattr(p, 'mybits', []) for p in cls.mro()[::-1]), 
[])


class Derived(Base):

mybits = [value3, value4]


class FurtherDerived(Derived):

mybits = [value5]


 Derived.mylist()
['value1', 'value2', 'value3', 'value4']
 FurtherDerived.mylist()
['value1', 'value2', 'value3', 'value4', 'value5']

HTH

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


Re: Sudoku

2013-03-31 Thread Arnaud Delobelle
On 31 March 2013 23:34, Dave Angel da...@davea.name wrote:
[...]  With my Python
 2.7.2, exit(something) with something being a string prints the string and
 then exits.  Nowhere have I seen that documented, and I thought it either
 took an int or nothing.

It is documented, just not exactly where you'd expect it (exit is a
constant, not a function):


http://docs.python.org/2/library/constants.html#constants-added-by-the-site-module

As for the behaviour when you pass a string, it's documented here:

http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit

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


Re: Doing both regex match and assignment within a If loop?

2013-03-29 Thread Arnaud Delobelle
On Friday, 29 March 2013, Alain Ketterlin wrote:

 Victor Hooi victorh...@gmail.com javascript:; writes:

  expression1 = re.compile(r'')
  expression2 = re.compile(r'')
 [...]

 Just a quick remark: regular expressions are pretty powerful at
 representing alternatives. You could just stick everything inside a
 single re, as in '...|...'


Then use the returned match to check which alternative was recognized
 (make sure you have at least one group in each alternative).


Yes, and for extra ease/clarity you can name these alternatives (
'(?Pnamepattern)').  Then you can do

if m.group('case1'):
...
elif m.group('case2'):
   ...

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


Re: Splitting a list into even size chunks in python?

2013-03-27 Thread Arnaud Delobelle
On 27 March 2013 08:27, Peter Otten __pete...@web.de wrote:

 Look again, for the grouper() recipe. For lists you can also use slicing:

 items
 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
 n = 3
 [items[start:start+n] for start in range(0, len(items), n)]
 [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Another way with islice (so it works for any iterable):

 from itertools import islice
 items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
 n = 3
 list(iter(lambda i=iter(items):list(islice(i, n)),[]))
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Not too readable though :)

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


Re: Decorator help

2013-03-27 Thread Arnaud Delobelle
On 27 March 2013 19:49, Joseph L. Casale jcas...@activenetwerx.com wrote:
 I have a class which sets up some class vars, then several methods that are 
 passed in data
 and do work referencing the class vars.


 I want to decorate these methods, the decorator needs access to the class 
 vars, so I thought
 about making the decorator its own class and allowing it to accept args.


 I was hoping to do all the work on in_data from within the decorator, which 
 requires access
 to several MyClass vars. Not clear on the syntax/usage with this approach 
 here, any guidance
 would be greatly appreciated!


 Class MyDecorator(object):

 def __init__(self, arg1, arg2):
 self.arg1 = arg1
 self.arg2 = arg2
 ...


 Class MyClass(object):
 def __init__(self):
 self.var_a = 
 
 @MyDecorator(...)
 def meth_one(self, in_data):
 ...

I don't really understand what you are trying to do.  It would be
easier if you had some code that tried to do something (even if it
doesn't quite work).

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


Re: how do you make a loop run in reverse?

2013-03-27 Thread Arnaud Delobelle
On 26 March 2013 23:59,  rahulredd...@hotmail.com wrote:
 So i have a set of for loops that create this :

 ***
 ***   ***   ***   ***   ***   ***   ***
 ***   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   ***
 ***

  *
 ***
*
   ***
  *

 but i want to nest all the loops under one BIG loop that'll run in reverse to 
 make this:

 ***
 ***   ***   ***   ***   ***   ***   ***
 ***   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   ***
 ***

  *
 ***
*
   ***
  *
   ***
*
 ***
  *
 ***
***   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   ***
 ***   ***   ***   ***   ***   ***   ***
 ***   ***   ***   ***   ***   ***   ***
 ***

 Is this possible?

Let's have a look at a simple example.  Imagine you have a function:

 def print_pretty_pattern():
...for i in range(1, 6):
...   print '*'*i
...
 print_pretty_pattern()
*
**
***

*

You can't reverse the pattern because it's not data so you need to
turn it into data:

 def generate_pretty_pattern():
... for i in range(1, 6):
... yield '*'*i

It's the same as above, but the 'print' statement has been replace
with a 'yield' statement, making the function into a generator
function, so that when you call it you get an iterable of all the
lines.  You can now make a function to print a pattern:

 def print_pattern(lines):
... for line in lines:
... print line

Or if you want to be concise:

 def print_pattern(lines):
... print \n.join(lines)

So you can print any pattern:

 print_pattern(generate_pretty_pattern())
*
**
***

*

So now you can write another generator that makes the mirror pattern
of a given pattern:

 def mirror_pattern(pattern):
... lines = []
... for line in pattern:
... yield line
... lines.append(line)
... if lines:
... lines.pop() # don't repeat the last line
... for line in reversed(lines):
... yield line
...
 print_pattern(mirror_pattern(generate_pretty_pattern()))
*
**
***

*

***
**
*

Here's another example:

 print_pattern(mirror_pattern(''.join(mirror_pattern(*.ljust(i).rjust(15)))
  for i in range(1,16,2)))
  *
*   *
  *   *
*   *
  *   *
*   *
  *   *
*   *
  *   *
*   *
  *   *
*   *
  *   *
*   *
  *

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


Re: Processing user input as it's entered

2013-03-26 Thread Arnaud Delobelle
On 26 March 2013 10:07, Sven sven...@gmail.com wrote:
 Hello,

 Is there a way (ideally cross platform but a *nix OS solution would be
 great) to process user input as they type?
 What I aim to achieve is to count the number of characters a user has
 entered and display it while they are typing. The entered text will also
 need to be captured once the user has finished typing.

 This is a gui-less CLI tool for python 2.7

 I've seen some information on tty.setraw but I'm not sure how you'd go about
 wiring that up.

Can you use curses (http://docs.python.org/2/library/curses.html)

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


tkinter: invisible PanedWindow sashes on OS X

2013-03-21 Thread Arnaud Delobelle
Hi Python List,

I'm trying to use PanedWindow on OS X (10.8.3).  I've started with the
effbot docs example (http://effbot.org/tkinterbook/panedwindow.htm),
namely:

--
from Tkinter import *

m = PanedWindow(orient=VERTICAL)
m.pack(fill=BOTH, expand=1)

top = Label(m, text=top pane)
m.add(top)

bottom = Label(m, text=bottom pane)
m.add(bottom)

mainloop()
--

I can see two panes alright, but no handle to resize them (or 'sash'
as they seem to be called in tkinter).  Is there something else that I
should be doing?

TIA,

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


Re: tkinter: invisible PanedWindow sashes on OS X

2013-03-21 Thread Arnaud Delobelle
On 21 March 2013 18:42, Christian Gollwitzer aurio...@gmx.de wrote:
 Am 21.03.13 15:37, schrieb Arnaud Delobelle:

 Hi Python List,

 I'm trying to use PanedWindow on OS X (10.8.3).  I've started with the
 effbot docs example (http://effbot.org/tkinterbook/panedwindow.htm),
 namely:

 --
 from Tkinter import *

 m = PanedWindow(orient=VERTICAL)
 m.pack(fill=BOTH, expand=1)

 top = Label(m, text=top pane)
 m.add(top)

 bottom = Label(m, text=bottom pane)
 m.add(bottom)

 mainloop()
 --

 I can see two panes alright, but no handle to resize them (or 'sash'
 as they seem to be called in tkinter).  Is there something else that I
 should be doing?


 This is, unfortunately, the platform standard on both OSX and Windows7. You
 can still resize the windows: Just grab the space between the two labels.
 There should be at least a cursor change.

I cannot effect a cursor change with the example above.

 With you example it doesn't work particularly well, because the labels are
 small and have no visible border. Try using e.g. a text widget instead (or
 maybe relief=SUNKEN)

If I use text widgets for the top and bottom panes, then I can get a
resize cursor and I am able to drag the 'sash' up and down.  That's
good enough for me to get started.  Thanks for the suggestion,

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


Retrieving an object from a set

2013-01-25 Thread Arnaud Delobelle
Dear Pythoneers,

I've got a seemingly simple problem, but for which I cannot find a
simple solution.

I have a set of objects (say S) containing an object which is equal to
a given object (say x). So

x in S

is true.  So there is an object y in S which is equal to x.  My
problem is how to retrieve y, without going through the whole set.
Here is a simple illustration with tuples (my actual scenario is not
with tuples but with a custom class):

 y = (1, 2, 3) # This is the 'hidden object'
 S = set([y] + range(1))
 x = (1, 2, 3)
 x in S
True
 x is y
False

I haven't found y.  It's a very simple problem, and this is the
simplest solution I can think of:

class FindEqual(object):
def __init__(self, obj):
self.obj = obj
def __hash__(self):
return hash(self.obj)
def __eq__(self, other):
equal = self.obj == other
if equal:
self.lastequal = other
return equal

 yfinder = FindEqual(x)
 yfinder in S
True
 yfinder.lastequal is y
True

I've found y!  I'm not happy with this as it really is a trick.  Is
there a cleaner solution?

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


Re: Obnoxious postings from Google Groups

2012-10-31 Thread Arnaud Delobelle
On 31 October 2012 22:33, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
[...]
 I don't killfile merely for posting from Gmail

And we are humbly grateful.

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


Re: sort order for strings of digits

2012-10-31 Thread Arnaud Delobelle
On 31 October 2012 23:09, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 The trick is to take each string and split it into a leading number and a
 trailing alphanumeric string. Either part may be empty. Here's a pure
 Python solution:

 from sys import maxsize  # use maxint in Python 2
 def split(s):
 for i, c in enumerate(s):
 if not c.isdigit():
 break
 else:  # aligned with the FOR, not the IF
 return (int(s), '')
 return (int(s[:i] or maxsize), s[i:])

 Now sort using this as a key function:

 py L = ['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
 py sorted(L, key=split)
 ['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']

You don't actually need to split the string, it's enough to return a
pair consisting of the number of leading digits followed by the string
as the key. Here's an implementation using takewhile:

 from itertools import takewhile
 def prefix(s):
... return sum(1 for c in takewhile(str.isdigit, s)) or 1000, s
...
 L = ['9', '1000', 'abc2', '55', '1', 'abc', '55a', '1a']
 sorted(L, key=prefix)
['1', '1a', '9', '55', '55a', '1000', 'abc', 'abc2']

Here's why it works:

 map(prefix, L)
[(1, '9'), (4, '1000'), (1000, 'abc2'), (2, '55'), (1, '1'), (1000,
'abc'), (2, '55a'), (1, '1a')]

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


Re: Compairing filenames in a list

2012-09-30 Thread Arnaud Delobelle
On 30 September 2012 02:27, Kevin Anthony kevin.s.anth...@gmail.com wrote:
 I have a list of filenames, and i need to find files with the same name,
 different extensions, and split that into tuples.  does anyone have any
 suggestions on an easy way to do this that isn't O(n^2)?

 import os, itertools
 filenames = [foo.png, bar.csv, foo.html, bar.py]
 dict((key, tuple(val)) for key, val in itertools.groupby(sorted(filenames), 
 lambda f: os.path.splitext(f)[0]))
{'foo': ('foo.html', 'foo.png'), 'bar': ('bar.csv', 'bar.py')}

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


running Lua in Python

2012-09-02 Thread Arnaud Delobelle
Hi all,

I'm looking for a way to run Lua scripts in Python, and also send and
receive data between the two.  Something like lunatic-python [1] would
be ideal.  However, so far I haven't been able to build it on the
machines it's supposed to run on (macs with OS X Lion) and it seems to
be dormant.

My requirements are stock OS X Python (which is 2.7) and Lua 5.2.  I'm
looking for either a way to make lunatic-python work or another tool
that would do the job.

Thanks in advance.

-- 
Arnaud

[1] http://labix.org/lunatic-python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running Lua in Python

2012-09-02 Thread Arnaud Delobelle
On 2 September 2012 10:39, Alec Taylor alec.tayl...@gmail.com wrote:
 Or you can use a module made for this task:

 http://labix.org/lunatic-python

As I said in my original message, I couldn't get this to work.

 http://pypi.python.org/pypi/lupa

I'll check this out, thanks.

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


Re: running Lua in Python

2012-09-02 Thread Arnaud Delobelle
On 2 September 2012 10:49, Arnaud Delobelle arno...@gmail.com wrote:
 On 2 September 2012 10:39, Alec Taylor alec.tayl...@gmail.com wrote:
 http://pypi.python.org/pypi/lupa

 I'll check this out, thanks.

Mmh it seems to be lua 5.1 and more importantly it seems to require a
custom build of Python, which I don't want.  So it seems the simplest
solution is to run Lua in a child process...

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


Re: running Lua in Python

2012-09-02 Thread Arnaud Delobelle
On 2 September 2012 19:42, Stefan Behnel stefan...@behnel.de wrote:
 Arnaud Delobelle, 02.09.2012 20:34:
 On 2 September 2012 10:49, Arnaud Delobelle wrote:
 On 2 September 2012 10:39, Alec Taylor wrote:
 http://pypi.python.org/pypi/lupa

 I'll check this out, thanks.

 Mmh it seems to be lua 5.1 and more importantly it seems to require a
 custom build of Python, which I don't want.

 I have no idea why you say that, for neither of the two.

* For the custom build of Python on OS X, this blog post:


http://t-p-j.blogspot.co.uk/2010/11/lupa-on-os-x-with-macports-python-26.html

which is actually linked to in lupa's own INSTALL.rst file

* For Lua 5.1, the official LuaJIT page:

http://luajit.org/luajit.html

where I quote:


LuaJIT implements the full set of language features defined by Lua 5.1.


Of course I'd be glad to be proved wrong on both counts.

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


Re: Tkinter bug in Entry widgets on OS X

2012-09-01 Thread Arnaud Delobelle
On Friday, 31 August 2012, Dennis Lee Bieber wrote:

 On Fri, 31 Aug 2012 15:41:01 GMT, Alister 
 alister.w...@ntlworld.comjavascript:;
 
 declaimed the following in gmane.comp.python.general:

  I agree that it is unexpected in a single line entry box but isn't the
 1st
  rule of user interface design to assume the user is a moron  will do
  things they are not supposed to do?
 
  Therefore invalid inputs should be handled gracefully (not just insert
  random characters) which is what I think the original poster is
  suggesting.

 To which I'd suggest the programmer (vs the user), probably needs
 to
 code some sort of per-character validation check... After all, there may
 be situations where accepting pretty much any key-code is desired, and
 if the widget filters characters before they get to the programmer level
 that becomes impossible.


It would be good if I could intercept the key press event and cancel its
action on the Entry widget.  It's easy to intercept the key event, but I
haven't found out how to prevent the funny characters from being inserted
into the Entry widget input area.  I've struggled to find good tkinter docs
on the web.


 caveat -- I've only written one simple form using Tkinter, so what
 do I know...


It's about as much as I've done!

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


Re: Tkinter bug in Entry widgets on OS X

2012-09-01 Thread Arnaud Delobelle
On 1 September 2012 11:30, Peter Otten __pete...@web.de wrote:
 Arnaud Delobelle wrote:
 It would be good if I could intercept the key press event and cancel its
 action on the Entry widget.  It's easy to intercept the key event, but I
 haven't found out how to prevent the funny characters from being inserted
 into the Entry widget input area.

 Untested as I have no Mac:

 import Tkinter as tk

 def suppress(event):
 if event.keycode in {111, 116}:
 print ignoring, event.keycode
 return break
 print event.keycode, accepted

 root = tk.Tk()
 entry = tk.Entry(root)
 entry.bind(Key, suppress)
 entry.pack()

 root.mainloop()

This works fine!

return break is the piece of knowledge that I was missing. Thanks a
lot!  In fact I lied a bit in my original message - I do use the UP
and DOWN arrows on one Entry widget for navigating its command
history. To do this I was binding the Up and Down events to a
function, which simply has to return break to work around the bug.
On other Entry widgets, I just bind Up and Down to a suppress
function which simply returns break.

 I've struggled to find good tkinter
 docs on the web.

 For my (basic) needs I keep coming back to

 http://infohost.nmt.edu/tcc/help/pubs/tkinter/

Thanks for the link.  I was using the docs on effbot which are nice
but probably incomplete (and old).

I guess I should flag up this bug but I don't even know if it's a
Python or Tk problem and have little time or expertise to investigate.

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


Tkinter bug in Entry widgets on OS X

2012-08-31 Thread Arnaud Delobelle
Hi all,

I'm writing a small GUI on OS X (v. 10.7.4) using Tkinter.  I'm using
stock Python.  It mostly works fine but there is a bug in Entry
widgets: if and Entry widget has focus and I press the UP arrow, a
\uf700 gets inserted in the widget.  If I press the DOWN arrow, a
\uf701 gets inserted.

I'm very inexperienced with Tkinter (I've never used it before).  All
I'm looking for is a workaround, i.e. a way to somehow suppress that
output.

Thanks in advance,

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


Re: Tkinter bug in Entry widgets on OS X

2012-08-31 Thread Arnaud Delobelle
On 31 August 2012 15:25, Kevin Walzer k...@codebykevin.com wrote:
 On 8/31/12 6:18 AM, Arnaud Delobelle wrote:

 I'm very inexperienced with Tkinter (I've never used it before).  All
 I'm looking for is a workaround, i.e. a way to somehow suppress that
 output.


 What are you trying to do? Navigate the focus to another widget? You should
 use the tab bar for that, not the arrow key. The entry widget is a
 single-line widget, and doesn't have up/down as the text widget does.

I'm not trying to do anything.  When a user presses the UP or DOWN
arrow, then a strange character is inserted in the Entry box.  I'd
rather nothing happened.

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


Re: Tkinter bug in Entry widgets on OS X

2012-08-31 Thread Arnaud Delobelle
On 31 August 2012 16:41, Alister alister.w...@ntlworld.com wrote:
 On Fri, 31 Aug 2012 11:21:14 -0400, Kevin Walzer wrote:

 On 8/31/12 11:18 AM, Arnaud Delobelle wrote:


 I'm not trying to do anything.  When a user presses the UP or DOWN
 arrow, then a strange character is inserted in the Entry box.  I'd
 rather nothing happened.

 Why is the user doing that? If they are trying to navigate to a
 different part of the interface, they need to use the tab key, not the
 arrow key. It's not a multi-line text widget and shouldn't be expected
 to work like one.

So you make software that only behaves well when the user does what
they're supposed to do?

 I agree that it is unexpected in a single line entry box but isn't the 1st
 rule of user interface design to assume the user is a moron  will do
 things they are not supposed to do?

 Therefore invalid inputs should be handled gracefully (not just insert
 random characters) which is what I think the original poster is
 suggesting.

Indeed.

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


Re: looking for a neat solution to a nested loop problem

2012-08-06 Thread Arnaud Delobelle
On 6 August 2012 16:52, Tom P werot...@freent.dd wrote:
 consider a nested loop algorithm -

 for i in range(100):
 for j in range(100):
 do_something(i,j)

 Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some
 other values i = N and j = M, and I want to iterate through all 10,000
 values in sequence - is there a neat python-like way to this? I realize I
 can do things like use a variable for k in range(1): and then derive
 values for i and j from k, but I'm wondering if there's something less
 clunky.

For example:

for i in range(100):
for j in range(100):
do_something((i + N)%100, (j + N)%100)

Cheers,

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


Re: OT: Text editors

2012-07-29 Thread Arnaud Delobelle
On 29 July 2012 06:36, rusi rustompm...@gmail.com wrote:
 Just curious about your emacs+python usage.
 Do you use the emacs builtin python mode or the separate python-mode?
 Do you use pdb?
 Any other special setups?

One thing that I find very useful is to configure flymake to use
pyflakes.  Very useful to get feedback on unused imports / unused
variables / undefined variables (which means you spot typos on
variable names straight away).

For instructions, see e.g. http://www.plope.com/Members/chrism/flymake-mode

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


Re: Generating valid identifiers

2012-07-26 Thread Arnaud Delobelle
On 26 July 2012 13:26, Laszlo Nagy gand...@shopzeus.com wrote:
[...]
 I do not want this program to generate very long identifiers. It would
 increase SQL parsing time, and don't look good. Let's just say that the
 limit should be 32 characters. But I also want to recognize the identifiers
 when I look at their modified/truncated names.
[...]
 print repr(Connection.makename(group1_group2_group3_some_field_name))
 'group1_group2_group3_some_fiel$AyQVQUXoyf'

 len('group1_group2_group3_some_fiel$AyQVQUXoyf')
41

You've exceeded 32 characters!  Perhaps you could change:

return basename[:30]+$+tail

to:

return basename[:21]+$+tail

But then you'd get something like this for your long identifier:

group1_group2_group3_$AyQVQUXoyf

which seems to miss out on a crucial bit: namely the field name.

Also it's hard to imagine a way to keep things readable when we don't
know what the original identifiers look like :)

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


Re: Encapsulation, inheritance and polymorphism

2012-07-18 Thread Arnaud Delobelle
On 17 July 2012 13:01, Lipska the Kat lip...@lipskathekat.com wrote:

 Well I've set myself a task.
 I have a text file containing a list of stock items
 each line contains the number in stock followed by a tab followed by the
 name of the item. I need to implement something that reads in the text file
 and outputs the stock list in ascending or descending order of quantity.

 Please note I am NOT asking for solutions.

 In bash this is laughably trivial

 sort -nr $1 | head -${2:-10}

Here's a Python translation that won't help :)

from sys import argv
print ''.join(sorted(open(argv[1]), key=lambda l:
-int(l.split('\t')[0]))[:10 if len(argv)  3 else int(argv[2])])

Who said Python was readabl'y yours,

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


Re: Problem with ImapLib and subject in French

2012-06-18 Thread Arnaud Delobelle
On 18 June 2012 12:31, Valentin Mercier merciervs...@gmail.com wrote:
 Hi,

 I'm trying to search some mails with SUBJECT criteria, but the problem is
 the encoding, I'm trying to search french terms (impalib and python V2.7)

 I've tried few things, but I think the encoding is the problem, in my mail
 header I have something like this:

  =?iso-8859-1?Q?Job:_Full_Backup_Les_Gr=E8ves_du_Lac)_?=

 I need to search unseen mail with the FROM and the SUBJECT criteria. I take
 those two in parameters in my python script and the second contain special
 caracters like é or è, so I encode the string like this:

              temp = header_encode(unicode('Les grèves','utf-8'),
 charset='iso-8859-1')

 And the string is exactly the same as the header:

 =?iso-8859-1?q?Full_Backup_Les_Gr=E8ves?=

 But the search function doesn't find my email, and I don't know why, even if
 I try with the entire string of the subject.

Can you post the code that doesn't work?  It's hard to debug search
function doesn't find my email.  It would be easier to debug actual
code (note: I'm not a user of imaplib so I'm not promising anything :)

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


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-10 Thread Arnaud Delobelle
On 10 June 2012 07:16, rusi rustompm...@gmail.com wrote:

 This is worth a read in this context: http://osteele.com/archives/2004/11/ides

Interesting! I definitely fall nicely at one extreme of this
dichotomy.  Every time I've tried to use an IDE, it's made me feel
inadequate and I've quickly retreated to my comfort zone (emacs +
xterm).  I felt inadequate because I felt like the IDE was hindering
me rather than helping me.  All I ask from the program that I use to
write code is:

* syntax highlighting
* sensible auto-indenting
* as little reliance on the mouse as possible
* emacs key bindings :)

This article makes me feel more positive about my inability to feel
comfortable in an IDE.  Thanks for the link!

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


Re: python3 raw strings and \u escapes

2012-05-30 Thread Arnaud Delobelle
On 30 May 2012 12:54, Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa...@spamschutz.glglgl.de
wrote:
 There is a 3rd one: use   r'[ ' + '\u3000' + ']'. Not very nice to read, but
 should do the trick...

You could even take advantage of string literal concatenation:)

r'[' '\u3000' r']'

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


Re: Help doing it the python way

2012-05-29 Thread Arnaud Delobelle
On 24 May 2012 21:22, Scott Siegler scott.sieg...@gmail.com wrote:
 Hello,

 I am an experienced programmer but a beginner to python.  As such, I can 
 figure out a way to code most algorithms using more C style syntax.

 I am doing something now that I am sure is a more python way but i can't 
 quite get it right.  I was hoping someone might help.

 So I have a list of grid coordinates (x, y).  From that list, I want to 
 create a new list that for each coordinate, I add the coordinate just above 
 and just below (x,y+1) and (x,y-1)

 right now I am using a for loop to go through all the coordinates and then 
 separate append statements to add the top and bottom.

 is there a way to do something like: [(x,y-1), (x,y+1) for zzz in coord_list] 
 or something along those lines?

AFAICS nobody's suggested yet the simple yet effective:

new_list = [(x, y + i) for x, y in coord_list for i in (-1, 1)]

IMHO these list comprehensions are often overlooked too quickly in
favour of itertools (in this case chain.from_iterable).

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


Re: How to generate only rotationally-unique permutations?

2012-05-19 Thread Arnaud Delobelle
On 19 May 2012 06:23, John O'Hagan resea...@johnohagan.com wrote:
 To revisit a question which I'm sure none of you remember from when I posted 
 it
 a year or so ago - there were no takers at the time - I'd like to try again 
 with
 a more concise statement of the problem:

 How to generate only the distinct permutations of a sequence which are not
 rotationally equivalent to any others? More precisely, to generate only the 
 most
 left-packed of each group of rotationally equivalent permutations, such that
 for each permutation p:

This makes me think of Lyndon words.  A Lyndon word is a word which is
the only lexicographical minimum of all its rotations.  There is a
very effective way of generating Lyndon words of length = n.  It may
be possible to adapt it to what you want (obviously as Lyndon words
are aperiodic you'd have to generate Lyndon word of length d | n when
suitable).

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


Re: Carbon Event Manager (Carbon.CarbonEvt module) - working?

2012-05-15 Thread Arnaud Delobelle
On 15 May 2012 20:55, Ned Deily n...@acm.org wrote:
 In article
 c4dc4a8f-52cc-4447-b199-dafcc296e...@e20g2000vbm.googlegroups.com,
  msmucr msm...@gmail.com wrote:
 i would like to ask you for some information regarding Carbon Event
 Manager ( Carbon.CarbonEvt ) library in Python.
 I need to recieve and work with few Carbon events in my program. I've
 followed some examples on PyObjC site, but wasn't successful. I know,
 that both Carbon library and this Python module is deprecated, but
 frankly i didn't find any usable alternative except of writing of
 something from scratch..
 I ended on basic import of required objects from Carbon.CarbonEvt
 module -
 like from Carbon.CarbonEvt import RegisterEventHotKey
 I tried it in Python 2.7.1 (standard distribution in OS X 10.7 Lion)
 and Python 2.6.1 (standard Apple distribution in OS X 10.6).
 Do I have something wrong or is it simply broken and unmaintained now?

 You may want to ask OS X specific questions on the macpython mailing
 list (http://www.python.org/community/sigs/current/pythonmac-sig/). The
 main reason that these modules are deprecated (and have been removed in
 Python 3) is because they depend on obsolete APIs in OS X that are only
 available in 32-bit versions.  Apple has made it clear that they will
 not be made available as 64-bit and will eventually go away.  You should
 try to find ways not to use the Carbon model in your applications.  That
 said, you can use these modules, even with the Apple-supplied Pythons in
 OS X 10.6 and 10.7, if you force Python to run in 32-bit-mode.  For
 those Apple-supplied Pythons, see the Apple man page (man 1 python) for
 system Python specific ways to force 32-bit mode persistently.  Another
 way that should work for any OS X universal Python 2.7.x:

    arch -i386 python2.7

This is what I have with system python 2.6:

$ cat ~/bin/python_32
#! /bin/bash
export VERSIONER_PYTHON_PREFER_32_BIT=yes
/usr/bin/python $@

I use it for wxpython, which only seems to work in 32 bit mode.  I
can't remember where I found it.  Maybe I read the man page?

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


Re: Good data structure for finding date intervals including a given date

2012-05-13 Thread Arnaud Delobelle
On 13 May 2012 13:29, Alec Taylor alec.tayl...@gmail.com wrote:
 There is an ordered dict type since Python 3.1[1] and Python 2.7.3[2].

I don't think that'll help the OP.  Python's OrderedDict keeps track
of the order in which the keys were inserted into the dictionary (a
bit like a list), it doesn't keep the keys sorted.

 If you are looking for the best possible self-sorting structure for
 searching, then perhaps you are looking for what's outlined in the
 2002 article by Han  Thorup: Integer Sorting in O(n sqrt(log log n))
 Expected Time and Linear Space[3].

I can't access it but it seems to me it's not about self sorted data
structures, which is what the OP is looking for.

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


Re: return respective values when mutiple keys are passed in dictionary

2012-05-07 Thread Arnaud Delobelle
On 7 May 2012 12:31, Nikhil Verma varma.nikhi...@gmail.com wrote:
 HI All

 I was clearing my concepts on dictionary and stuck in this problem.
 I have a dictionary which i have formed by using zip function on two list so
 that one list (which i have hardcoded) becomes the keys and the other list
 becomes its values.

 Now i want to know how can i get the values of keys at once if i pass the
 keys in a dictionary.

 Let say I have a dictionary

 mydict = {'a':'apple' , 'b':'boy' ,'c' : 'cat', 'd':'duck','e':'egg'}

 Now if i do :-

 mydict.get('a')
 'apple'

mydict['a'] is the usual way to get the value associated with a key.
The difference is that it will throw an exception if the key doesn't
exist, which is most of the time the sanest thing to do.

 What i want is some i pass keys in get and in return i should have all the
 values of those keys which i pass.

 ##
 mydict.get('a','b','c')    ###demo for what i want
 'apple','boy','cat'    ### Output i want
 #

1. You can use a list comprehension

 [mydict[k] for k in 'a', 'b', 'c']
['apple', 'boy', 'cat']

2. You can use map (for python 3.X, you need to wrap this in list(...))

 map(mydict.__getitem__, ['a', 'b', 'c'])
['apple', 'boy', 'cat']

3. You can use operator.itemgetter

 from operator import itemgetter
 itemgetter('a', 'b', 'c')(mydict)
('apple', 'boy', 'cat')

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


Re: syntax for code blocks

2012-05-01 Thread Arnaud Delobelle
(sent from my phone)
On May 1, 2012 6:42 PM, Jerry Hill malaclyp...@gmail.com wrote:

 On Tue, May 1, 2012 at 1:07 PM, Kiuhnm
 kiuhnm03.4t.yahoo...@mail.python.org wrote:
  If you had read the module's docstring you would know that the public
  version uses

 Are you aware that you've never posted a link to your module, nor it's
 docstrings?  Are you also aware that your module is essentially
 unfindable on google?  Certainly nothing on the first two pages of
 google results for 'python codeblocks' jumps out at me as a python
 module of that name.

 Perhaps you would have better luck if you either post the actual code
 you want people to critique, or posted a link to that code.

He did post a link to a blog post describing his module and also a link to
the actual code, on bitbucket IIRC.

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


Re: confusing doc: mutable and hashable

2012-04-29 Thread Arnaud Delobelle
(sent from my phone)
On Apr 28, 2012 7:36 PM, Chris Rebert c...@rebertia.com wrote:
 Correct. Pedantically, you can define __hash__() on mutable objects;
 it's just not very useful or sensible, so people generally don't.

I find it's fine to define __hash__ on mutable objects as long as __eq__
only relies on immutable state (and then so should __hash__ of course).  A
typical example would be an object that does some caching.

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


Re: why () is () and [] is [] work in other way?

2012-04-26 Thread Arnaud Delobelle
On 26 April 2012 12:42, Adam Skutt ask...@gmail.com wrote:
 On Apr 26, 5:10 am, Steven D'Aprano steve
 +comp.lang.pyt...@pearwood.info wrote:
 On Wed, 25 Apr 2012 20:50:21 -0700, Adam Skutt wrote:
  On Apr 25, 8:01 pm, Steven D'Aprano steve
  +comp.lang.pyt...@pearwood.info wrote:
  On Wed, 25 Apr 2012 13:49:24 -0700, Adam Skutt wrote:
  [Sterile pedantry]
  [More sterile pedantry]
  [Yet more sterile pedantry]
 [And more]
 [Record breaking levels of sterile pedantry]

Please stop!  Steven, I've learnt a lot from your posts on this list
over the years, but too often you spoil it with your compulsion to
have the last word on every argument you get involved in at any cost.
Some arguments aren't worth winning...

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


Re: Framework for a beginner

2012-04-17 Thread Arnaud Delobelle
On 17 April 2012 09:54, Bryan bryanjugglercryptograp...@yahoo.com wrote:
 Django has emphasized backwards compatibility with the
 down-side that, last I heard, there was no plan to move to Python 3.

Not quite:

https://www.djangoproject.com/weblog/2012/mar/13/py3k/

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


Re: Making helper methods more concise

2012-04-16 Thread Arnaud Delobelle
On 16 April 2012 13:01, Alan Ristow alan.ris...@gmail.com wrote:
 Hi all,

 I have defined a class that includes a number of helper methods that
 are useful to me, but pretty redundant. Something like so, where I
 maintain a list of tuples:

 class A(object):
    def __init__(self):
        self.listing = []

    # This method does the work.
    def append_text(self, text, style):
        self.listing.append((text, style))

    # The rest of the methods are just helpers.
    def append_paragraph(self, text):
        self.append_text(text, 'Paragraph')

    def append_header(self, text):
        self.append_text(text, 'Header')

    def append_title(self, text):
        self.append_title(text, 'Title')

 obj = A()
 obj.append_title('On Learning Something New About Python')
 obj.append_header('A Question Is Posed')
 obj.append_paragraph('Where is lorem ipsum when you need it?')


 To me, this code is simple, clear, and easy to maintain, but
 incredibly redundant. That's fine, I have no problem with that, but it
 got me thinking: Is there a way to make the code more concise?

 I know that concise is not necessarily better, but I am asking
 primarily to educate myself rather than to improve this particular
 piece of code -- the code only inspired the question. I'm trying to
 wrap my head around decorators (aside from the simplest ones) and
 metaclasses at the moment, so feel free to throw those sorts of
 solutions into the mix if something like that would be appropriate.

You can do this (untested), but no doubt it won't be to everybody's taste:

class A(object):
   def __init__(self):
   self.listing = []

   # This method does the work.
   def append_text(self, text, style):
   self.listing.append((text, style))

   # The rest of the methods are just helpers.
   for style in 'paragraph', 'header', 'title':
   exec def append_%s(self, text):
   self.append_text(text, %s) % (style, style.capitalize())
   del style


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


Re: Making helper methods more concise

2012-04-16 Thread Arnaud Delobelle
On 16 April 2012 13:29, Arnaud Delobelle arno...@gmail.com wrote:
 You can do this (untested), but no doubt it won't be to everybody's taste:

 class A(object):
   def __init__(self):
       self.listing = []

   # This method does the work.
   def append_text(self, text, style):
       self.listing.append((text, style))

   # The rest of the methods are just helpers.
   for style in 'paragraph', 'header', 'title':
       exec def append_%s(self, text):
           self.append_text(text, %s) % (style, style.capitalize())
   del style

Oops I sent too quickly.  Another way would be

class A(object):
  def __init__(self):
  self.listing = []

  # This method does the work.
  def append_text(self, text, style):
  self.listing.append((text, style))

for style in 'paragraph', 'header', 'title':
   setattr(A, 'append_' + style, lambda s, t, style=style:
A.append_text(s, t, style))

Untested too :)

Cheers,

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


Re: Zipping a dictionary whose values are lists

2012-04-14 Thread Arnaud Delobelle
On 13 April 2012 17:35, Kiuhnm kiuhnm03.4t.yahoo...@mail.python.org wrote:
 On 4/13/2012 17:58, Alexander Blinne wrote:

 zip(*[x[1] for x in sorted(d.items(), key=lambda y: y[0])])

 Or
  zip(*[d[k] for k in sorted(d.keys())])

.keys() is superfluous here:

zip(*(d[k] for k in sorted(d)))

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


Re: Python Gotcha's?

2012-04-05 Thread Arnaud Delobelle
On 5 April 2012 21:06, Emile van Sebille em...@fenx.com wrote:
 Kind of begs for a contains method that returns the appropriate boolean:

 if text.contains('bob')

It's already there:

text.__contains__('bob')

It's usually spelt otherwise though:

'bob' in text

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


Re: Odd strip behavior

2012-03-22 Thread Arnaud Delobelle
On Mar 22, 2012 7:49 PM, Rodrick Brown rodrick.br...@gmail.com wrote:

 #!/usr/bin/python

 def main():

str1='this is a test'
str2='t'

print .join([ c for c in str1 if c not in str2 ])
print(str1.strip(str2))

 if __name__ == '__main__':
main()

 ./remove_str.py
 his is a es
 his is a tes

 Why wasnt the t removed ?

Try help(ste.strip)

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


Re: Odd strip behavior

2012-03-22 Thread Arnaud Delobelle
On 22 March 2012 20:04, Rodrick Brown rodrick.br...@gmail.com wrote:

 On Mar 22, 2012, at 3:53 PM, Arnaud Delobelle arno...@gmail.com wrote:
 Try help(ste.strip)

 It clearly states if chars is given and not None, remove characters in
 chars instead.

 Does it mean remove only the first occurrence of char? That's the behavior
 I'm seeing.

The key words in the docstring are leading and trailing

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


Re: Currying in Python

2012-03-20 Thread Arnaud Delobelle
On 19 March 2012 23:20, Ian Kelly ian.g.ke...@gmail.com wrote:
 I hope you don't mind if I critique your code a bit!

 On Fri, Mar 16, 2012 at 7:21 PM, Kiuhnm
 kiuhnm03.4t.yahoo...@mail.python.org wrote:
 Here we go.

 ---
 def genCur(f, unique = True, minArgs = -1):

 It is customary in Python for unsupplied arguments with no default to
 use the value None, not -1.  That's what it exists for.

     Generates a 'curried' version of a function. 
    def geng(curArgs, curKwargs):
        def g(*args, **kwargs):
            nonlocal f, curArgs, curKwargs, minArgs;    # our STATIC data

I don't know if all the rest of the code is below, but this line above
would only be necessary if you want to rebind f, curArgs, minArgs.
You don't seem to do it, so I think this line is unnecessary.

Also, your naming of variables disagrees with PEP 8 :)

            if len(args) or len(kwargs):

 Collections evaluate as true if they are not empty, so this could just be:

            if args or kwargs:

                # Allocates data for the next 'g'. We don't want to modify our
                # static data.
                newArgs = curArgs[:];

Semicolon to end a statement?

                newKwargs = dict.copy(curKwargs);

                # Adds positional arguments.
                newArgs += args;

                # Adds/updates keyword arguments.
                if unique:
                    # We don't want repeated keyword arguments.
                    for k in kwargs.keys():
                        if k in newKwargs:
                            raise(Exception(Repeated kw arg while unique = 
 True));
                newKwargs.update(kwargs);

 Since you're writing this for Python 3 (as evidenced by the use of the
 nonlocal keyword), you could take advantage here of the fact that
 Python 3 dictionary views behave like sets.  Also, you should use a
 more specific exception type:

                if unique and not kwargs.keys().isdisjoint(newKwargs):
                    raise ValueError(A repeated keyword argument was 
 supplied)

                # Checks whether it's time to evaluate f.
                if minArgs = 0 and minArgs = len(newArgs) + len(newKwargs):

 With minArgs defaulting to None, that would be:

                if minArgs is not None and minArgs = len(newArgs) +
 len(newKwargs):

                    return f(*newArgs, **newKwargs);    # f has enough args
                else:
                    return geng(newArgs, newKwargs);    # f needs some more 
 args
            else:
                return f(*curArgs, **curKwargs);    # the caller forced the 
 evaluation
        return g;
    return geng([], {});

 def cur(f, minArgs = -1):
    return genCur(f, True, minArgs);

 def curr(f, minArgs = -1):
    return genCur(f, False, minArgs);

 The names cur and curr are terrible.  Good names should describe
 what the function does without being too onerous to type, and the
 addition of the duplicate r is not an obvious mnemonic for
 remembering that the first one prohibits duplicate keyword arguments
 and the second one allows them.  Why not more descriptive names like
 curry and curry_unique?

 That's all I've got.  All in all, it's pretty decent for a Python newbie.

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


Re: Python is readable

2012-03-15 Thread Arnaud Delobelle
On 15 March 2012 00:27, Chris Angelico ros...@gmail.com wrote:
 On Thu, Mar 15, 2012 at 10:54 AM, Arnaud Delobelle arno...@gmail.com wrote:
 I don't know this book and there may be a pedagogical reason for the
 implementation you quote, but pairwise_sum is probably better
 implemented in Python 3.X as:

 def pairwise_sum(list1, list2):
    return [x1 + x2 for x1, x2 in zip(list1, list2)]

 Okay, here's something for debate.

 Should the readability of a language be gauged on the basis of its
 standard library, or should you be comparing actual code?

But here's the code posted by the OP:

--- Python ---
def pairwise_sum(list1, list2):
   result = []
   for i in range(len(list1)):
   result.append(list1[i] + list2[i])
   return result
--- ---

The code I posted uses one builtin function (zip), the code posted by
the OP uses two (range and len).  Neither uses the standard library.

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


Re: Python is readable

2012-03-15 Thread Arnaud Delobelle
On 15 March 2012 22:35, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Kiuhnm kiuhnm03.4t.yahoo.it writes:

 Moreover, I think that
   if (
       
       ):
       
       
       
 is not very readable anyway.

 I agree, and am glad PEP 8 has been updated to recommend an extra level
 of indentation for continuation, to distinguish from the new block that
 follows URL:http://www.python.org/dev/peps/pep-0008/#indentation.

Personally I solve this by never writing if conditions that span more
than one line.  If the worst comes to the worst, I would write:

aptly_named_condition = (
very long condition
that goes over
plenty of lines
)
if aptly_named_condition:
do stuff

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


Re: Style question (Poll)

2012-03-14 Thread Arnaud Delobelle
On 14 March 2012 20:37, Croepha croe...@gmail.com wrote:
 Which is preferred:

 for value in list:
  if not value is another_value:
    value.do_something()
    break

 --or--

 if list and not list[0] is another_value:
  list[0].do_something()

Hard to say, since they don't do the same thing :)

I suspect you meant:

for value in list:
   if not value is another_value:
   value.do_something()
   break

I always feel uncomfortable with this because it's misleading: a loop
that never loops.

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


Re: Style question (Poll)

2012-03-14 Thread Arnaud Delobelle
On 14 March 2012 22:15, Prasad, Ramit ramit.pra...@jpmorgan.com wrote:
 Only use 'is' if you are looking for objects like True,
 False, None or something that MUST be exactly the same object.

I've rarely seen valid uses of 'is True' or 'is False'.

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


Re: Python is readable

2012-03-14 Thread Arnaud Delobelle
On 14 March 2012 23:34, Kiuhnm kiuhnm03.4t.yahoo...@mail.python.org wrote:
 I've just started to read
  The Quick Python Book (2nd ed.)
 The author claims that Python code is more readable than Perl code and
 provides this example:

 --- Perl ---
 sub pairwise_sum {
    my($arg1, $arg2) = @_;
    my(@result) = ();
    @list1 = @$arg1;
    @list2 = @$arg2;
    for($i=0; $i  length(@list1); $i++) {
        push(@result, $list1[$i] + $list2[$i]);
    }
    return(\@result);
 }

 --- Python ---
 def pairwise_sum(list1, list2):
    result = []
    for i in range(len(list1)):
        result.append(list1[i] + list2[i])
    return result
 --- ---

 It's quite clear that he knows little about Perl.
 Here's what I would've written:

 sub pairwise_sum {
    my ($list1, $list2) = @_;
    my @result;
    push @result, $list1-[$_] + $list2-[$_] for (0..@$list1-1);
    \@result;
 }

 Having said that, the Python code is still more readable, so there's no need
 to misrepresent Perl that way.
 Now I'm wondering whether the author will show me good or bad Python
 code throughout the book. Should I keep reading?

I don't know this book and there may be a pedagogical reason for the
implementation you quote, but pairwise_sum is probably better
implemented in Python 3.X as:

def pairwise_sum(list1, list2):
return [x1 + x2 for x1, x2 in zip(list1, list2)]

Or in Python 2.X:

from itertools import izip

def pairwise_sum(list1, list2):
return [x1 + x2 for x1, x2 in izip(list1, list2)]

Or even:

from operator import add

def pairwise_sum(list1, list2):
return map(add, list1, list2)

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


Re: Fast file data retrieval?

2012-03-12 Thread Arnaud Delobelle
On 12 March 2012 19:39, Virgil Stokes v...@it.uu.se wrote:
 I have a rather large ASCII file that is structured as follows

 header line
 9 nonblank lines with alphanumeric data
 header line
 9 nonblank lines with alphanumeric data
 ...
 ...
 ...
 header line
 9 nonblank lines with alphanumeric data
 EOF

 where, a data set contains 10 lines (header + 9 nonblank) and there can be
 several thousand
 data sets in a single file. In addition, each header has a unique ID code.

 Is there a fast method for the retrieval of a data set from this large file
 given its ID code?

It depends.  I guess if it's a long running application, you could
load up all the data into a dictionary at startup time (several
thousand data sets doesn't sound like that much).  Another option
would be to put all this into a dbm database file
(http://docs.python.org/library/dbm.html) - it would be very easy to
do.

Or you could have your own custom solution where you scan the file and
build a dictionary mapping keys to file offsets, then when requesting
a dataset you can seek directly to the correct position.
-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython callable. How?

2012-03-04 Thread Arnaud Delobelle
On Mar 4, 2012 9:04 AM, Sirotin Roman web.elektro@gmail.com wrote:

 Hi.
 How exactly jython decides is object callable or not? I defined
 __call__ method but interpreter says it's still not callable.
 BTW, my code works in cpython

It will help if you show us the code.

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


Re: decompilation

2012-03-02 Thread Arnaud Delobelle
On 2 March 2012 18:52, shikha panghal spdollyshik...@gmail.com wrote:
 Hi

 Please decoplile the .pyc code ,as i have lost my .py code.

Aha, a customer!  I've written a module for this: unpyc3
(http://code.google.com/p/unpyc3/)

Here it is in action:


Python 3.2.1 (v3.2.1:ac1f7e5c0510, Jul  9 2011, 01:03:53)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type help, copyright, credits or license for more information.
 import unpyc3
 import hangman322
 code = unpyc3.decompile(hangman322)
 print(code)
import random

def readFile(fileName):
file = open(fileName)
lineList = file.readlines()
file.close()
return lineList

def initialize(fileName):
try:
lineList = readFile(fileName)
except:
print('Oops! ' + filename + ' was not a valid file.')
return
len_d = len(lineList)
word_length = [0]*len_d
for i in range(len_d):
if lineList[i][-1] == '\n':
word_length[i] = len(lineList[i]) - 1
else:
word_length[i] = len(lineList[i])
tabulate = [0]*25
for i in range(len_d):
if word_length[i] = 24:
tabulate[24] = tabulate[24] + 1
else:
tabulate[word_length[i]] = tabulate[word_length[i]] + 1
words = [None]*25
for i in range(2, 24):
words[i] = [None]*tabulate[i]
k = 0
for j in range(len_d):
if word_length[j] == i:
words[i][k] = lineList[j]
k = k + 1
for i in range(24, 25):
words[i] = [None]*tabulate[i]
k = 0
for j in range(len_d):
if word_length[j] = i:
words[i][k] = lineList[j]
k = k + 1
return words

def wordsOfLength(n, source_file):
words = initialize(source_file)
return words[n]

def getUserStringInput(L, prompt):
replyInList = False
while not replyInList:
reply = input(prompt)
replyInList = reply in L
if not replyInList:
print('That reply is invalid. Try again.')
return reply

def intListToStringList(L):
L2 = ['']*len(L)
for i in range(len(L)):
L2[i] = str(L[i])
return L2

def getNewLetterGuess(availableLetters):
letterString = ''
for j in range(26):
if availableLetters[j]:
letterString = letterString + chr(65 + j) + ' '
else:
letterString = letterString + '  '
validChar = False
print(letterString)
while not validChar:
reply = input('Guess!  ')
if len(reply) == 1:
validChar = True
letterIndex = ord(reply) - 65
if letterIndex  25:
letterIndex = letterIndex - 32
while letterIndex  25 or not availableLetters[letterIndex]:
print('This is an invalid choice. Please try again!')
validChar = False
print(letterString)
while not validChar:
reply = input('Guess!  ')
if len(reply) == 1:
validChar = True
letterIndex = ord(reply) - 65
if letterIndex  25:
letterIndex = letterIndex - 32
guess = chr(97 + letterIndex)
availableLetters[letterIndex] = False
return guess, availableLetters

def getWordFamilyCounter(L, n, guess):
wordFamilyCounter = [0]*2**n
familyIndexList = [-1]*len(L)
for k in range(len(L)):
w = list(L[k])
ct = 0
for k2 in range(n):
if w[k2] == guess:
ct = ct + 2**k2
familyIndexList[k] = ct
wordFamilyCounter[ct] = wordFamilyCounter[ct] + 1
return wordFamilyCounter, familyIndexList

def extractLargestFamily(L, familyIndexList, wordFamilyCounter):
bestFamily = wordFamilyCounter.index(max(wordFamilyCounter))
boolist = [False]*len(L)
for k3 in range(len(L)):
if familyIndexList[k3] == bestFamily:
boolist[k3] = True
j2 = 0
smallList = [' ']*sum(boolist)
for k4 in range(len(L)):
if boolist[k4]:
smallList[j2] = L[k4]
j2 = j2 + 1
return smallList

def updatePatternList(patternList, guess, bestFamily):
n = len(patternList)
for k6 in range(n):
if bestFamily//2 == bestFamily/2:
pass
else:
patternList[k6] = guess + ' '
bestFamily = bestFamily  1
return patternList

def pickWordFrom(L):
index = random.randint(0, len(L) - 1)
return L[index]

def play():
reply = getUserStringInput(intListToStringList(list(range(2,
21))), 'How long should I make your word?!!? (2 to 20)  ')
n = int(reply)
patternList = ['_ ']*n
print(''.join(patternList))
L = wordsOfLength(n, 'dictionary.txt')
reply = getUserStringInput(intListToStringList(list(range(1,
27))), 'How many guesses will you need?  ')
m = int(reply)
availableLetters = [True]*26
for i in range(m):
guess, availableLetters = getNewLetterGuess(availableLetters)
wordFamilyCounter, familyIndexList = getWordFamilyCounter(L, n, 

Re: exec

2012-03-01 Thread Arnaud Delobelle
On 1 March 2012 13:07, Rolf Wester rolf.wes...@ilt.fraunhofer.de wrote:
 Hi,

 I would like to define methods using exec like this:

 class A:
    def __init__(self):
        cmd = def sqr(self, x):\n    return x**2\nself.sqr = sqr\n
        exec cmd
 a = A()
 print a.sqr(a, 2)

 This works, but I have to call sqr with a.sqr(a, 2), a.sqr(2) does not work
 (TypeError: sqr() takes exactly 2 arguments (1 given)).

I'm curious to know your motivation for doing this.

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


Re: Listing children processes

2012-02-28 Thread Arnaud Delobelle
On 28 February 2012 21:39, Mihai Badoiu mbad...@gmail.com wrote:
 On Tue, Feb 28, 2012 at 4:35 PM, Chris Rebert c...@rebertia.com wrote:

 On Tue, Feb 28, 2012 at 10:33 AM, Mihai Badoiu mbad...@gmail.com wrote:
  I'm trying to compute the total CPU load of an external process and it's
  children.  (so I cannot use resource.getrusage)  For the load of the
  process
  I can just grab it from /proc/X/stat.  How do I get the CPU load of the
  children processes?  Is there an easy way to get a list of the children
  processes?

 http://code.google.com/p/psutil/

 Cheers,
 Chris

 Looked at that before.  psutil doesn't do children.

 --mihai

Please don't top-post!  Also, psutil.Process.get_children() looks to
me like it does children.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-26 Thread Arnaud Delobelle
On 26 February 2012 13:38, Wolfgang Meiners wolfgangmeiner...@web.de wrote:
      do_it = (len(str) = maxlength) if maxlength is not None else True

That's a funny way to spell:

do_it = maxlength is None or len(str) = maxlength

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


Re: Does turtledemo in Python 3.2 actually work?

2012-02-24 Thread Arnaud Delobelle
On 24 February 2012 12:25, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Python 3.2 includes turtledemo, a demonstration program for the turtle
 module.

 When I run it, I can load the turtle scripts, and the GUI application
 says Press the start button, but there is no start button.

 Can anyone else confirm this as a bug?

 http://docs.python.org/py3k/library/turtle.html#demo-scripts

Just tested with Python 3.2.1 on Mac OS X 10.6.8 and all seems fine.
Perhaps if you say which platform it's failing on, others will be able
to reproduce the failure on the same platform?

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


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Arnaud Delobelle
On 24 February 2012 14:54, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:

 for...else is a very useful construct, but the name is misleading. It
 took me a long time to stop thinking that the else clause executes when
 the for loop was empty.

This is why I think we should call this construct for / break / else
rather than for / else.

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


Re: sum() requires number, not simply __add__

2012-02-23 Thread Arnaud Delobelle
On 23 February 2012 21:19, Buck Golemon b...@yelp.com wrote:
 I feel like the design of sum() is inconsistent with other language
 features of python. Often python doesn't require a specific type, only
 that the type implement certain methods.

 Given a class that implements __add__ why should sum() not be able to
 operate on that class?

It can.  You need to pass a second argument which will be the start
value.  Try help(sum) for details.

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


Re: sum() requires number, not simply __add__

2012-02-23 Thread Arnaud Delobelle
On 23 February 2012 21:23, Buck Golemon b...@yelp.com wrote:
 def sum(values,
 base=0):
      values =
 iter(values)

      try:
          result = values.next()
      except StopIteration:
          return base

      for value in values:
          result += value
      return result

This is definitely not backward compatible.  To get something that has
a better chance of working with existing code, try this (untested):

_sentinel = object()

def sum(iterable, start=_sentinel):
if start is _sentinel:
iterable = iter(iterable)
try:
start = iterable.next()
except StopIteration:
return 0
for x in iterable:
start += x
return start

del _sentinel

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


Re: sum() requires number, not simply __add__

2012-02-23 Thread Arnaud Delobelle
On 23 February 2012 21:53, Chris Angelico ros...@gmail.com wrote:
 On Fri, Feb 24, 2012 at 8:41 AM, Arnaud Delobelle arno...@gmail.com wrote:
 _sentinel = object()

 def sum(iterable, start=_sentinel):
    if start is _sentinel:

 del _sentinel

 Somewhat off-topic: Doesn't the if statement there do a lookup for a
 global, which would mean that 'del _sentinel' will cause it to fail?
 Or have I missed something here?

Yes, you're right :)  Change the signature to

def sum(iterable, start=_sentinel, _sentinel=_sentinel):

This is not pretty...

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


Re: sum() requires number, not simply __add__

2012-02-23 Thread Arnaud Delobelle
On 23 February 2012 22:04, Chris Angelico ros...@gmail.com wrote:
 On Fri, Feb 24, 2012 at 8:59 AM, Arnaud Delobelle arno...@gmail.com wrote:
 def sum(iterable, start=_sentinel, _sentinel=_sentinel):

 Is this a reason for Python to introduce a new syntax, such as:

 def foo(blah, optional=del):
    if optional is del: print(No argument was provided)

 Basically, 'del' is treated like a unique non-providable object, only
 possible in an argument list and only if the argument was omitted. No
 more proliferation of individual sentinels... what do you think?

The problem with these proposals is to avoid the leakage of 'del'.
Here you could do:

def get_del(x=del):
return x

And then you're in trouble again.

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


Re: HTTP logging

2012-02-20 Thread Arnaud Delobelle
On 20 February 2012 16:03, Jason Friedman ja...@powerpull.net wrote:
 I am logging to HTTP:

 logger.addHandler(logging.handlers.HTTPHandler(host, url))

 Works great, except if my HTTP server happens to be unavailable:

 socket.error: [Errno 111] Connection refused

 Other than wrapping all my logger.log() calls in try/except blocks, is
 there a way to skip logging to the HTTPhandler if the HTTP server is
 unavailable?

Here's one: subclass HTTPHandler :)

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


Re: question about function pointer

2012-02-17 Thread Arnaud Delobelle
On 17 February 2012 07:53, Zheng Li dllizh...@gmail.com wrote:
 def method1(a = None):
        print a

 i can call it by
 method1(*(), **{'a' : 1})

 I am just curious why it works and how it works?
 and what do *() and **{'a' : 1} mean?

 when I type *() in python shell, error below happens

  File stdin, line 1
    *()
    ^
 SyntaxError: invalid syntax

It's worth reading the Python tutorial.  Here's the relevant section:

http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

You could read all of 4.7

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


Re: Wanted: Criticism of code for a Python module, plus a Mac tester

2012-02-16 Thread Arnaud Delobelle
On 16 February 2012 05:03, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Wed, Feb 15, 2012 at 6:11 PM, HoneyMonster someone@someplace.invalid 
 wrote:
 As to your first suggestion though, I am having some difficulty. Note
 that the vulnerability rotates; i.e. CONDITIONS[4] is not the same as
 CONDITIONS[0].
 Is there a better way of doing it than a simple list.append()?

 Ah, it's more complicated than I realized.  I believe this generates
 the correct result, although adding None to the dealers list is
 somewhat unsatisfactory:

 DEALERS = [Dealer North, Dealer East, Dealer South, Dealer West, None]
 VULNERABILITIES = [
   Neither vulnerable, North-South vulnerable,
   East-West vulnerable, Both vulnerable,
 ]
 CONDITIONS = [(d, v) for (d, v) in zip(DEALERS * 4, VULNERABILITIES * 5) if d]

You could also do:

DEALERS = [Dealer North, Dealer East, Dealer South, Dealer West]
VULNERABILITIES = [
  Neither vulnerable, North-South vulnerable,
  East-West vulnerable, Both vulnerable,
]
CONDITIONS = [
(DEALERS[j], VULNERABILITIES[(i + j)%4])
for i in range(4) for j in range(4)
]

If you don't care about the order in which the conditions are listed,
you could use

CONDITIONS = itertools.product(DEALERS, VULNERABILITIES)

(But maybe you do, I haven't looked at the code)

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


Re: TEST AN EXECUTABLE PYTHON SCRIPT SPEED UNDER A PYTHON SHELL

2012-02-16 Thread Arnaud Delobelle
On 16 February 2012 21:10, Prasad, Ramit ramit.pra...@jpmorgan.com wrote:
 When you reply to a known bot, please include some indication of the
 fact, so we know your message can be ignored as well.

Sometimes I wonder about 8. Is there a real person there, as well as the 
bot? A lot of his/its
 posts look too intelligent to be computer-generated - or maybe I'm 
 underestimating the quality of AI.

 I was wondering the exact same thing.

I think it may be that what you are underestimating is your ability,
as a human being, to create meaning where there is none.

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


Re: OT: Entitlements [was Re: Python usage numbers]

2012-02-15 Thread Arnaud Delobelle
On 15 February 2012 09:47, Duncan Booth duncan.booth@invalid.invalid wrote:
 Rick Johnson rantingrickjohn...@gmail.com wrote:
[...]

Perhaps it's a bit presumptuous of me but...

It's tempting to react to his inflammatory posts, but after all Rick
is a troll and experience shows that trolls are best left alone.
Also, please spare a thought for all of us who have him in our
killfiles.

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


Re: Interactive keyword help

2012-02-15 Thread Arnaud Delobelle
On 15 February 2012 17:23, Andrew Berg bahamutzero8...@gmail.com wrote:
 On 2/15/2012 10:04 AM, Mark Lawrence wrote:
 I didn't realise that this was available until today.  It doesn't appear
 to be prominent in the official docs or have I missed something?
 Certainly I'd have thought a couple of sentences here
 http://www.python.org/about/help/ would be justified, what do y'all think?

 help() is a built-in function, not a keyword.

I think he's referring to help *on* keywords, e.g.

 help('yield')

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


Re: name of a sorting algorithm

2012-02-14 Thread Arnaud Delobelle
On 14 February 2012 15:31, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:
 On Tue, 14 Feb 2012 16:01:05 +0100, Jabba Laci jabba.l...@gmail.com
 wrote:

Could someone please tell me what the following sorting algorithm is called?

Let an array contain the elements a_1, a_2, ..., a_N. Then:

for i = 1 to N-1:
    for j = i+1 to N:
        if a_j  a_i then swap(a_j, a_i)

        Off hand... The ancient Bubble-Sort...

 http://en.wikipedia.org/wiki/Bubble_sort

Ahem...

No, it's not Bubble Sort.  Bubble sort only swaps adjacent terms.

I don't know what this sort is called, if it even has a name.  It's a
kind of Selection Sort, as each pass it looks for the minimum of the
remaining unsorted items.  But it ruffles the unsorted list each pass,
seemingly to save using an extra register to store the current minumum
(there was a time when registers were at a premium).

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


Re: Strange Behavior on Python 3 Windows Command Line

2012-02-13 Thread Arnaud Delobelle
On 13 February 2012 19:50, waylan way...@gmail.com wrote:
 When I try running any Python Script on the command line with Python
 3.2 I get this weird behavior. The cursor dances around the command
 line window and nothing ever happens. Pressing Ctr+C does nothing.
 When I close the window (mouse click on X in top right corner), an
 error dialog appears asking me to force it to close.

I'm not a Windows user, so I can't be of assistance but it may help
others if you explained how you installed Python 3.2 on your computer.
 Also have you tried reinstalling it?

 Strangely it was working fine the other day. Then while debugging a
 script it suddenly started do this and now does this for every script

How were you debugging?

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


Re: round down to nearest number

2012-02-10 Thread Arnaud Delobelle
On 10 February 2012 06:21, Ian Kelly ian.g.ke...@gmail.com wrote:
 (3219 + 99) // 100 * 100
 3300
 (3289 + 99) // 100 * 100
 3300
 (328678 + 99) // 100 * 100
 328700
 (328 + 99) // 100 * 100
 400

 Those are all rounded up to the nearest 100 correctly.

 One thing to be aware of though is that while the round down formula
 works interchangeably for ints and floats, the round up formula does
 not.

 (3300.5 + 99) // 100 * 100
 3300.0


I'm surprised I haven't seen:

 212 - (212 % -100)
300

Here's a function that:
* rounds up and down
* works for both integers and floats
* is only two operations (as opposed to 3 in the solutions given above)

 def round(n, k):
... return n - n%k
...
 # Round down with a positive k:
... round(167, 100)
100
 round(-233, 100
... )
-300
 # Round up with a negative k:
... round(167, -100)
200
 round(-233, -100)
-200
 # Edge cases
... round(500, -100)
500
 round(500, 100)
500
 # Floats
... round(100.5, -100)
200.0
 round(199.5, 100)
100.0

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


Re: Read-only attribute in module

2012-02-10 Thread Arnaud Delobelle
On 10 February 2012 03:27, Terry Reedy tjre...@udel.edu wrote:
 On 2/9/2012 8:04 PM, Steven D'Aprano wrote:

 Python happily violates consenting adults all over the place. We have
 properties, which can easily create read-only and write-once attributes.


 So propose that propery() work at module level, for module attributes, as
 well as for class attributes.

I think Steven would like something else: bare names that cannot be
rebound. E.g. something like:

 const a = 42
 a = 7

Would raise an exception.  Is that right?

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


Re: multiple namespaces within a single module?

2012-02-10 Thread Arnaud Delobelle
On 10 February 2012 00:05, Ethan Furman et...@stoneleaf.us wrote:
 Ethan Furman wrote:

 Hrm -- and functions/classes/etc would have to refer to each other that
 way as well inside the namespace... not sure I'm in love with that...



 Not sure I hate it, either.  ;)

 Slightly more sophisticated code:

 code
 class NameSpace(object):
    def __init__(self, current_globals):
        self.globals = current_globals
        self.saved_globals = current_globals.copy()

    def __enter__(self):
        return self
    def __exit__(self, *args):
        new_items = []
        for key, value in self.globals.items():
            if (key not in self.saved_globals and value is not self
                    or key in self.saved_globals
                    and value != self.saved_globals[key]):

                new_items.append((key, value))
        for key, value in new_items:
            setattr(self, key, value)
            del self.globals[key]
        self.globals.update(self.saved_globals)

 if __name__ == '__main__':
    x = 'inside main!'
    with NameSpace(globals()) as a:
        x = 'inside a?'
        def fn1():
            print(a.x)
    with NameSpace(globals()) as b:
        x = 'inside b?'
        def fn1():
            print(b.x)
        def fn2():
            print('hello!')
            b.fn1()
    y = 'still inside main'
    a.fn1()
    b.fn1()
    print(x)
    print(y)
 /code

Please! Metaclasses are the obvious way to proceed here :)  Then there
is no need for the 'a.x' and 'b.x' cruft.

marigold:junk arno$ cat namespace.py
function = type(lambda:0)

def change_globals(f, g):
return function(f.__code__, g, f.__name__, f.__defaults__, f.__closure__)

class MetaNamespace(type):
def __new__(self, name, bases, attrs):
attrs['__builtins__'] = __builtins__
for name, value in attrs.items():
if isinstance(value, function):
attrs[name] = change_globals(value, attrs)
return type.__new__(self, name, bases, attrs)

class Namespace(metaclass=MetaNamespace):
pass


x = inside main

class a(Namespace):
x = inside a
def fn1():
print(x)

class b(Namespace):
x = inside b
def fn1():
print(x)
def fn2():
print(hello)
fn1()

y = inside main

a.fn1()
b.fn1()
b.fn2()
print(x)
print(y)
marigold:junk arno$ python3 namespace.py
inside a
inside b
hello
inside b
inside main
inside main

A bit more work would be needed to support nested functions and closures...

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


Re: when to use import statements in the header, when to use import statements in the blocks where they are used?

2012-02-10 Thread Arnaud Delobelle
On 8 February 2012 01:48, Lei Cheng pat.ins...@gmail.com wrote:
 Hi all,

    In a py file, when to use import statements in the header, when to use
 import statements in the blocks where they are used?
    What are the best practices?
    Thanks!

Aside from other answers: in some rare cases, importing within a
function can avoid circularity problems (e.g. A imports B which tries
itself to import A)

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


Re: log and figure out what bits are slow and optimize them.

2012-02-10 Thread Arnaud Delobelle
On 10 February 2012 12:30, sajuptpm sajup...@gmail.com wrote:
 Hi,

 I want to log time taken to complete database requests inside a method/
 function using decorator .  is it possible 
 I think, i have to inject log code inside the method/fuctions or
 modify it.
 I wrote a decorator to log taken by a method/function to complete it
 execution and its working well.

 My requirement : log everything and figure out what bits are slow and
 optimize them.

 What are your suggestions ??

Are you familiar with this?

http://docs.python.org/library/profile.html

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


Re: How can I catch misnamed variables?

2012-02-10 Thread Arnaud Delobelle
On 10 February 2012 21:06, John Gordon gor...@panix.com wrote:
 Recently I was been bitten by some stupid errors in my code, and I'm
 wondering if there's a simple way to catch them.

 One error was of the form:

  my_object.some_function()

 .. when I hadn't declared an object named my_object.

 The other error was similar:

  x = my_module.CONSTANT

 .. when I hadn't imported my_module.

 Of course both of these errors were deep inside a long-running function
 call, so it took a while for them to crop up.

 Is there an automated way to catch errors like these?  I'm using the
 compileall module to build my program and it does catch some errors
 such as incorrect indentation, but not errors like the above.

There's pychecker and pylint

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


Re: Naming convention for in-house modules (Newbie question)

2012-02-09 Thread Arnaud Delobelle
On 9 February 2012 14:00, Laurent Claessens moky.m...@gmail.com wrote:

 Here is my question: I would like to start an in-house library of small
 modules to import, for things like error handling/logging. That's easy
 enough, but is there a recommended way of naming such modules? I am
 concerned about avoiding name clashes with standard modules and site
 packages.

 Thanks.


 This is not 100% an answer to the question, but you should read that :
 http://www.python.org/dev/peps/pep-0008/

The OP mentions PEP 8 in the bit of his message that you *don't* quote.

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


Re: iterating over list with one mising value

2012-02-07 Thread Arnaud Delobelle
On 7 February 2012 20:23, Sammy Danso samdans...@yahoo.com wrote:

 Hi Expert,
 Thanks for your responses and help. thought I should provide more information 
 for clarity.

Please don't top-post.

 Please find the error message below for more information

    for (key, value) in wordFreq2:
 ValueError: need more than 1 value to unpack

 this is a sample of my data

 ['with', 3, 'which', 1, [...] , 3, 'other']

 What I would like to do is to pad the last value 'other' with a default so I 
 can iterate sucessfully

* It would be better if you provided the code that produces the error,
rather than just the error.  This would allow others to diagnose your
problem without having to guess what you're really doing (see my guess
below)

* Also, don't truncate the traceback.

My guess: you're running a loop like this, where each item is unpacked:

for (key, value) in wordFreq2:
print key, value

on data like that:

wordFreq2 = ['with', 3, 'which', 1, 'were', 2, 'well', 1]

Your list is flat so the unpacking fails.  For it to work, you need
your list to be of the form:

wordFreq2 = [('with', 3), ('which', 1), ('were', 2), ('well', 1)]

Then it will work.  The quickest way to transform your list to the
required form is something like this:

def pairs(seq, fillvalue):
it = iter(seq)
return list(izip_longest(it, it, fillvalue=fillvalue)

so you can do:

word_freq_pairs = pairs(wordFreq2)

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


Re: iterating over list with one mising value

2012-02-07 Thread Arnaud Delobelle
On 7 February 2012 22:57, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:
 On Tue, 7 Feb 2012 21:37:20 +, Arnaud Delobelle arno...@gmail.com
 wrote:



Your list is flat so the unpacking fails.  For it to work, you need
your list to be of the form:

    wordFreq2 = [('with', 3), ('which', 1), ('were', 2), ('well', 1)]

Then it will work.  The quickest way to transform your list to the
required form is something like this:

        Well... From my viewpoint, the quickest way is to load the list
 correctly in the first place... Where does this list come from? If it's
 a file of

Of course, but how much guessing can you do in a reply?  The OP
provided a Python list, that's what I used.

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


Re: Common LISP-style closures with Python

2012-02-04 Thread Arnaud Delobelle
On 4 February 2012 10:14, Antti J Ylikoski antti.yliko...@tkk.fi wrote:
 On 4.2.2012 4:47, Chris Rebert wrote:
 Out of curiosity, what would be non-Common-Lisp-style closures?

 Cheers,
 Chris


 I understand that a closure is something which is typical of functional
 programming languages.  -- Scheme-style closures, for example.

 I don't know Haskell, ML etc. but I do suspect that we could create closures
 in those languages as well.  Maybe someone more expert than me can help?

I think what Chris asking is: what is the feature of Common-Lisp
closures that Python closures share but other languages don't?

I think what he is implying is that there is no such feature.  Python
closures are no more Common-Lisp-style than they are Scheme-style
or Smalltalk-like or any other language-like.

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


Re: Iterate from 2nd element of a huge list

2012-02-01 Thread Arnaud Delobelle
On 1 February 2012 08:11, Peter Otten __pete...@web.de wrote:
 Arnaud Delobelle wrote:
 The example should be

 from itertools import islice:

 for el in islice(mylist, 1, None):
     process2(el)

Oops!

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


Re: Generator problem: parent class not seen

2012-02-01 Thread Arnaud Delobelle
On Feb 1, 2012 9:01 PM, Russell E. Owen ro...@uw.edu wrote:

 I have an odd and very intermittent problem in Python script.
 Occasionally it fails with this error:

 Traceback (most recent call last):
  File
 /Applications/APO/TTUI.app/Contents/Resources/lib/python2.7/TUI/Base/Bas
 eFocusScript.py, line 884, in run
  File
 /Applications/APO/TTUI.app/Contents/Resources/lib/python2.7/TUI/Base/Bas
 eFocusScript.py, line 1690, in initAll
 TypeError: unbound method initAll() must be called with BaseFocusScript
 instance as first argument (got ScriptClass instance instead)
 self=ScriptClass object at 0x2066b410; class hierarchy=[(class
 'TUI.Base.BaseFocusScript.ImagerFocusScript', (class
 'TUI.Base.BaseFocusScript.BaseFocusScript',)), [(class 'ScriptClass',
 (class 'TUI.Base.BaseFocusScript.ImagerFocusScript',))]]


Looks like you have loaded the same module twice.  So you have two versions
of your class hierarchies. You can check by printing the ids of your
classes. You will get classes with the same name but different ids.

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


Re: Iterate from 2nd element of a huge list

2012-01-31 Thread Arnaud Delobelle
On 1 February 2012 03:16, Paulo da Silva p_s_d_a_s_i_l_...@netcabo.pt wrote:
 Em 01-02-2012 01:39, Paulo da Silva escreveu:
 Hi!

 What is the best way to iterate thru a huge list having the 1st element
 a different process? I.e.:

 process1(mylist[0])
 for el in mylist[1:]:
       process2(el)

 This way mylist is almost duplicated, isn't it?

 Thanks.


 I think iter is nice for what I need.
 Thank you very much to all who responded.

Nobody mentioned itertools.islice, which can be handy, especially if
you weren't interested in the first element of the list:

from itertools import islice:

for el in islice(mylist, 1):
process2(el)

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


Re: 'class' named tuple

2012-01-31 Thread Arnaud Delobelle
On 1 February 2012 00:54, Emmanuel Mayssat emays...@gmail.com wrote:
 I have the following program.
 I am trying to have index the attributes of an object using __getitem__.
 Reading them this way works great, but assigning them a value doesn't
 Is there a way to do such a thing?
 (Almost like a named tuple, but with custom methods)

 class LIter(object):
    def __init__(self,parent=None):
        super(LIter, self).__init__()
        self.toto = 3
        self.tata = 'terto'


Add
_attrs = 'toto', 'tata'
def __getitem__(self, index):
return getattr(self, _attrs[index])
def __setitem__(self, index, value)
setattr(self, _attrs[index], value)

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


  1   2   3   4   5   6   7   8   9   10   >