Re: MailingLogger 3.4.0 Released!

2011-08-23 Thread Chris Withers
Heh, of course, I forgot the setuptools-git extension to make 
include_package_data=True work, so this release was pretty useless, 
other than the docs on packages.python.org/testfixtures ;-)


Anyway, 3.4.1 has now been released which fixes this!

cheers,

Chris

On 17/08/2011 23:37, Chris Withers wrote:

I'm pleased to announce a new release of Mailinglogger.

Mailinglogger provides two handlers for the standard python
logging framework that enable log entries to be emailed either as the
entries are logged or as a summary at the end of the running process.

The handlers have the following features:

- customisable and dynamic subject lines for emails sent

- emails sent with a configurable headers for easy filtering

- flood protection to ensure the number of emails sent is not excessive

- support for SMTP servers that require authentication

- fully documented and tested

This release has no functional changes but finally ships with a full new
set of Sphinx docs:

http://packages.python.org/mailinglogger/

For more information, please see:
http://www.simplistix.co.uk/software/python/mailinglogger
or
http://pypi.python.org/pypi/mailinglogger

cheers,

Chris



--
Simplistix - Content Management, Batch Processing  Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-announce-list

   Support the Python Software Foundation:
   http://www.python.org/psf/donations/


[ANNOUNCE] PySide 1.0.6 - Isolino: Python for Qt released!

2011-08-23 Thread Renato Araujo Oliveira Filho
The PySide team is proud to announce the monthly release version 1.0.6
of PySide project.

Major changes
==

. New documentation layout;
. Fixed some regressions from the last release (1.0.5);
. Optimizations during anonymous connection;

About PySide


PySide is the Nokia-sponsored Python Qt bindings project, providing access to
not only the complete Qt 4.7 framework but also Qt Mobility, as well as to
generator tools for rapidly generating bindings for any C++ libraries.

The PySide project is developed in the open, with all facilities you'd expect
from any modern OSS project such as all code in a git repository [2], an open
Bugzilla [3] for reporting bugs, and an open design process [4]. We welcome
any contribution without requiring a transfer of copyright.


List of bugs fixed
==

972 anchorlayout.py of  graphicsview example  raised a unwriteable
memory exception when exits
953 Segfault when QObject is garbage collected after QTimer.singeShot
951 ComponentComplete not called on QDeclarativeItem subclass
965 Segfault in QtUiTools.QUiLoader.load
958 Segmentation fault with resource files
944 Segfault on QIcon(None).pixmap()
941 Signals with QtCore.Qt types as arguments has invalid signatures
964 QAbstractItemView.moveCursor() method is missing
963 What's This not displaying QTableWidget column header information
as in Qt Designer
961 QColor.__repr__/__str__ should be more pythonic
960 QColor.__reduce__ is incorrect for HSL colors
950 implement Q_INVOKABLE
940 setAttributeArray/setUniformValueArray do not take arrays
931 isinstance() fails with Signal instances
928 100's of QGraphicItems with signal connections causes slowdown
930 Documentation mixes signals and functions.
923 Make QScriptValue (or QScriptValueIterator) implement the Python
iterator protocol
922 QScriptValue's repr() should give some information about its data
900 QtCore.Property as decorator
895 jQuery version is outdated, distribution code de-duplication
breaks documentation search
731 Can't specify more than a single 'since' argument
983 copy.deepcopy raises SystemError with QColor
947 NETWORK_ERR during interaction QtWebKit window with server
873 Deprecated methods could emit DeprecationWarning
831 PySide docs would have a Inherited by list for each class


Download


The files can be downloaded from PySide download page[2]


References
==

[1] http://lists.pyside.org/pipermail/pyside/2011-July/002648.html
[2] http://qt.gitorious.org/pyside
[3] http://bugs.openbossa.org/
[4] http://www.pyside.org/docs/pseps/psep-0001.html
[5] http://developer.qt.nokia.com/wiki/PySideDownloads

-- 
Renato Araujo Oliveira Filho
Instituto Nokia de Tecnologia - INdT
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: how to write the lambda expression in my tkinter ?

2011-08-23 Thread Chris Rebert
2011/8/22 守株待兔 1248283...@qq.com:
 from Tkinter import *
 fields = 'Name', 'Job', 'Pay'

 def fetch(event,entries):
    for entry in entries:
    print 'Input = %s' % entry.get()   # get text
    print  event.widget


 def makeform(root, fields):
    entries = []
    for field in fields:
    row = Frame(root)   # make a new row
    lab = Label(row, width=5, text=field)   # add label, entry
    ent = Entry(row)
    row.pack(side=TOP, fill=X)  # pack row on top
    lab.pack(side=LEFT)
    ent.pack(side=RIGHT, expand=YES, fill=X)# grow horizontal
    entries.append(ent)
    return entries

 if __name__ == '__main__':
    root = Tk()
    ents = makeform(root, fields)
    root.bind('Return', lambda event,entries=ents: fetch(event,entries))
    Button(root, text='Fetch', command= lambda event:fetch(event,entries)).pack(side=LEFT)
    root.mainloop()

 when you run it ,press enter ,you can get the value in the entry;when you
 click the  Button(Fetch),there is a wrong output ,i can't revise it,i know
 it is the  26  can't run ,how to fix it ?

 Button(root, text='Fetch', command= lambda event:fetch(event,entries)).pack(side=LEFT)

Problem 1: `entries` is undefined within the scope of the lambda; it's
not a parameter of the lambda, nor is it defined in any outer scope
that encloses the lambda. This will lead to a NameError. `ents` is /
would be within scope however...(*wink*)

Problem 2: Based on quick experimentation, Tkinter does not pass
`command` any arguments, yet your lambda has 1 required argument
(namely, `event`). This will cause a run-time error when the lambda is
called.

That should be enough to get you started.

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


Re: try... except with unknown error types

2011-08-23 Thread Paul Rubin
Chris Angelico ros...@gmail.com writes:
 Ehh, granted. Definitely a case of should. But certainly, there
 won't be an infinite number of new exceptions invented; 

Right, the number is finite, but the issue is that it's unknown.  It's
like never knowing whether you've fixed the last bug in a program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding modified methods from another class without subclassing

2011-08-23 Thread Steven D'Aprano
On Mon, 22 Aug 2011 11:08 pm John O'Hagan wrote:

 On Mon, 22 Aug 2011 15:27:36 +1000
 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote:
[...]
 # Untested
 class MySeq(object):
 methods_to_delegate = ('__getitem__', '__len__', ...)
 pitches = ...  # make sure pitches is defined
 def __getattr__(self, name):
 if name in self.__class__.methods_to_delegate:
 return getattr(self.pitches, name)
 return super(MySeq, object).__getattr__(self, name)
 # will likely raise AttributeError
 
 Thanks, this looks promising. I didn't know about __getattr__ or
 delegation. This example doesn't seem to work as is for special methods
 beginning with __ (e.g.: TypeError: object of type 'MyList' has no
 len()). It seems that __getattr__ is not called for special methods.

Ah yes, that would be a problem.

This recipe may help.

http://code.activestate.com/recipes/252151-generalized-delegates-and-proxies/


 Also, it doesn't immediately suggest to me a way of modifying method calls
 (maybe __setattr__?). 

What do you mean, modifying method calls?

__getattr__ doesn't know whether the method retrieved modifies the instance
or not. That's irrelevant.

__setattr__ is called when you say 

instance.attribute = value



 But it's certainly a neater way to get methods to 
 operate on the attribute. I'm looking into it, and delegation generally.
 
 However, I don't understand what the super call is doing. If the method
 isn't delegated, shouldn't it just fall back to getattr(self, name)?

getattr(self, name) will just call self.__getattr__(name) again, which will
call getattr, and so on... leading to RecursionError.



-- 
Steven

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


Re: CGI input: Filter dict.update() unwanted variables

2011-08-23 Thread Chris Angelico
On Mon, Aug 22, 2011 at 4:39 PM, Miki Tebeka miki.teb...@gmail.com wrote:
 You can check if there is a non-allowed variable and then return HTTP error.
 if set(form) - set(allowedVariables):
    print('Status: 406\n\n')
    raise SystemExit()


I'd be disinclined to do this; ignore unrecognized query variables,
but don't throw back an error. Sometimes it's convenient to let the
browser send a junk header that the server will ignore - helps with
integration with other systems. As long as you can be sure that the
script won't do the wrong thing, it should be fine to have an extra
bit of GET/POST data.

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


Re: try... except with unknown error types

2011-08-23 Thread Chris Angelico
On Tue, Aug 23, 2011 at 8:21 AM, Paul Rubin no.email@nospam.invalid wrote:
 Chris Angelico ros...@gmail.com writes:
 Ehh, granted. Definitely a case of should. But certainly, there
 won't be an infinite number of new exceptions invented;

 Right, the number is finite, but the issue is that it's unknown.  It's
 like never knowing whether you've fixed the last bug in a program.


Yeah. Oh, I know when I've fixed the last bug in a program. It's the
day the program gets deleted. Until then? Nope.

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


Re: Setting the time in Win7

2011-08-23 Thread Tim Golden

On 22/08/2011 20:42, Bob Greschke wrote:

Several people have been hacking away on this computer we are testing
on, so I'm not sure what settings -- other than all of them -- have been
messed with, but popen(time ...) seems to work, but system(time ...)
does not. I'm going to restore the machine to its original state and see
what happens.


Hoping that this helps: you can programatically set the system time
from within Python by using the pywin32 modules, or ctypes if you
prefer. The code below works for an already-elevated command prompt
by enabling the SystemTime privilege and (crudely) moving the time
forward by five minutes by way of showing what's happening before
resetting it back.

I've commented out the actual SetSystemTime calls just in case anyone
cuts-and-pastes indjudiciously. Ideally you should disable the
privilege afterwards but I've left that out so as not to clutter
the example.

code
import os, sys

import win32api
import win32security
import ntsecuritycon

hToken = win32security.OpenProcessToken (
  win32api.GetCurrentProcess (),
  ntsecuritycon.MAXIMUM_ALLOWED
)
time_privilege = win32security.LookupPrivilegeValue (None, 
win32security.SE_SYSTEMTIME_NAME)

win32security.AdjustTokenPrivileges (
  hToken, 0,
  [(time_privilege, win32security.SE_PRIVILEGE_ENABLED)]
)

current_time = win32api.GetSystemTime ()
print Current time:, current_time
new_time = list (current_time)
new_time[5] += 5
## print win32api.SetSystemTime (*new_time)
print Current time:, win32api.GetSystemTime ()
## print win32api.SetSystemTime (*current_time)
print Current time:, win32api.GetSystemTime ()

/code

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


Re: try... except with unknown error types

2011-08-23 Thread Steven D'Aprano
On Mon, 22 Aug 2011 04:26 am Paul Rubin wrote:

 The Erlang approach is tempting.  Don't catch the exception at all--just
 let the process crash, and restart it.  But that's a more heavyweight
 operation in Python.

You might be interested in this paper:

http://usenix.org/events/hotos03/tech/full_papers/candea/candea.pdf


-- 
Steven

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


Re: try... except with unknown error types

2011-08-23 Thread gene heskett
On Tuesday, August 23, 2011 04:42:04 AM Chris Angelico did opine:

 On Tue, Aug 23, 2011 at 8:21 AM, Paul Rubin no.email@nospam.invalid 
wrote:
  Chris Angelico ros...@gmail.com writes:
  Ehh, granted. Definitely a case of should. But certainly, there
  won't be an infinite number of new exceptions invented;
  
  Right, the number is finite, but the issue is that it's unknown.  It's
  like never knowing whether you've fixed the last bug in a program.
 
 Yeah. Oh, I know when I've fixed the last bug in a program. It's the
 day the program gets deleted. Until then? Nope.
 
 ChrisA

OTOH, ChrisA, I have it on good authority that no program is ever finished, 
until someone shoots the programmer.  :)

Cheers, gene
-- 
There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order.
-Ed Howdershelt (Author)
http://204.111.25.156:85/gene/

Practice is the best of all instructors.
-- Publilius
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try... except with unknown error types

2011-08-23 Thread Chris Angelico
On Tue, Aug 23, 2011 at 9:43 AM, gene heskett ghesk...@wdtv.com wrote:
 OTOH, ChrisA, I have it on good authority that no program is ever finished,
 until someone shoots the programmer.  :)


Correct, although I've had projects that were killed by changes to
requirements - such as my fantastic system for writing device drivers
that leveraged DEBUG.EXE to translate assembly code into machine code,
and a REXX script to handle jump labels and such. That project was
quite thoroughly finished on the day that I met nasm :)

But that's quite off-topic.

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


Why __slots__ slows down attribute access?

2011-08-23 Thread Jack
People have illusion that it is faster to visit the attribute defined
by __slots__ .
http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be

That is wrong. The following tests show it is slower.
__slots__ are implemented at the class level by creating descriptors
(Implementing Descriptors) for each variable name. It makes a little
bit slower.

So __slots__ just saves memory space by preventing creation of
__dict__ and __weakref__ on each instance, while sacrifice performance
and inheritance flexibility.
http://groups.google.com/group/comp.lang.python/msg/6623e8b94b6d6934


D:\d:\python-v3.1.2\python  -mtimeit -s class A(object): __slots__ =
('a', 'b', 'c') -s inst = A() inst.a=5; inst.b=6; inst.c=7
100 loops, best of 3: 0.237 usec per loop

D:\d:\python-v3.1.2\python  -mtimeit -s class A(object): pass -s
inst = A() inst.a=5 inst.b=6; inst.c=7
100 loops, best of 3: 0.214 usec per loop

D:\d:\python-v2.6.4\python  -mtimeit -s class A(object): __slots__ =
('a', 'b', 'c') -s inst = A() inst.a=5; inst.b=6; inst.c=7
100 loops, best of 3: 0.26 usec per loop

D:\d:\python-v2.6.4\python  -mtimeit -s class A(object): pass -s
inst = A() inst.a=5; inst.b=6; inst.c=7
100 loops, best of 3: 0.217 usec per loop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why __slots__ slows down attribute access?

2011-08-23 Thread Peter Otten
Jack wrote:

 People have illusion that it is faster to visit the attribute defined
 by __slots__ .
 http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be
 
 That is wrong. The following tests show it is slower.

Not so fast. Here's what I get (python2.6.4, 64 bit):

$ python  -mtimeit -s class A(object): __slots__ = ('a', 'b', 'c') -s 
inst = A() inst.a=5; inst.b=6; inst.c=7
100 loops, best of 3: 0.324 usec per loop

$ python  -mtimeit -s class A(object): pass -s inst = A() inst.a=5; 
inst.b=6; inst.c=7
100 loops, best of 3: 0.393 usec per loop

Now what?

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


Re: Why __slots__ slows down attribute access?

2011-08-23 Thread John-John Tedro
On Tue, Aug 23, 2011 at 12:26 PM, Peter Otten __pete...@web.de wrote:

 Jack wrote:

  People have illusion that it is faster to visit the attribute defined
  by __slots__ .
  http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be
 
  That is wrong. The following tests show it is slower.

 Not so fast. Here's what I get (python2.6.4, 64 bit):

 $ python  -mtimeit -s class A(object): __slots__ = ('a', 'b', 'c') -s
 inst = A() inst.a=5; inst.b=6; inst.c=7
 100 loops, best of 3: 0.324 usec per loop

 $ python  -mtimeit -s class A(object): pass -s inst = A() inst.a=5;
 inst.b=6; inst.c=7
 100 loops, best of 3: 0.393 usec per loop

 Now what?

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


This is what I get on a 64 bit Linux 2.6.39

script:
for v in 2.6 2.7 3.2; do
  python$v --version
  echo -n (slots)   = ;
  python$v -mtimeit -s class A(object): __slots__ = ('a', 'b', 'c') -s
inst = A() inst.a=5; inst.b=6; inst.c=7;
  echo -n (regular) = ;
  python$v -mtimeit -s class A(object): pass -s inst = A() inst.a=5;
inst.b=6; inst.c=7;
done

output:
Python 2.6.5
(slots)   = 100 loops, best of 3: 0.219 usec per loop
(regular) = 100 loops, best of 3: 0.231 usec per loop
Python 2.7.2
(slots)   = 100 loops, best of 3: 0.244 usec per loop
(regular) = 100 loops, best of 3: 0.285 usec per loop
Python 3.2
(slots)   = 100 loops, best of 3: 0.193 usec per loop
(regular) = 100 loops, best of 3: 0.224 usec per loop

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


Re: Why __slots__ slows down attribute access?

2011-08-23 Thread Adam Skutt
On Aug 23, 5:48 am, Jack wujac...@gmail.com wrote:
 People have illusion that it is faster to visit the attribute defined
 by __slots__ 
 .http://groups.google.com/group/comp.lang.python/msg/c4e413c3d86d80be

 That is wrong. The following tests show it is slower.

No, they don't really show anything.  The default clocks used by
timeit lack the resolution to measure such things accurately; you're
measuring various noise sources on your system.  The range of 100
trials of 1million iterations on my system is 70.3 ms, which is 70ns
when divided by a million, which is about the size of the difference
you show.  A 70ns average difference between iterations is trivially
attributable to noise on a modern machine.

Run enough trials or just wait for the moon to move a bit, and I
wouldn't be terribly surprised if you got difference results.
Rebooting your machine might be enough to do it.

Adam

 D:\d:\python-v3.1.2\python  -mtimeit -s class A(object): __slots__ =
 ('a', 'b', 'c') -s inst = A() inst.a=5; inst.b=6; inst.c=7
 100 loops, best of 3: 0.237 usec per loop

 D:\d:\python-v3.1.2\python  -mtimeit -s class A(object): pass -s
 inst = A() inst.a=5 inst.b=6; inst.c=7
 100 loops, best of 3: 0.214 usec per loop

 D:\d:\python-v2.6.4\python  -mtimeit -s class A(object): __slots__ =
 ('a', 'b', 'c') -s inst = A() inst.a=5; inst.b=6; inst.c=7
 100 loops, best of 3: 0.26 usec per loop

 D:\d:\python-v2.6.4\python  -mtimeit -s class A(object): pass -s
 inst = A() inst.a=5; inst.b=6; inst.c=7
 100 loops, best of 3: 0.217 usec per loop

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


is there any principle when writing python function

2011-08-23 Thread smith jack
i have heard that function invocation in python is expensive, but make
lots of functions are a good design habit in many other languages, so
is there any principle when writing python function?
for example, how many lines should form a function?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Peter Otten
smith jack wrote:

 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

Five ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Mel
smith jack wrote:

 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?

It's hard to discuss in the abstract.  A function should perform a 
recognizable step in solving the program's problem.  If you prepared to 
write your program by describing each of several operations the program 
would have to perform, then you might go on to plan a function for each of 
the described operations.  The high-level functions can then be analyzed, 
and will probably lead to functions of their own.

Test-driven development encourages smaller functions that give you a better 
granularity of testing.  Even so, the testable functions should each perform 
one meaningful step of a more general problem.

 for example, how many lines should form a function?
Maybe as few as one.

def increase (x, a):
return x+a

is kind of stupid, but a more complicated line

def expand_template (bitwidth, defs):
'''Turn Run-Length-Encoded list into bits.'''
return np.array (sum (([bit]*(count*bitwidth) for count, bit in 
defs), []), np.int8)

is the epitome of intelligence.  I wrote it myself.  Even increase might be 
useful:

def increase (x, a):
return x + a * application_dependent_quantity

`increase` has become a meaningful operation in the imaginary application 
we're discussing.


For an upper bound, it's harder to say.  If you read to the end of a 
function and can't remember how it started, or what it did in between, it's 
too big.  If you're reading on your favourite screen, and the end and the 
beginning are more than one page-scroll apart, it might be too big.  If it's 
too big, factoring it into sub-steps and making functions of some of those 
sub-steps is the fix.

Mel.

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


Re: is there any principle when writing python function

2011-08-23 Thread Roy Smith
In article mailman.346.1314100765.27778.python-l...@python.org,
 smith jack thinke...@gmail.com wrote:

 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

Enough lines to do what the function needs to do, but no more.

Seriously, break up your program into functions based on logical 
groupings, and whatever makes your code easiest to understand.  When 
you're all done, if your program is too slow, run it under the profiler.  
Use the profiling results to indicate which parts need improvement.

It's very unlikely that function call overhead will be a significant 
issue.  Don't worry about stuff like that unless the profiler shows its 
a bottleneck.  Don't try to guess what's slow.  My guesses are almost 
always wrong.  Yours will be too.

If your program runs fast enough as it is, don't even bother with the 
profiler.  Be happy that you've got something useful and move on to the 
next thing you've got to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Roy Smith
In article j305uo$pmd$1...@solani.org, Peter Otten __pete...@web.de 
wrote:

 smith jack wrote:
 
  i have heard that function invocation in python is expensive, but make
  lots of functions are a good design habit in many other languages, so
  is there any principle when writing python function?
  for example, how many lines should form a function?
 
 Five ;)

Five is right out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Ulrich Eckhardt
smith jack wrote:
 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

Don't compromise the design and clarity of your code just because you heard 
some rumors about performance. Also, for any performance question, please 
consult a profiler.

Uli

-- 
Domino Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Fwd: is there any principle when writing python function

2011-08-23 Thread Yaşar Arabacı
I accidentally sent below mail only to roy. Resending to groups.

-- Yönlendirilmiş ileti --
Kimden: Yaşar Arabacı yasar11...@gmail.com
Tarih: 23 Ağustos 2011 16:19
Konu: Re: is there any principle when writing python function
Kime: Roy Smith r...@panix.com


I don't see myself a good python programmer or anything, but just saying
what I do. I create function for each of the biggest code blocks that is
going to be executed more then once.


2011/8/23 Roy Smith r...@panix.com

 In article j305uo$pmd$1...@solani.org, Peter Otten __pete...@web.de
 wrote:

  smith jack wrote:
 
   i have heard that function invocation in python is expensive, but make
   lots of functions are a good design habit in many other languages, so
   is there any principle when writing python function?
   for example, how many lines should form a function?
 
  Five ;)

 Five is right out.
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
http://yasar.serveblog.net/




-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Hiding token information from users

2011-08-23 Thread Tobiah

I am making QR codes that cell phone users scan in order
to make use of an application.  Part of the information
is a token that needs to be passed on to the server, but
I'd rather not allow a person examining the QR code to
be able to see that plain bit of information.  I'd like
to scramble up the token so that the result:

1) takes up the same (near, or less) number of characters as the 
original token.


2) They key can be derived from the input, and vise versa.

3) The result is alphanumeric.

4) When one character changes in the source,
   many characters are likely to change in the
   result.

So if my token is:

mytoken2011

The result might be something like:

xm23ffz4uuw

Then
mytoken2012

might yield something very different:

d8ru3jdhvhd

I was thinking of just stringing up all letters and
numbers into a 'wheel' and doing an 18 char rotation on
the chars in the token, but that fails #4.  The secret is not like
the key to Fort Knox.  We would rather not have the plain
token out there, as it's internal business information,
but we don't have to protect the information at all costs.
Just making it really inconvenient to extract is fine.

Thanks,

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


PyDev 2.2.2 Released

2011-08-23 Thread Fabio Zadrozny
Hi All,

PyDev 2.2.2 has been released

Details on PyDev: http://pydev.org
Details on its development: http://pydev.blogspot.com

Release Highlights:
---

**IPython / Interactive console**

* IPython (0.10 or 0.11) is now used as the interactive console
backend if PyDev can detect it in the PYTHONPATH.
* While waiting for the output of a command, intermediary results
are printed in the console.
* ANSI color codes are supported in the interactive console.

**Code Analysis**

* Reporting variables that shadow builtins as warnings.
* Fixed issue where __dict__ was not found.

**Code completion**

* Aliases have a better treatment (i.e.: unittest.assertEqual will
show the proper type/parameters).
* Improved support for analyzing function builtins where the
return type is known (i.e.: open, str.split, etc).

**Debugger**

* When doing a remote debug session, if the files cannot be found
in the local filesystem, PyDev will ask for files in the remote
debugger.

**Editor**

* Files without extension that have a python shebang (e.g.:
#!/usr/bin/python in the first line) are automatically opened with the
PyDev editor (in the PyDev Package Explorer).

**Django**

* When the shell command is used in the django custom commands,
PyDev no longer uses 100% cpu while it doesn't complete.

**Others**

* Fixed issue where the * operator was not properly formatted.
* When the quick outline dialog is deactivated, it's closed.
* Fixed heuristic for finding position for local import.
* Fixed compare editor issue with Eclipse 3.2.
* Fixed integration issue with latest PyLint.
* Fixed deadlock issue on app engine manage window.
* More options added to configure the automatic deletion of .pyc
files (delete always, never delete, delete only on .py delete).



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python, Jython
and IronPython development -- making Eclipse a first class Python IDE
-- It comes with many goodies such as code completion, syntax
highlighting, syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

Appcelerator
http://appcelerator.com/

Aptana
http://aptana.com/

PyDev - Python Development Environment for Eclipse
http://pydev.org
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Windows Extensions for Mac

2011-08-23 Thread Christian Heimes
Am 22.08.2011 15:07, schrieb johnny.venter:
 Chris, thank you for the information.  Focusing on Active Directory, I 
 reviewed the info at the following site: 
 http://technet.microsoft.com/en-us/library/cc961766.aspx
 
 Based on this, I need to find a module that implements the LDAP APIs.  By 
 default, it does not appear that Python can speak this language, I am using 
 version 2.6.1.  The module I found is Python-LDAP 
 (http://www.python-ldap.org/).
 
 Does anyone have experience using this?

LDAP is a protocol, not a language. You are right, LDAP isn't part of
the Python standard library. The python-ldap extensions works well with
Active Directory. I've used it to write an authentication and
authorisation layer for our application.

A word of warning: LDAP isn't trivial and AD has its quirks, too. It's
going to take you a while to understand its concepts.

Christian

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


Directly executing from an egg

2011-08-23 Thread RVince
I have created an egg file with one source file in it, hello.py (I
just want to go through the entire uild/install/execute cycle using
egg files). I create it fine, and now I want to execute the eg file
directly (i.e. run it without unpacking or easy_install'ing it). So
when I invoke it from the directory the egg is in with:

python 'hello-1.0-py2.6.egg

I get:

can't find '__main__.py' in 'hello-1.0-py2.6.egg'

How do I remedy this? I've looked through the docs but it seems
ambiguous on this point to me. Below is the setup section from my
setup.py which I used to create this egg. Thank you, RVince

setup(
name='hello',
version='1.0',
description='',
author='',
author_email='',
install_requires=[
SQLAlchemy=0.4,
psycopg2,
],
zip_safe=False,
entry_points=
[hello]
hello = hello:hello_app
,
)
-- 
http://mail.python.org/mailman/listinfo/python-list


why i cannot invoke python script using command line?

2011-08-23 Thread smith jack
but i can invoke it in eclipse, what's wrong?
the script refered to another python script in eclipse project.

f:\project\src\a.py
f:\project\src\lib\b.py

there is such lines in a.py
from lib import b

i can invoke a.py very well in eclipse

but failed when using python f:\project\src\a.py, what's wrong?
(the error msg shows a.py cannot find b.py) , what should i do in
order to run a.py using command line?
-- 
http://mail.python.org/mailman/listinfo/python-list


Methods on file-like objects can only used once on one object?

2011-08-23 Thread Yingjie Lin
Hi Python users,

I just realize that my post yesterday shouldn't be specifically for mechanize. 
It should be a general question for file-like objects.

 f = open('my_file.txt')
 print f.readlines()
( prints a list of strings
 print f.readlines()
[]

There are quite a few methods for file-like objects that can only be used once 
on one object. If I prefer to use some of these methods on one object, one 
after another, like:

f.readlines()
f.read()
...

What should I do? Thank you.

- Yingjie







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


Re: why i cannot invoke python script using command line?

2011-08-23 Thread John Gordon
In mailman.350.1314108212.27778.python-l...@python.org smith jack 
thinke...@gmail.com writes:

 but i can invoke it in eclipse, what's wrong?
 the script refered to another python script in eclipse project.

 f:\project\src\a.py
 f:\project\src\lib\b.py

 there is such lines in a.py
 from lib import b

 i can invoke a.py very well in eclipse

 but failed when using python f:\project\src\a.py, what's wrong?
 (the error msg shows a.py cannot find b.py) , what should i do in
 order to run a.py using command line?

What is your PYTHONPATH environment variable setting?

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, The Gashlycrumb Tinies

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


Re: why i cannot invoke python script using command line?

2011-08-23 Thread Chris Angelico
On Tue, Aug 23, 2011 at 3:03 PM, smith jack thinke...@gmail.com wrote:
 but failed when using python f:\project\src\a.py, what's wrong?
 (the error msg shows a.py cannot find b.py) , what should i do in
 order to run a.py using command line?


From the sound of things, your working directory is not
f:\project\src. I recommend you either:

1) Change to that directory first:
cd f:\project\src
python a.py

Or 2) Add to your import path inside a.py:
import sys
sys.path.append(rf:\project\src)

Either method should solve the problem.

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


Re: Hiding token information from users

2011-08-23 Thread Ian Kelly
How many of these codes do you need, and do they only need to be decrypted
at a central server? You might be able to just create random strings of
whatever form you want and associate them with the tokens in a database.
Then they will be completely opaque.
-- 
http://mail.python.org/mailman/listinfo/python-list


incorporate png/ico to exe and use it in application

2011-08-23 Thread Peter Irbizon
hello,

I am zsing py2exe to compile exe files. I would like to incorporate png and
icon file into exe and then use it during program run (to show it in about
dialog and system tray). How can I do it?

For example now I
use self.staticon.set_from_file(os.path.join(module_path(), icon.ico)) but
I would like to prevent user from changeing this icon. Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Steven D'Aprano
smith jack wrote:

 i have heard that function invocation in python is expensive, 

It's expensive, but not *that* expensive. Compare:

[steve@sylar ~]$ python3.2 -m timeit 'x = abc.upper()'
100 loops, best of 3: 0.31 usec per loop
[steve@sylar ~]$ python3.2 -m timeit -s 'def f():
return abc.upper()' 'f()'
100 loops, best of 3: 0.53 usec per loop

So the function call is nearly as expensive as this (very simple!) sample
code. But in absolute terms, that's not very expensive at all. If we make
the code more expensive:

[steve@sylar ~]$ python3.2 -m timeit '(abc*1000)[2:995].upper().lower()'
1 loops, best of 3: 32.3 usec per loop
[steve@sylar ~]$ python3.2 -m timeit -s 'def f(): return (abc*1000
[2:995].upper().lower()' 'f()'
1 loops, best of 3: 33.9 usec per loop

the function call overhead becomes trivial.

Cases where function call overhead is significant are rare. Not vanishingly
rare, but rare enough that you shouldn't worry about them.


 but make 
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

About as long as a piece of string.

A more serious answer: it should be exactly as long as needed to do the
smallest amount of work that makes up one action, and no longer or shorter.

If you want to maximise the programmer's efficiency, a single function
should be short enough to keep the whole thing in your short-term memory at
once. This means it should consist of no more than seven, plus or minus
two, chunks of code. A chunk may be a single line, or a few lines that
together make up a unit, or if the lines are particularly complex, *less*
than a line.

http://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two
http://www.codinghorror.com/blog/2006/08/the-magical-number-seven-plus-or-minus-two.html

(Don't be put off by the use of the term magical -- there's nothing
literally magical about this. It's just a side-effect of the way human
cognition works.)

Anything longer than 7±2 chunks, and you will find yourself having to scroll
backwards and forwards through the function, swapping information into your
short-term memory, in order to understand it.

Even 7±2 is probably excessive: I find that I'm most comfortable with
functions that perform 4±1 chunks of work. An example from one of my
classes:

def find(self, prefix):
Find the item that matches prefix.
prefix = prefix.lower()  # Chunk #1
menu = self._cleaned_menu  # Chunk #2
for i,s in enumerate(menu, 1):  # Chunk #3
if s.lower().startswith(prefix):
return i
return None  # Chunk #4

So that's three one-line chunks and one three-line chunk.



-- 
Steven

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


Re: Methods on file-like objects can only used once on one object?

2011-08-23 Thread darnold
On Aug 23, 9:21 am, Yingjie Lin yingjie@mssm.edu wrote:
 Hi Python users,

 I just realize that my post yesterday shouldn't be specifically for 
 mechanize. It should be a general question for file-like objects.

  f = open('my_file.txt')
  print f.readlines()

         ( prints a list of strings print f.readlines()

 []

 There are quite a few methods for file-like objects that can only be used 
 once on one object. If I prefer to use some of these methods on one object, 
 one after another, like:

 f.readlines()
 f.read()
 ...

 What should I do? Thank you.

 - Yingjie

Each of those calls consumes the entire file, leaving the file pointer
at end-of-file. to reset the file pointer back to the beginning of the
file and enable re-reading, use f.seek(0) .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hiding token information from users

2011-08-23 Thread Tobiah

On 08/23/2011 08:08 AM, Ian Kelly wrote:

How many of these codes do you need, and do they only need to be
decrypted at a central server? You might be able to just create random
strings of whatever form you want and associate them with the tokens in
a database. Then they will be completely opaque.



The tokens have a year portion that increments each year, and
the base portion of the token will be created newly in accordance
with new accounts that we take on.  I really need some sort of
algorithm that will let me take an unknown string and generate
the encrypted bit on the fly.

Thanks,

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


Re: Methods on file-like objects can only used once on one object?

2011-08-23 Thread Paul Kölle

Am 23.08.2011 16:21, schrieb Yingjie Lin:

Hi Python users,

[snip]


There are quite a few methods for file-like objects that can only be used once 
on one object. If I prefer to use some of these methods on one object, one 
after another, like:

f.readlines()
f.read()
...

What should I do? Thank you.
use f.seek(0) between calls. The python documentation will educate you 
about the details.


hth
 Paul

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


Re: Methods on file-like objects can only used once on one object?

2011-08-23 Thread Steven D'Aprano
Yingjie Lin wrote:

 Hi Python users,
 
 I just realize that my post yesterday shouldn't be specifically for
 mechanize. It should be a general question for file-like objects.
 
 f = open('my_file.txt')
 print f.readlines()
 ( prints a list of strings
 print f.readlines()
 []

Once you've read the file, the file pointer is now at the end of the file.
To go back to the beginning of the file and read it again, you have to use
the seek method:

f.seek(0)

But better is to not read the file twice:


f = open('my_file.txt')
lines = f.readlines()
print lines
print lines
print lines
print lines
f.close()

There's no need to read the lines again unless you expect that the file has
changed.


-- 
Steven

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


Windows No-Install Distribution?

2011-08-23 Thread Eric Lemings
Hi,

I would like to create/find a Python 3.x distribution that can be
redeployed simply by copying a directory of required files; i.e.
without the need for actually installing an MSI, modifying Windows
registry entries, etc.  First of all, will Python even work on Windows
simply by copying files from one system to another?  If so, does such
a no-install distribution already exist?  If not, what are the
minimum set of Python 3.x files from a standard Windows Python
installation required for proper/normal operation?

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


Re: Windows No-Install Distribution?

2011-08-23 Thread Redcat
I haven't tried it myself yet, but might http://www.portablepython.com/ 
be what you're looking for?


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


aboutdialog space between program name/version and logo

2011-08-23 Thread Peter Irbizon
Hello,

please how can i set space between program name/version and logo in this
code? thanks

about = gtk.AboutDialog()
about.set_program_name(name)
about.set_version(0.0.1)
about.set_logo(gtk.gdk.pixbuf_new_from_file(file.png))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why i cannot invoke python script using command line?

2011-08-23 Thread Steven D'Aprano
smith jack wrote:

 but i can invoke it in eclipse, what's wrong?
 the script refered to another python script in eclipse project.
 
 f:\project\src\a.py
 f:\project\src\lib\b.py
 
 there is such lines in a.py
 from lib import b
 
 i can invoke a.py very well in eclipse
 
 but failed when using python f:\project\src\a.py, what's wrong?
 (the error msg shows a.py cannot find b.py) , what should i do in
 order to run a.py using command line?

The import statement doesn't search the entire hard drive. It only searches
the places in sys.path. You can modify sys.path either programmatically, or
by adding things to the environment variable PYTHONPATH.

Eclipse may be modifying the path so that it works in Eclipse. My
recommendation is to either:

(1) Use a flatter layout, like:

f:\project\src\a.py
f:\project\src\b.py

and cd into f:\project\src\ before executing python a.py

OR

(2) learn how to use packages, and put a and b into a package;

OR 

(3) Inside script a.py, add this to the start of the file:


import os
import sys
import __main__
location = os.path.split(__main__.__file__)[0]
location = os.path.join(location, 'lib')
sys.path.append(location)


-- 
Steven

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


Re: Setting the time in Win7

2011-08-23 Thread Bob Greschke

On 2011-08-23 02:26:38 -0600, Tim Golden m...@timgolden.me.uk said:


On 22/08/2011 20:42, Bob Greschke wrote:

Several people have been hacking away on this computer we are testing
on, so I'm not sure what settings -- other than all of them -- have been
messed with, but popen(time ...) seems to work, but system(time ...)
does not. I'm going to restore the machine to its original state and see
what happens.


Hoping that this helps: you can programatically set the system time
from within Python by using the pywin32 modules, or ctypes if you
prefer. The code below works for an already-elevated command prompt
by enabling the SystemTime privilege and (crudely) moving the time
forward by five minutes by way of showing what's happening before
resetting it back.

I've commented out the actual SetSystemTime calls just in case anyone
cuts-and-pastes indjudiciously. Ideally you should disable the
privilege afterwards but I've left that out so as not to clutter
the example.

code
import os, sys

import win32api
import win32security
import ntsecuritycon

hToken = win32security.OpenProcessToken (
   win32api.GetCurrentProcess (),
   ntsecuritycon.MAXIMUM_ALLOWED
)
time_privilege = win32security.LookupPrivilegeValue (None, 
win32security.SE_SYSTEMTIME_NAME)

win32security.AdjustTokenPrivileges (
   hToken, 0,
   [(time_privilege, win32security.SE_PRIVILEGE_ENABLED)]
)

current_time = win32api.GetSystemTime ()
print Current time:, current_time
new_time = list (current_time)
new_time[5] += 5
## print win32api.SetSystemTime (*new_time)
print Current time:, win32api.GetSystemTime ()
## print win32api.SetSystemTime (*current_time)
print Current time:, win32api.GetSystemTime ()

/code

TJG


Oooo.  Now I can be dangerous.  We kinda also solved the whole thing 
for us (just a few minutes ago) by checking the checkbutton Run as 
administrator in the Properties, Compatibility tab, for python.exe and 
pythonw.exe.  The account is an Administrator, so it's OK for this.


I thought there must be a way through pywin32, but I don't know much of 
anything about Windows API calls.  I have a Windows Programming book 
collecting dust somewhere...


Thanks!

Bob

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


Re: Methods on file-like objects can only used once on one object?

2011-08-23 Thread Grant Edwards
On 2011-08-23, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote:
 Yingjie Lin wrote:

 Hi Python users,
 
 I just realize that my post yesterday shouldn't be specifically for
 mechanize. It should be a general question for file-like objects.
 
 f = open('my_file.txt')
 print f.readlines()
 ( prints a list of strings
 print f.readlines()
 []

 Once you've read the file, the file pointer is now at the end of the file.
 To go back to the beginning of the file and read it again, you have to use
 the seek method:

 f.seek(0)

It's too bad Python doesn't support the f.rewind() spelling for that
operation.  Rewinding disk files always made me smile...

-- 
Grant Edwards   grant.b.edwardsYow! Did I say I was
  at   a sardine?  Or a bus???
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows No-Install Distribution?

2011-08-23 Thread Andrew Berg
On 2011.08.23 10:29 AM, Eric Lemings wrote:
 Hi,
 
 I would like to create/find a Python 3.x distribution that can be
 redeployed simply by copying a directory of required files; i.e.
 without the need for actually installing an MSI, modifying Windows
 registry entries, etc.  First of all, will Python even work on Windows
 simply by copying files from one system to another?  If so, does such
 a no-install distribution already exist?  If not, what are the
 minimum set of Python 3.x files from a standard Windows Python
 installation required for proper/normal operation?
I unpacked the 32-bit version of CPython 3.2 from its installer into a
folder and it seems to work. I haven't done any real testing, but it
works for me (mainly I just need to have the files needed to build
32-bit frozen binaries with cx_Freeze).

-- 
CPython 3.2.1 | Windows NT 6.1.7601.17592 | Thunderbird 5.0
PGP/GPG Public Key ID: 0xF88E034060A78FCB
-- 
http://mail.python.org/mailman/listinfo/python-list


truncating strings

2011-08-23 Thread Roy Smith
I want to log a string but only the first bunch of it, and add ...
to the end if it got truncated.  This certainly works:

  log_message = message
  if len(log_message) = 50:
log_message = log_message[:50] + '...'
  logger.error(FAILED: '%s', '%s', %s, %s % (log_message,
route, params, e.code))

but it bugs me that there should be some cleaner way to do this.  I'm
fantasizing about something along the lines of:

  logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
route, params, e.code))

does anything like this exist?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows No-Install Distribution?

2011-08-23 Thread Eric Lemings
On Aug 23, 9:31 am, Redcat red...@streemit.net wrote:
 I haven't tried it myself yet, but mighthttp://www.portablepython.com/
 be what you're looking for?

Almost except it contains additional Python packages that I'm not
interested in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hiding token information from users

2011-08-23 Thread Steven D'Aprano
Tobiah wrote:

 I really need some sort of
 algorithm that will let me take an unknown string and generate
 the encrypted bit on the fly.

Google broken for you? *wink*

Seriously, there are about a bazillion algorithms for encrypting and
obfuscating strings. Depending on your security requirements, that can be
as simple as rot13 and as complex as blowfish (or even more so).

If it helps, I have a module that implements a selection of classical (i.e.
insecure) encryption algorithms:

http://pypi.python.org/pypi/obfuscate


Earlier, you said:

 The secret is not like
 the key to Fort Knox.  We would rather not have the plain
 token out there, as it's internal business information,
 but we don't have to protect the information at all costs.
 Just making it really inconvenient to extract is fine.

I don't understand the point of this. What could your users do with the
plain token that they shouldn't? I don't see why, if it's not worth
encrypting properly, why it's worth obfuscating it at all.


-- 
Steven

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


Re: Hiding token information from users

2011-08-23 Thread Tobiah

On 08/23/2011 09:55 AM, Steven D'Aprano wrote:

Tobiah wrote:


I really need some sort of
algorithm that will let me take an unknown string and generate
the encrypted bit on the fly.


Google broken for you? *wink*


I had some requirements in the OP that I could not
find a solution for.


Seriously, there are about a bazillion algorithms for encrypting and
obfuscating strings. Depending on your security requirements, that can be
as simple as rot13 and as complex as blowfish (or even more so).

If it helps, I have a module that implements a selection of classical (i.e.
insecure) encryption algorithms:

http://pypi.python.org/pypi/obfuscate


Earlier, you said:


The secret is not like
the key to Fort Knox.  We would rather not have the plain
token out there, as it's internal business information,
but we don't have to protect the information at all costs.
Just making it really inconvenient to extract is fine.


I don't understand the point of this. What could your users do with the
plain token that they shouldn't? I don't see why, if it's not worth
encrypting properly, why it's worth obfuscating it at all.


The token ends up translating into the name of a database on our
server.  With that information alone, it's difficult to imagine
a serious vulnerability, yet we just thought it would be worth
it to disguise the plain text.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Seebs
On 2011-08-23, smith jack thinke...@gmail.com wrote:
 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?

Lots of them.  None of them have to do with performance.

 for example, how many lines should form a function?

Between zero (which has to be written pass) and a few hundred.  Usually
closer to the lower end of that range.  Occasionally outside it.

Which is to say:  This is the wrong question.

Let us give you the two laws of software optimization.

Law #1:  Don't do it.

If you try to optimize stuff, you will waste a ton of time doing things that,
it turns out, are unimportant.

Law #2: (Experts only.)  Don't do it yet.

You don't know enough to optimize this yet.

Write something that does what it is supposed to do and which you understand
clearly.  See how it looks.  If it looks like it is running well enough,
STOP.  You are done.

Now, if it is too slow, and you are running it on real data, NOW it is time
to think about why it is slow.  And the solution there is not to read abstract
theories about your language, but to profile it -- actually time execution and
find out where the time goes.

I've been writing code, and making it faster, for some longish period of time.
I have not yet ever in any language found cause to worry about function call
overhead.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread rantingrick
On Aug 23, 6:59 am, smith jack thinke...@gmail.com wrote:
 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

Everyone here who is suggesting that function bodies should be
confined to ANY length is an idiot. The length of a functions code
block is inconsequential. Don't worry if it too small or too big. It's
not the size that matters, it's the motion of the sources ocean!

A good function can be one line, or a hundred lines. Always use
comments to clarify code and NEVER EVER create more functions only for
the sake of short function bodies, WHY, because all you do is move
confusion OUT OF the function body and INTO the module/class body.

Energy can neither be created nor be destroyed: it can only be
transformed from one state to another

http://en.wikipedia.org/wiki/Conservation_of_energy
https://sites.google.com/site/thefutureofpython/

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


Re: truncating strings

2011-08-23 Thread Chris Rebert
On Tue, Aug 23, 2011 at 9:29 AM, Roy Smith r...@panix.com wrote:
 I want to log a string but only the first bunch of it, and add ...
 to the end if it got truncated.  This certainly works:

          log_message = message
          if len(log_message) = 50:
            log_message = log_message[:50] + '...'
          logger.error(FAILED: '%s', '%s', %s, %s % (log_message,
 route, params, e.code))

 but it bugs me that there should be some cleaner way to do this.  I'm
 fantasizing about something along the lines of:

          logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
 route, params, e.code))

 does anything like this exist?

You can specify a maximum width to truncate the string to, but I don't
see any built-in way to add an elision indication (e.g. ...).

 %.4s % spam and eggs
'spam'
 {:.4s}.format(spam and eggs)
'spam'

You could define something to wrap strings and override __format__()
or similar, but that seems like overkill.

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


Re: try... except with unknown error types

2011-08-23 Thread Paul Rubin
gene heskett ghesk...@wdtv.com writes:
 OTOH, ChrisA, I have it on good authority that no program is ever finished, 
 until someone shoots the programmer.  :)

The way I heard it was software is never finished until the last user
is dead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extended slicing and negative stop value problem

2011-08-23 Thread Ian Kelly
On Aug 21, 2011 1:34 PM, Max maxmo...@gmail.com wrote:
  a[0:11][::-1]
  # Instead of a[10:-1:-1], which looks like it should work, but doesn't.

 It works nicely, but it is 1.3 times slower in my code (I am surprised
 the interpreter doesn't optimize this).

Have you tried reverse()? I haven't timed it, but since it merely creates an
iterator rather than a second copy, you may get better performance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread Terry Reedy

On 8/23/2011 7:59 AM, smith jack wrote:

i have heard that function invocation in python is expensive,


That comes into play when chosing between

list2 = map(lambda x: 2*x, list1) # versus
list2 = [2*x for x in list1]

It also comes into play when choosing between looping with recursion 
(function calls) versus looping with iteration (while/for).  In Python, 
the iteration is faster, while some functional languages omit looping 
syntax constructs and perhaps auto-translate some recursion to iteration.



but makelots of functions are a good design habit in many other languages,


Same for Python, with the exceptions noted above of avoiding trivial 
one-use functions when there is an alternative.



is there any principle when writing python function?


Same as usual. Functions define new words and create new abstractions 
than encapsulate a unit of computation.



for example, how many lines should form a function?


1 to many, as long as the 1 is more complex than 2*x, unless the trivial 
function is required for a callback. I doubt the stdlib has many defs 
longer than 100 lines.


Try the following: complex enough that the function call overhead does 
not matter; simple enough to be understood as a unit.


I just came up with the following hypothesis: the complexity of a 
function is related to the number of *different* functions used to 
define it:

x = a*b + c/d - e**f
is more complex (harder to understand) than
x = a + b + c + d + e + f

For this purpose, different statememts count as functions (and indeed, 
they translate to bytecode functions. So:

for i in iterable:
   if f(i):
  print i
is more complex than
a = 1
b = 2
c = 3
d = 4

People can retain at most about 10 different things in short term 
memory. So perhaps 10 different 'functions' within a function, or at 
least a commented block, is enough.


--
Terry Jan Reedy

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


Re: is there any principle when writing python function

2011-08-23 Thread Terry Reedy

On 8/23/2011 11:22 AM, Steven D'Aprano wrote:


Even 7±2 is probably excessive: I find that I'm most comfortable with
functions that perform 4±1 chunks of work. An example from one of my
classes:

 def find(self, prefix):
 Find the item that matches prefix.
 prefix = prefix.lower()  # Chunk #1
 menu = self._cleaned_menu  # Chunk #2
 for i,s in enumerate(menu, 1):  # Chunk #3
 if s.lower().startswith(prefix):
 return i
 return None  # Chunk #4

So that's three one-line chunks and one three-line chunk.


In terms of different functions performed (see my previous post), I see
  attribute lookup
  assignment
  enumerate
  sequence unpacking
  for-looping
  if-conditioning
  lower
  startswith
  return
That is 9,  which is enough.

--
Terry Jan Reedy


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


reading and writing files

2011-08-23 Thread Adrián Monkas
Hi.
I`ve been trying to copy a long text from one file to another but it always
copied me just a small part.
I would be glad if you can help me or explain which is my error.
Thanks

--
def runMenu():

print \nMENU
print   1) Copiar
print   0) Exit

response = int( raw_input().strip() )

if response == 1:
print Copiar
try:
print Abro Archivo Origen
archivo=open(D:\Boot.txt,r)
print Name of the file: , archivo.name
print Closed or not : , archivo.closed
print Opening mode : , archivo.mode

print ORIGEN---
print archivo.read()
print -
archivo.seek(0, 0)

print Abro Archivo Destino
archivo2=open(D:\Copia.txt,w+)
print Name of the file: , archivo2.name
print Closed or not : , archivo2.closed
print Opening mode : , archivo2.mode



archivo2.write(archivo.read())

archivo2.seek(0, 0)
print -DESTINO-
print archivo2.read()
print -
archivo.close()
archivo2.close()

except IOError:
print (I/O Error de Lectura)
else:
print Lectura OK

elif response == 0:
#device.close()
print Exit

return response

def main():
print main
while(1):
if runMenu() == 0: break

main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows No-Install Distribution?

2011-08-23 Thread Stephen Hansen
On 8/23/11 8:29 AM, Eric Lemings wrote:
 I would like to create/find a Python 3.x distribution that can be
 redeployed simply by copying a directory of required files; i.e.

Just take the default installer, install it, and then check the Python
directory: does it have the python DLL? If not, go look into the
system32 directory, grab it, drop it in the Python directory. (If you
installed for all-users this will happen,

Now copy/zip/whatever that Python directory to another machine where it
was not installed. It'll work fine.

You'll have to explicitly provide the path to the Python.exe of course;
you can't just double-click on a .py or run 'python blah.py', but if
your shortcuts/whatever all do C:\Where\You\Installed\Python.exe,
everything should just work.

We do that at work and never run into any trouble. (We actually provide
a MSI but only for convenience of customers who want to auto-install via
Group Policy).

In most situations, Python's good at finding itself, i.e. where the
python.exe is actually located -- and it boostraps the location of
everything else based on that.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for python/pyramid developers for a project

2011-08-23 Thread Mathew
Hello,

My company an ISP is looking to build an administrative webapp
dashboard for our underlying systems. We are looking to hire a
developer(s) immediately. We would prefer the application be built on
python with a popular framework such as pyramid. This position is a
contract position paid hourly (35-45$ based on experience). Please
email me if you are interested and attach any relevant past projects/
screenshots that were built on pyramid/python.


email: mzummo at [gmail.com]
skype  mzummo 


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


Re: is there any principle when writing python function

2011-08-23 Thread rantingrick
On Aug 23, 1:29 pm, Terry Reedy tjre...@udel.edu wrote:

 In terms of different functions performed (see my previous post), I see
    attribute lookup
    assignment
    enumerate
    sequence unpacking
    for-looping
    if-conditioning
    lower
    startswith
    return
 That is 9,  which is enough.


attribute lookup - inspection
assignment - ditto
enumerate - enumeration
sequence unpacking - parallel assignment
for-looping - cycling
if-conditioning - logic
lower - mutation (don't try to argue!)
startswith - boolean-logic
return - exiting (although all exits require an entrance!)
omitted: documenting, referencing, -presumptuousness-

pedantic-ly yours, rr
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions ( answers) about object, type, builtin types, class, metaclass and __getattribute__

2011-08-23 Thread Amirouche B.
On Aug 22, 1:57 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 The relationship between type and object is somewhat special, and needs to
 be bootstrapped by the CPython virtual machine.

Since you are talking  about CPython, I'm wondering how it is
bootstraped since you can easly reference PyType in PyObject that part
is not hard.

  2) type is its own metaclass : type(type) is type ?

 Yes. Another bit of bootstrapping that the compiler does.

self reference is easy same as referencing PyType from PyObject and
PyObject from PyType.

  5) type(any_object) == last_metaclass_..., which is, most of the time,
  type ?

 I'm not sure what you mean by last_metaclass. But no. The type of an
 object is its class:

see this code for example proove my point:

class meta_a(type):
def __new__(cls, *args, **kwargs):
return type.__new__(cls, *args, **kwargs)  # see (¤)


class meta_b(meta_a):
def __new___(cls, *args, **kwargs):
return meta_a.__new__(cls, *args, **kwargs) # same as above


class ClassWithTypeMetaA(object):
__metaclass__ = meta_a


class ClassWithTypeMetaB(object):
__metaclass__ = meta_b


type(ClassWithTypeMetaA) == meta_a
type(ClassWithTypeMetaB) == meta_b


[¤] super call doesn't work here, anyone can say why ?

Regards,

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


Re: truncating strings

2011-08-23 Thread Seebs
On 2011-08-23, Roy Smith r...@panix.com wrote:
 I want to log a string but only the first bunch of it, and add ...
 to the end if it got truncated.  This certainly works:

   logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
 route, params, e.code))

 does anything like this exist?

%.50s

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions ( answers) about object, type, builtin types, class, metaclass and __getattribute__

2011-08-23 Thread Amirouche B.
On Aug 22, 5:41 pm, Stephen Hansen me+list/pyt...@ixokai.io wrote:
  3) object's type is type : object.__class__ is type
  4) type parent object is object : type.__bases__ == (object,)

 Saying type and parent and the like for new-style classes is
 something of a misnomer. For type and object, these things aren't
 constructed like this.

 What you have here is technically true if you go poke at it in the
 interpreter, but it doesn't really /mean/ anything because its not how
 these objects came to be and is circular and a bit confusing. These
 fundamental objects are created special.

The code snippet is here to illustrate how it is visible in the
interpreter. But
you are right.

  2) type is its own metaclass : type(type) is type ?

 Only in a purely theoretical way. It doesn't actually mean anything;
 moreover, type(something) is NOT how you determine somethings metaclass.
 Its how you determine somethings type.

see the answer to Steven D'Aprano. type(class_object) ==
a_meta_class_object


 The two concepts may be very distinct. Lots of things don't have
 metaclasses.

All object in new style class have a metaclass at least type.


  3) object's metaclass is type ?

 Again, only theoretically.

and again the famous bootstrapping make it like type created object.
From the
outside world of the Python implementation object looks like a type
instance.


  5) type(any_object) == last_metaclass_..., which is, most of the time,
  type ?

 Not necessarily at all. In fact, there is no way I'm aware of to
 determine if a metaclass was involved in a classes construction unless
 said metaclass wants to provide such a mechanism.

 Metaclasses are kind of a  hack. They are a way to hook into the class
 construction that's normally done and do something, anything you want,
 (even hijack the whole procedure and NOT construct a class at all, but
 play a song if you want) before its all finished.

 For example, this is a metaclass I've used:

 PageTypes = {}

 class _PageRegistration(type):
 def __new__(cls, name, bases, dct):
 klass = type.__new__(cls, name, bases, dct)
 typename = name[:-9].lower()
 if not typename:
 typename = None

 PageTypes[typename] = klass
 klass.Type = typename

 return klass

 class QueuePage(sc.SizedPanel):
 __metaclass__ = _PageRegistration

 Note, the fact that my _PageRegistration metaclass inherits is itself a
 class which inherits from type is just one convenient way to write
 metaclasses. It could as simply have been just a function.

 Metaclasses are somewhat poorly named in that they are really, creation
 hooks.


It the same issue in django, views are only function, until you need
complex
behavior and you want a namespace to put everything in it. IMO
that's why class
based views exists for complex cases. That said being able to declare
a metaclass
only as a functions is neat.


  C) type vs class
  

  1) Type is the metaclass of most classes

 Yes and no. Yes, in that most classes are created using the default
 mechanism inside CPython. The class body is executed in a scope, the
 resulting dictionary is bound to a new class object, bases and the like
 are set, and such.

 No in that it really just, IIUC, skips the whole metaclass part of the
 process because this 'default mechanism' doesn't need to call out into
 other code to do its job. At least, I think-- May be wrong here,
 metaclasses are something of a dark voodoo and I'm not 100% entirely
 familiar with the internal workings of CPython.

 But functionally, a metaclass is the chunk of code responsible for the
 actual physical construction of the class object.

For me it takes some variables, namely ``bases``, ``class_dict`` and
``configuration class_name`` and do something with it, probably
creating a
class_object which behaviour is parametred with the context. I did not
know
Python before new-style class, so probably for most people explainning
that
metaclasses are a creation hook is easier for them...

  4) It's in type.__call__ that happens calls to __new__ and __init__

 Again, translates to is suggesting this is what happens when you do
 X, which I don't know if is strictly true. CPython inside may be
 optimizing this whole process.
 Especially when it comes to magic
 methods, __x__ and the like -- CPython rarely uses __get*_ for those.
 It just calls the methods directly on the class object.

IIUC the code of Jython tells me what I've written. If the first part
of the algorithm
is lookup for special methods (what you seem to say) then we both
agree that we
agree, isn't it ?

Moreover I'm not looking in this part to understand how CPython works
internally,
but how Python works. Since I'm most proeffencient in Python I
translate it to
Python.

*Translates* means it's a shortcut for.


  5) 3) = classes are instance of type

  6) Since type.__call__ is used to instantiate instance of instance 

Re: truncating strings

2011-08-23 Thread Ethan Furman

Seebs wrote:

On 2011-08-23, Roy Smith r...@panix.com wrote:

I want to log a string but only the first bunch of it, and add ...
to the end if it got truncated.  This certainly works:



  logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
route, params, e.code))



does anything like this exist?


%.50s


That's not working in 2.7 or 3.2.

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


Re: Windows No-Install Distribution?

2011-08-23 Thread Eric Lemings
On Aug 23, 1:52 pm, Stephen Hansen me+list/pyt...@ixokai.io wrote:
 On 8/23/11 8:29 AM, Eric Lemings wrote:

  I would like to create/find a Python 3.x distribution that can be
  redeployed simply by copying a directory of required files; i.e.

 Just take the default installer, install it, and then check the Python
 directory: does it have the python DLL? If not, go look into the
 system32 directory, grab it, drop it in the Python directory. (If you
 installed for all-users this will happen,

 Now copy/zip/whatever that Python directory to another machine where it
 was not installed. It'll work fine.

 You'll have to explicitly provide the path to the Python.exe of course;
 you can't just double-click on a .py or run 'python blah.py', but if
 your shortcuts/whatever all do C:\Where\You\Installed\Python.exe,
 everything should just work.

 We do that at work and never run into any trouble. (We actually provide
 a MSI but only for convenience of customers who want to auto-install via
 Group Policy).

 In most situations, Python's good at finding itself, i.e. where the
 python.exe is actually located -- and it boostraps the location of
 everything else based on that.

 --

    Stephen Hansen
    ... Also: Ixokai
    ... Mail: me+list/python (AT) ixokai (DOT) io
    ... Blog:http://meh.ixokai.io/

  signature.asc
  1KViewDownload

Excellent start.

Which files comprise the standard Python library?  Only the files in
the 'Lib' subdirectory or are more needed?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: truncating strings

2011-08-23 Thread Seebs
On 2011-08-23, Ethan Furman et...@stoneleaf.us wrote:
 Seebs wrote:
 On 2011-08-23, Roy Smith r...@panix.com wrote:
   logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
 route, params, e.code))

 does anything like this exist?

 %.50s

 That's not working in 2.7 or 3.2.

Huh.

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type help, copyright, credits or license for more information.
 print %.5s % (hello there, truncate me!)
hello

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


upgrade python

2011-08-23 Thread Ronald Reynolds
What is recommended for upgrading python for windows? Do I just install the new 
versionDo I edit my system path? Should I uninstall the old version.  Right now 
I have 2.7 and3.1  and 3.2  and I keep editing my system path when I install a 
new version but I'm notsure that's the right way to go.  Is there an upgrade 
way? I only found downloads at Python.org  thx     'Ron bumpker Reynolds' -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for python/pyramid developers for a project

2011-08-23 Thread Ben Finney
Mathew mzu...@gmail.com writes:

 We are looking to hire a developer(s) immediately.

Please don't use this Python discussion for recruitment.

Instead, please use the Python Jobs Board for that purpose
URL:http://www.python.org/community/jobs/.

-- 
 \  “It's a good thing we have gravity or else when birds died |
  `\ they'd just stay right up there. Hunters would be all |
_o__)confused.” —Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: upgrade python

2011-08-23 Thread Terry Reedy

On 8/23/2011 6:09 PM, Ronald Reynolds wrote:

What is recommended for upgrading python for windows? Do I just install
the new version


I put each version in its own Pythonxy directory, as the installer 
wants. x.y.z bug fix releases replace the previous x.y release.



Do I edit my system path?


However, I put all versions in my own 'Programs' directory (not at 
top-level, not in Program Files. On my old machine, I added that one 
directory to PATH. Then I copied Pythonxy/python to pyxy in that 
directory. I will do the same on my new machine when I have need. But I 
mostly execute from an IDLE editor window, so PATH and command prompts 
are mostly irrelevant for me.



Should I uninstall the old version.


If and only if you are sure you have no further use for it.


--
Terry Jan Reedy

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


Re: truncating strings

2011-08-23 Thread Ethan Furman

Seebs wrote:

On 2011-08-23, Ethan Furman et...@stoneleaf.us wrote:

Seebs wrote:

On 2011-08-23, Roy Smith r...@panix.com wrote:

  logger.error(FAILED: '%s{50}', '%s', %s, %s % (message,
route, params, e.code))



does anything like this exist?



%.50s



That's not working in 2.7 or 3.2.


Huh.

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type help, copyright, credits or license for more information.
 print %.5s % (hello there, truncate me!)
hello


Ah -- that's only part of it -- the OP wants '...' to print as well.  :)

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


Re: Windows No-Install Distribution?

2011-08-23 Thread Terry Reedy

On 8/23/2011 5:56 PM, Eric Lemings wrote:

On Aug 23, 1:52 pm, Stephen Hansenme+list/pyt...@ixokai.io  wrote:

On 8/23/11 8:29 AM, Eric Lemings wrote:


I would like to create/find a Python 3.x distribution that can be
redeployed simply by copying a directory of required files; i.e.


Just take the default installer, install it,


except do a custom install and leave out what you do not want. (Tools? 
tcl/tk/idle?). You can leave out tests, but then you might want that, at 
least once, to test your no-install copy.



and then check the Python
directory: does it have the python DLL? If not, go look into the
system32 directory, grab it, drop it in the Python directory. (If you
installed for all-users this will happen,


For Python3, python3.dll in in Python3y\DLLs even for all users install.
I believe this is per MS recommendation. So just copy the entire 
python3y directory.



Which files comprise the standard Python library?  Only the files in
the 'Lib' subdirectory

That only has Python-coded modules.


or are more needed?
C-coded modules are in /DLLs. I presume /libs is needed too but I do not 
really know, and I will not experiment.


Just limit your install to what you want and copy everything.

--
Terry Jan Reedy

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


Re: truncating strings

2011-08-23 Thread Steven D'Aprano
Seebs wrote:

 Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
 [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
 Type help, copyright, credits or license for more information.
  print %.5s % (hello there, truncate me!)
 hello


Well, whadda you know, I learned something new :)


In any case, this doesn't solve the OP's problem, as he wants to truncate
the input string, and append '...' if and only if it were truncated.

The right solution is to wrap the functionality in a function. It's not
hard, and is elegant. Not everything needs to be a built-in.

# Untested.
def truncate(s, maxwidth=50):
if len(s) = maxwidth:
return s
s = s[:maxwidth - 3]
return s + '...'



-- 
Steven

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


Re: is there any principle when writing python function

2011-08-23 Thread Steven D'Aprano
Terry Reedy wrote:

 On 8/23/2011 11:22 AM, Steven D'Aprano wrote:
 
 Even 7±2 is probably excessive: I find that I'm most comfortable with
 functions that perform 4±1 chunks of work. An example from one of my
 classes:

  def find(self, prefix):
  Find the item that matches prefix.
  prefix = prefix.lower()  # Chunk #1
  menu = self._cleaned_menu  # Chunk #2
  for i,s in enumerate(menu, 1):  # Chunk #3
  if s.lower().startswith(prefix):
  return i
  return None  # Chunk #4

 So that's three one-line chunks and one three-line chunk.
 
 In terms of different functions performed (see my previous post), I see
attribute lookup
assignment
enumerate
sequence unpacking
for-looping
if-conditioning
lower
startswith
return
 That is 9,  which is enough.


I think we have broad agreement, but we're counting different things.
Analogy: you're counting atoms, I'm grouping atoms into molecules and
counting them.

It's a little like phone numbers: it's not an accident that we normally
group phone numbers into groups of 2-4 digits:

011 23 4567 8901

In general, people can more easily memorise four chunks of four digits (give
or take) than one chunk of 13 digits: 0112345678901.



-- 
Steven

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


Learning Python

2011-08-23 Thread User

Hello all,
Does anyone have any good resources for learning Python? I know basic 
Java and basic Python (loops, data types, if-then statements, etc), but 
I want to delve into Python further. If anyone knows of any good books, 
video tutorials, etc it would be greatly appreciated.

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


Re: is there any principle when writing python function

2011-08-23 Thread alex23
rantingrick rantingr...@gmail.com wrote:
 Everyone here who is suggesting that function bodies should be
 confined to ANY length is an idiot.

Or, more likely, is the sort of coder who has worked with other coders
in the past and understands the value of readable code.

 Don't worry if it too small or too big. It's
 not the size that matters, it's the motion of the sources ocean!

If only you spent as much time actually thinking about what you're
saying as trying to find 'clever' ways to say it...

 Always use
 comments to clarify code and NEVER EVER create more functions only for
 the sake of short function bodies

This is quite likely the worst advice you've ever given. I can only
assume you've never had to refactor the sort of code you're advocating
here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread alex23
rantingrick rantingr...@gmail.com wrote:
 https://sites.google.com/site/thefutureofpython/

Very soon I will be hashing out a specification for python 4000.

AHAHAHAHAhahahahahahahAHAHAHAHahahahahaaa. So rich. Anyone willing
to bet serious money we won't see this before 4000AD?

Heck even our leader seems as a captain too drunk with vanity to
care; and our members like a ship lost at sea left to sport of every
troll-ish wind!

Quite frankly, you're a condescending, arrogant blow-hard that this
community would be better off without.

We must constantly strive to remove multiplicity from our systems;
lest it consumes us!

s/multiplicity/rantingrick/ and I'm in full agreement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading and writing files

2011-08-23 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Adrián Monkas wrote:

Hi.
I`ve been trying to copy a long text from one file to another but it always
copied me just a small part.
I would be glad if you can help me or explain which is my error.
Thanks

--
def runMenu():

 print \nMENU
 print   1) Copiar
 print   0) Exit

 response = int( raw_input().strip() )

 if response == 1:
 print Copiar
 try:
 print Abro Archivo Origen
 archivo=open(D:\Boot.txt,r)
 print Name of the file: , archivo.name
 print Closed or not : , archivo.closed
 print Opening mode : , archivo.mode

 print ORIGEN---
 print archivo.read()
 print -
 archivo.seek(0, 0)

 print Abro Archivo Destino
 archivo2=open(D:\Copia.txt,w+)
 print Name of the file: , archivo2.name
 print Closed or not : , archivo2.closed
 print Opening mode : , archivo2.mode



 archivo2.write(archivo.read())

 archivo2.seek(0, 0)
 print -DESTINO-
 print archivo2.read()
 print -
 archivo.close()
 archivo2.close()

 except IOError:
 print (I/O Error de Lectura)
 else:
 print Lectura OK

 elif response == 0:
 #device.close()
 print Exit

 return response

def main():
 print main
 while(1):
 if runMenu() == 0: break

main()

What's your goal?  If it's to write a small program to copy a file, try 
using shutil library. It'll save you lots of trouble.  It can handle 
files that are bigger than available memory, it can fix up timestamps, etc.


If it's to learn Python, then you need to learn about writing debuggable 
code.  Part of that is doing things once.  So if you read() the entire 
contents of the file, keep it in a variable and use that variable to 
write() to the other file, and also to print to the screen.  Then if 
something's wrong, you can be sure it's the same both places.  Never do 
something like  y.write(x.read())  till you're sure everything's 
working.  That's a kind of optimization which doesn't save any execution 
time, and only a few keystrokes.  And you'll waste those keystrokes 
changing the code a dozen times to find out why it isn't working.


You don't make clear just what is just a small part.  In other words, 
what is truncated?  Is it the ORIGEN printout, the DESTINO printout, or 
the actual file contents ?


And is the file involved a gigabyte or two, or is it 500 bytes?

Did it display part of the file correctly, or by small part did you 
mean zero bytes?


Show the actual stack trace if you got an error, or the program output 
if not.


And in general, when you're asking questions, please specify the Python 
version and OS version you're running.  Clearly, the latter is some kind 
of Windows, since you're using the D: drive.  And the Python version is 
2.x for some value of x.  But sometimes it'll matter.


Your filenames are incorrect, since you use the backslash without 
escaping it.  So the source file has a backspace in it.  I'm amazed you 
don't get an error, since it's unlikely you have a file with that kind 
of name.  When I run it, I get  Abro Archivo Origen.  I'm astounded 
you don't.  When making a literal string out of a Windows filename, 
either double the backslashes, or use Rxxx for raw strings, or just 
use forward slashes.


HTH.


DaveA


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


Re: Learning Python

2011-08-23 Thread Steven D'Aprano
On Wed, 24 Aug 2011 12:46 pm User wrote:

 Hello all,
 Does anyone have any good resources for learning Python?

http://duckduckgo.com/?q=python+tutorial



-- 
Steven

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


Announcing a new podcast: Radio Free Python

2011-08-23 Thread Larry Hastings



Radio Free Python is a new monthly podcast focused on Python and its 
community.


Episode 1 has just been released!  It features a panel discussion with 
the PythonLabs team:


   * Barry Warsaw,
   * Fred Drake,
   * Guido van Rossum,
   * Roger Masse,
   * and Tim Peters.


You can find it at http://www.radiofreepython.com/ as of this very minute.

Enjoy!


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


Re: reading and writing files

2011-08-23 Thread Chris Rebert
On Tue, Aug 23, 2011 at 9:05 PM, Dave Angel da...@ieee.org wrote:
 On 01/-10/-28163 02:59 PM, Adrián Monkas wrote:
snip
             print Abro Archivo Origen
             archivo=open(D:\Boot.txt,r)
snip
 Your filenames are incorrect, since you use the backslash without escaping
 it.  So the source file has a backspace in it.  I'm amazed you don't get an
 error, since it's unlikely you have a file with that kind of name.

Backslash escape sequences only work for lowercase characters:
 '\b'
'\x08'
 '\B'
'\\B'

But yeah, I don't endorse relying on this.

Just use forward slashes instead of backslashes in paths; Windows
accepts them just fine.

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


Re: truncating strings

2011-08-23 Thread Seebs
On 2011-08-23, Ethan Furman et...@stoneleaf.us wrote:
 Ah -- that's only part of it -- the OP wants '...' to print as well.  :)

O.  Hmm.

That's harder.  I can't think of a pretty way, so I think I'd probably
write a prettytrunc(string, len) or something similar.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue12678] test_packaging and test_distutils failures under Windows

2011-08-23 Thread Nadeem Vawda

Nadeem Vawda nadeem.va...@gmail.com added the comment:

 I’ll commit the tmp-debug patch so that we can get info from the buildbot,
 unless Jeremy or someone can investigate.

If you can wait until this evening (CEST), I'll run the tests with that
patch applied locally. It might be easier to get to the bottom of this if
we co-ordinate via IRC.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12678
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12678] test_packaging and test_distutils failures under Windows

2011-08-23 Thread Éric Araujo

Éric Araujo mer...@netwok.org added the comment:

I’m in CEST too (France), but I’m not sure I’ll have Internet access this 
evening.  Would tomorrow afternoon work for you?  I don’t want you to have to 
dive in distutils more than you should :)

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12678
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12821] test_fcntl failed on OpenBSD 5.x

2011-08-23 Thread Remi Pointel

New submission from Remi Pointel pyt...@xiri.fr:

Hello,

test_fcntl failed on OpenBSD 5.0.
It's ok when we add openbsd5 in the tuple of sys.platform (patch attached).

Thanks a lot,

Remi.

--
files: patch-Lib_test_test_fcntl_py
messages: 142784
nosy: rpointel
priority: normal
severity: normal
status: open
title: test_fcntl failed on OpenBSD 5.x
versions: Python 2.7, Python 3.2, Python 3.3
Added file: http://bugs.python.org/file23012/patch-Lib_test_test_fcntl_py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12821
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12821] test_fcntl failed on OpenBSD 5.x

2011-08-23 Thread Charles-François Natali

Charles-François Natali neolo...@free.fr added the comment:

Note that it's been fixed in default with the recent sys.platform refactoring:

26 if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 
'bsdos'))
27 or sys.platform == 'darwin'):
28 if struct.calcsize('l') == 8:

I'll commit a patch for 2.7 and 3.2.

--
components: +Tests
nosy: +neologix
stage:  - needs patch
type:  - behavior
versions:  -Python 3.3

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12821
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12821] test_fcntl failed on OpenBSD 5.x

2011-08-23 Thread Remi Pointel

Remi Pointel pyt...@xiri.fr added the comment:

Thanks a lot, I prefer to use sys.platform.startswith too.

Remi.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12821
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6560] socket sendmsg(), recvmsg() methods

2011-08-23 Thread Charles-François Natali

Charles-François Natali neolo...@free.fr added the comment:

 However, in doing this, I noticed that these methods will, at best, work 
 during the time between connection and the socket going secure and were not 
 added to the list of methods that the SSL is documented as exposing. Perhaps 
 we should just ditch them entirely?

+1

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6560
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12409] Moving Documenting Python to Devguide

2011-08-23 Thread Georg Brandl

Georg Brandl ge...@python.org added the comment:

+1, and as Eric says, we can do it without changing versions of Sphinx used.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12409
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12822] NewGIL should use CLOCK_MONOTONIC if possible.

2011-08-23 Thread INADA Naoki

New submission from INADA Naoki songofaca...@gmail.com:

Using CLOCK_MONOTONIC is better than CLOCK_REALTIME (default) for GIL
because settimeofday() may break the pthread_cond_timedwait().

Attached patch uses CLOCK_MONOTONIC and clock_gettime. But I don't know
how to write appropriate configure script.
-lrt is also needed to use clock_gettime() but I don't know how to add
it to LIBS.

--
components: None
files: use_monotonic_clock.patch
keywords: patch
messages: 142789
nosy: naoki
priority: normal
severity: normal
status: open
title: NewGIL should use CLOCK_MONOTONIC if possible.
type: behavior
versions: Python 3.2, Python 3.3
Added file: http://bugs.python.org/file23013/use_monotonic_clock.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12822
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12678] test_packaging and test_distutils failures under Windows

2011-08-23 Thread Éric Araujo

Éric Araujo mer...@netwok.org added the comment:

higery: Would you have a bit of free time to help use here?

--
nosy: +higery

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12678
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12822] NewGIL should use CLOCK_MONOTONIC if possible.

2011-08-23 Thread STINNER Victor

Changes by STINNER Victor victor.stin...@haypocalc.com:


--
nosy: +haypo

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12822
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12822] NewGIL should use CLOCK_MONOTONIC if possible.

2011-08-23 Thread STINNER Victor

STINNER Victor victor.stin...@haypocalc.com added the comment:

See also #10278.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12822
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10278] add time.wallclock() method

2011-08-23 Thread STINNER Victor

STINNER Victor victor.stin...@haypocalc.com added the comment:

See also #12822.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10278
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12808] Coverage of codecs.py

2011-08-23 Thread Marc-Andre Lemburg

Marc-Andre Lemburg m...@egenix.com added the comment:

Tennessee Leeuwenburg wrote:
 
 Tennessee Leeuwenburg tleeuwenb...@gmail.com added the comment:
 
 Thanks for the review. Here is a patch incorporating the two comments being 
 to move some comments.

Hmm, the documentation patch doesn't appear to have changed. Did you
upload the right patch ?

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12808
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12808] Coverage of codecs.py

2011-08-23 Thread STINNER Victor

Changes by STINNER Victor victor.stin...@haypocalc.com:


--
nosy: +haypo

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12808
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12823] Broken link in SSL wrapper for socket objects document

2011-08-23 Thread Roger Li

New submission from Roger Li worm...@gmail.com:

In http://docs.python.org/release/3.1.3/library/ssl.html
You will find a link at the bottom named Introducing SSL and Certificates 
using OpenSSL, it's a broken link.

The server may be down or not exist, the only version I can find is 
http://web.archive.org/web/20090429050651/http://old.pseudonym.org/ssl/wwwj-index.html

Please consider to replace the link to the new one.

--
assignee: docs@python
components: Documentation
messages: 142794
nosy: docs@python, iworm
priority: normal
severity: normal
status: open
title: Broken link in SSL wrapper for socket objects document
versions: Python 3.1

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12823
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12824] Make the write_file() helper function in test_shutil return the file name it wrote to

2011-08-23 Thread Hynek Schlawack

New submission from Hynek Schlawack h...@ox.cx:

test_shutil contains a handy helper function called write_file(filename. 
contents). If *filename* is a tuple, os.path.join() is used to concatenate it 
to a path.

To be really useful, the resulting file name should be returned, so the user 
can work with it.

So instead of:
fn = os.path.join(x,y)
write_file(fn, 'contents')

I'd prefer:
fn = write_file((x,y), 'contents')

I have attached a simple patch that achieves this and also applied the 
resulting simplification to some of the tests.

--
components: Tests
files: write_file_returns_filename.diff
keywords: patch
messages: 142795
nosy: eric.araujo, hynek
priority: normal
severity: normal
status: open
title: Make the write_file() helper function in test_shutil return the file 
name it wrote to
type: feature request
versions: Python 3.3
Added file: http://bugs.python.org/file23014/write_file_returns_filename.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12824
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12721] Chaotic use of helper functions in test_shutil for reading and writing files

2011-08-23 Thread Hynek Schlawack

Hynek Schlawack h...@ox.cx added the comment:

Done in Issue12824.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12721
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12825] Missing and incorrect link to a command line option.

2011-08-23 Thread Kyle Simpson

New submission from Kyle Simpson illwhip...@gmail.com:

The documentation for the runpy module has a link to the -m command line 
option. In version 2.7.2 of the docs, the link doesn't exist.

http://docs.python.org/release/2.7/library/runpy.html
http://docs.python.org/release/2.7.2/library/runpy.html

If you run

touch library/runpy.rst
make html

then the link is created, but with an anchor of cmdoption-unittest-discover-m 
instead of cmdoption-m.

http://docs.python.org/release/2.7.2/using/cmdline.html#cmdoption-unittest-discover-m

--
assignee: docs@python
components: Documentation
messages: 142797
nosy: Kyle.Simpson, docs@python
priority: normal
severity: normal
status: open
title: Missing and incorrect link to a command line option.
versions: Python 2.7

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12825
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12825] Missing and incorrect link to a command line option.

2011-08-23 Thread Éric Araujo

Éric Araujo mer...@netwok.org added the comment:

It’s weird that the docs under /release/2.7 has the link but not the one under 
/.

--
nosy: +eric.araujo, georg.brandl

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12825
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12826] module _socket failed to build on OpenBSD

2011-08-23 Thread Remi Pointel

New submission from Remi Pointel pyt...@xiri.fr:

Hello,
I try to build Python 3.3 on OpenBSD, and it failed to build these modules: 
_socket (so _ssl too).

Errors are:
/home/remi/dev/cpython_test/Modules/socketmodule.c: In function 'sock_recvmsg':
/home/remi/dev/cpython_test/Modules/socketmodule.c:2935: error: storage size of 
'iov' isn't known
/home/remi/dev/cpython_test/Modules/socketmodule.c:2935: warning: unused 
variable 'iov'
/home/remi/dev/cpython_test/Modules/socketmodule.c: In function 
'sock_recvmsg_into':
/home/remi/dev/cpython_test/Modules/socketmodule.c:3023: error: invalid 
application of 'sizeof' to incomplete type 'struct iovec' 
/home/remi/dev/cpython_test/Modules/socketmodule.c:3023: warning: division by 
zero
/home/remi/dev/cpython_test/Modules/socketmodule.c:3023: error: invalid 
application of 'sizeof' to incomplete type 'struct iovec' 
/home/remi/dev/cpython_test/Modules/socketmodule.c:3034: error: invalid use of 
undefined type 'struct iovec'
/home/remi/dev/cpython_test/Modules/socketmodule.c:3034: error: dereferencing 
pointer to incomplete type
/home/remi/dev/cpython_test/Modules/socketmodule.c:3035: error: invalid use of 
undefined type 'struct iovec'
/home/remi/dev/cpython_test/Modules/socketmodule.c:3035: error: dereferencing 
pointer to incomplete type
/home/remi/dev/cpython_test/Modules/socketmodule.c: In function 'sock_sendmsg':
/home/remi/dev/cpython_test/Modules/socketmodule.c:3332: error: invalid 
application of 'sizeof' to incomplete type 'struct iovec' 
/home/remi/dev/cpython_test/Modules/socketmodule.c:3332: warning: division by 
zero
/home/remi/dev/cpython_test/Modules/socketmodule.c:3332: error: invalid 
application of 'sizeof' to incomplete type 'struct iovec' 
/home/remi/dev/cpython_test/Modules/socketmodule.c:3343: error: invalid use of 
undefined type 'struct iovec'
/home/remi/dev/cpython_test/Modules/socketmodule.c:3343: error: dereferencing 
pointer to incomplete type
/home/remi/dev/cpython_test/Modules/socketmodule.c:3344: error: invalid use of 
undefined type 'struct iovec'
/home/remi/dev/cpython_test/Modules/socketmodule.c:3344: error: dereferencing 
pointer to incomplete type
*** WARNING: renaming _ssl since importing it failed: No module named 
'_socket'

If I add a #include sys/uio.h, these 2 modules correcly build.

Attached file are:
-the diff
-the details of errors.

Thanks,
Remi.

--
files: socketmodule_build_openbsd.diff
keywords: patch
messages: 142799
nosy: rpointel
priority: normal
severity: normal
status: open
title: module _socket failed to build on OpenBSD
versions: Python 3.3
Added file: http://bugs.python.org/file23015/socketmodule_build_openbsd.diff

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12826
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   >