Python on Android (was: PyPy 2.0 beta 1 released)

2012-11-22 Thread Stefan Behnel
Peter Funk, 23.11.2012 07:54:
> Is it be possible to use PyPy to develop Apps for Android phones and tablets? 
> Or will it be possible to do so in the future?

You can use CPython and kivy for that. Nik Klever gave a quick intro to
Python on Android at this year's PyCon-DE:

http://pyvideo.org/video/1443/erfahrungen-mit-py4a-sowohl-mit-sl4a-als-auch

He's using it for teaching purposes.

Stefan


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


Re: PyPy 2.0 beta 1 released

2012-11-22 Thread Peter Funk

Maciej Fijalkowski wrote 22.11.2012 12:54:
> We're pleased to announce the 2.0 beta 1 release of PyPy.
...
> It also supports ARM machines running Linux.
...
Is it be possible to use PyPy to develop Apps for Android phones and tablets? 
Or will it be possible to do so in the future?

Regards, Peter Funk
-- 
Peter Funk, home: ✉Oldenburger Str.86, D-2 Ganderkesee
mobile:+49-179-640-8878 phone:+49-421-20419-0 
office: ArtCom GmbH, ✉Haferwende 2, D-28357 Bremen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Data manipulation tool built with bottle and redis

2012-11-22 Thread markcial
Hi, i have little expertise on python and redis, but i started a project on 
github, i'm looking for any guidelines, help, or advices, hope you don't mind 
my noob coding.

https://github.com/Markcial/BottledJinn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 10 sec poll - please reply!

2012-11-22 Thread Steven D'Aprano
On Thu, 22 Nov 2012 10:00:54 -0800, Michael Herrmann wrote:

> We took the fact that naming our one function 'type' was so difficult to
> name as an indicator that it may be trying to do too many things:

I don't think it is difficult to name at all.

> On the one hand, it allows you to enter plain text as in `type("Hello
> World!")`; 

That would be called "typing".

> on the other hand, it lets you press single keys, 

That would be called "typing".

> possibly in combination with control keys as for instance in 
> `type(CTRL + 'a')`. 

That would be called "prestidigitation".

Nah, just kidding. That would also be called "typing".



> We believe it won't normally be necessary to combine the two.

I can't imagine why you say that. You even go ahead and give a perfectly 
fine example of combining a control character with plain text.

I don't know what operating system you are using, but under Linux, people 
often use strings of regular characters mixed in with control- or alt-
characters. E.g. I in the shell, I might type Alt-B Shift-' END Shift-' 
to jump backwards one word (Alt-B), insert a double quote mark (Shift-'), 
jump to the end of the line I am editing (END), and insert another double 
quote mark.

It is a needless restriction to assume that every control character must 
only be part of a single key press event. I even remember a Mac 
application back in the early 1990s or late 1980s that used combinations 
like Ctrl-A Y to perform commands. (Actually, such older Macs didn't have 
a Control key, they used Command instead, but the principle is the same.)


> One of the main goals of our automation product is that using it should
> feel like giving instructions to a human being looking over their
> shoulder at a screen.

In a word processor, I might say

"Type Ctrl-A Ctrl-X to cut all the text from the document."

rather than

"Press Ctrl-A. Now press Ctrl-X."


> We really quite like the word `type`, and a few people here seem to
> favour it too. In particular, Steven: We're glad you accidentally
> clicked on our mail. Thank you for your inputs and the great quote by
> Phil Karlton. We think you were right in everything you said. However,
> some people seem to be *really* put off when you override a built-in
> function. Even though of course you can avoid the overriding by saying
>   from automa.api import type *as* ...,
> (as Tim pointed out) we'd like to avoid irritating those people. For
> this reason, we would rather not use `type`.

You need to ask yourself, who is your primary audience for your software?

Is it ... ?

a) non-technical people who aren't very familiar with Python, and might 
not even know that there is a built-in function also called "type", or 
care if they do know;

b) Python programmers who have embraced the concept of namespaces and 
have no fear about x.foo clashing with y.foo;

c) Python programmers with a superstitious dread of using any name which 
is not global unique, just in case somebody accidentally shadows one 
function "foo" with another function "foo".

I think it is downright silly to avoid using the descriptive and simple 
name "type" out of some superstition against re-using names which have 
been used elsewhere, even in the builtins.

If it were possible to be confused by the two types, e.g. if they took 
the same arguments but did radically different things, then I would 
accept that it was too dangerous/confusing to re-use the name. Reasonable 
fears about shadowing and confusion are, well, reasonable. But nobody is 
going to confuse your use of type as a command:

type(some_string)

with the built-in use as a function

if type(something) is list:
MyClass = type(x, y, z)


I don't think there is any point in having two functions that do exactly 
the same thing. Expect your users to develop all sorts of superstitions 
like "you can only use press() with a single key at a time", and get 
confused as to when you are supposed to use enter() and when press() (for 
whatever names you eventually choose).


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


Re: Migrate from Access 2010 / VBA

2012-11-22 Thread Jason Friedman
> I am the lone developer of db apps at a company of 350+ employees. Everything 
> is done in MS Access 2010 and VBA. I'm frustrated with the limitations of 
> this platform and have been considering switching to Python. I've been 
> experimenting with the language for a year or so, and feel comfortable with 
> the basics.
>
> I am concerned that I'll have a hard time replacing the access form and 
> report designers. I've worked a little with TKinter, but it's a far cry from 
> the GUI designer in Access. Finding a professional grade report designer 
> looks like an even bigger challenge.
>
> I don't need to port any applications, but I will need to use the data 
> (mdb/accede format), design a variety of reports with multi-level groupings, 
> and deliver them to many individual recipients via email.

Do the employees need to be able to create their own reports, or do
you interview them and create reports based on their requirements?

Is there a need to provide slice-and-dice, or is each permutation/view
of the data its own report?

Are the recipients internal?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Steven D'Aprano
On Thu, 22 Nov 2012 16:51:27 +0100, Peter Otten wrote:

> Marc Aymerich wrote:
> 
>> Hi,
>> 
>> I want to create a method within a class that is able to accept either
>> a class or an instance.
[...]
> Why would you overload a method that way?


The use-case I have is that I have a number of classes with default 
state. Most instances don't override any of the state, so the instances 
don't add anything except an extra conceptual layer:

instance = MyClass()  # notice that there are no arguments passed
instance.method(args)

Since the instances don't have any state except for that already held by 
the class, they are redundant and pointless. Just knowing the class is 
enough to specify the behaviour. If I used class methods, I could do this:

MyClass.method(args)


But here's the thing -- sometimes I *do* have instances that override the 
default state:

instance = MyClass(x, y, z)
instance.method(args)

Now if method is a class method, my per-instance state is ignored. So I 
want a method that can be called from the class, and see the default 
state, or from the instance, and see the per-instance state. Neither 
classmethod, staticmethod nor ordinary instance methods do the job, but 
my custom dualmethod does.

http://code.activestate.com/recipes/577030/



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


Re: Yet another Python textbook

2012-11-22 Thread Alec Taylor
No worries,

I've just sent you my pull-request :)

On Thu, Nov 22, 2012 at 1:11 PM, Pavel Solin  wrote:
> Hi Alec,
>
>> Can you put your website—http://femhub.com/textbook-python/—on your
>> github—https://github.com/femhub/nclab-textbook-python?
>
> Done, thank you so much.
>
> I edited the textbook based on responses that I received. Based
> on several inquiries we also decided to add Python 3.2 to NCLab.
> New release is coming in one or two weeks.
>
> Cheers,
>
> Pavel
>
>
> On Wed, Nov 21, 2012 at 4:34 PM, Alec Taylor  wrote:
>>
>> Dear Prof. Solin,
>>
>> Can you put your website—http://femhub.com/textbook-python/—on your
>> github—https://github.com/femhub/nclab-textbook-python?
>>
>> I will then send you a pull request with a bootstrapped homepage with good
>> UX.
>>
>> All the best,
>>
>> Alec Taylor
>
>
>
>
> --
> Pavel Solin
> Associate Professor
> Applied and Computational Mathematics
> University of Nevada, Reno
> http://hpfem.org/~pavel
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Migrate from Access 2010 / VBA

2012-11-22 Thread David Hutto
On Thu, Nov 22, 2012 at 10:19 PM, kgard  wrote:
> Greetings:
>
> I am the lone developer of db apps at a company of 350+ employees. Everything 
> is done in MS Access 2010 and VBA. I'm frustrated with the limitations of 
> this platform and have been considering switching to Python. I've been 
> experimenting with the language for a year or so, and feel comfortable with 
> the basics.
>
> I am concerned that I'll have a hard time replacing the access form and 
> report designers. I've worked a little with TKinter, but it's a far cry from 
> the GUI designer in Access. Finding a professional grade report designer 
> looks like an even bigger challenge.
>
> I don't need to port any applications, but I will need to use the data 
> (mdb/accede format), design a variety of reports with multi-level groupings, 
> and deliver them to many individual recipients via email.
>
> Has anyone here made this transition successfully? If so, could you pass 
> along your suggestions about how to do this as quickly and painlessly as 
> possible?http://www.youtube.com/watch?v=DksSPZTZES0
>
> TIA
> Keith

Translate function for function to the new language(return values),
then adapt the GUI to represent the new functions on event activity
via widgets.



-- 
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another Python textbook

2012-11-22 Thread Steven D'Aprano
On Thu, 22 Nov 2012 17:41:22 -0500, Colin J. Williams wrote:

> You and I used __format__.  I understand that the use of double
> underscore functions is deprecated.

Double leading and trailing underscore methods are not deprecated, they 
are very much part of the public interface. But they are reserved for 
Python's use, and under normal conditions you should not be using them by 
hand. For example:

y = x.__add__(1)  # NO
y = x + 1  # YES

if mylist.__len__() > 2:  # NO
if len(mylist) > 2:  # YES


> Is there some regular function which can achieve the same result?

The built-in format() function is the public API for calling the dunder 
method __format__. So normally you would write:

format(value, spec)

instead of value.__format__(spec).



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


Migrate from Access 2010 / VBA

2012-11-22 Thread kgard
Greetings:

I am the lone developer of db apps at a company of 350+ employees. Everything 
is done in MS Access 2010 and VBA. I'm frustrated with the limitations of this 
platform and have been considering switching to Python. I've been experimenting 
with the language for a year or so, and feel comfortable with the basics. 

I am concerned that I'll have a hard time replacing the access form and report 
designers. I've worked a little with TKinter, but it's a far cry from the GUI 
designer in Access. Finding a professional grade report designer looks like an 
even bigger challenge.

I don't need to port any applications, but I will need to use the data 
(mdb/accede format), design a variety of reports with multi-level groupings, 
and deliver them to many individual recipients via email.

Has anyone here made this transition successfully? If so, could you pass along 
your suggestions about how to do this as quickly and painlessly as possible? 

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


Re: Spam source (Re: Horror Horror Horror!!!!!)

2012-11-22 Thread Steven D'Aprano
On Thu, 22 Nov 2012 14:08:58 -0800, Robert Miles wrote:

> It now takes two people reporting the same spam to get google groups to
> do much about it.  I just reported this one as well, though.

Speaking of spam, googlegroups, and other annoyances, please don't CC 
python-list@python.org as well as posting to the newsgroup.

The newsgroup is already automatically mirrored by the mailing list, and 
vice versa, so by CCing all you do is needlessly, and annoyingly, 
duplicate your message.




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


Re: Print value from array

2012-11-22 Thread Mike
El jueves, 22 de noviembre de 2012 16:02:30 UTC-3, Alister  escribió:
> On Thu, 22 Nov 2012 10:44:02 -0800, Mike wrote:
> 
> 
> 
> > Hello,
> 
> > I am noob en python programing,  i wrote a perl script for read from csv
> 
> > but now i wish print value but the value must be within double quote and
> 
> > I can not do this.
> 
> > 
> 
> > For example now the output is:
> 
> > 
> 
> > ma user@domain displayName Name SecondName givenName Name sn SecondName
> 
> > cn Name
> 
> > 
> 
> > and i wish
> 
> > 
> 
> > ma "user@domain" displayName "Name Lastname" givenName "Name" sn
> 
> > "SecondName" cn "Name"
> 
> > 
> 
> > My script is
> 
> > 
> 
> > #!/usr/bin/python import csv
> 
> > 
> 
> > with open ('file.csv', 'rb') as f:
> 
> > reader = csv.reader (f, delimiter=';' )
> 
> > for row in reader:
> 
> > mail = row [0]
> 
> > name = row [1]
> 
> > lastname = row [2]
> 
> > name2  = row [1] + ' ' + row [2]
> 
> > 
> 
> > print  'ma ' + mail + ' displayName ' +  name2.title() + 
> 
> ' givenName '
> 
> > + name.title() + ' sn ' + lastname.title() + ' cn ' + 
> 
> name.title()
> 
> > 
> 
> > #   print '\n'
> 
> > 
> 
> > f.close()
> 
> 
> 
> concatenation is not the python way to build strings
> 
> double quotes can be included in single quoted strings ( & vice Versa)
> 
> try using the string formatting options, something like
> 
> 
> 
> 
> 
> print 'ma "{}" display name "{}" Given Name "{}" sn "{}" cn "{}"'.format
> 
> ((mail,name2.title(),name.title(),lastname.title(),name.title()))
> 
> 
> 
> 
> 
> -- 
> 
> "Plan to throw one away.  You will anyway."
> 
> - Fred Brooks, "The Mythical Man Month"

Thanks Alister , i modify the print structure with your recommendation and is 
solved

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


Re: Managing multiple packages

2012-11-22 Thread Thomas Bach
On Tue, Nov 20, 2012 at 03:24:59PM -0600, Evan Driscoll wrote:
> 
> Suppose I have packages A-C. In addition to being modules in the Python
> sense, they are logically distinct, probably sit in different
> repositories, etc., so there's a directory layout like
> 
> [SNIP]
>
> Finally, suppose that you're changing between editing all three modules.
> 
> 
> How do you deal with this?

I am using virtual environments and do a

python setup.py develop

on each package. This just creates a symbolic link to the package and
all edits show up immediately.

I have not come up with a good solution for tox, yet.

Hope this helps,

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


Re: Yet another Python textbook

2012-11-22 Thread Joshua Landau
On 22 November 2012 22:41, Colin J. Williams  wrote:

> On 22/11/2012 1:27 PM, Ian Kelly wrote:
>
>> On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams  wrote:
>>
>>>  From my reading of the docs, it seems to me that the three following
>>> should
>>> be equivalent:
>>>
>>>(a) formattingStr.format(values)
>>> with
>>>(b) format(values, formattingStr)
>>> or
>>>(c) tupleOfValues.__format__(**formattingStr
>>>
>>> Example:
>>> print('{:-^14f}{:^14d}'.**format(-25.61, 95 ))
>>> print(format((-25.61, 95), '{:-^14f}{:^14d}'))
>>> (-25.61, 95 ).__format__('{:-^14f}{:^14d}'**)
>>>
>>> The second fails, perhaps because values can only be a single value.
>>> The third fails, the reason is unclear.
>>>
>>
>> The latter two (which are more or less equivalent) fail because they are
>> intended for invoking the formatting rules of a single value.  The
>> string argument to each of them is not a format string, but a "format
>> specification", which in a format string is only the part that goes
>> inside the curly braces and after the optional colon.  For example, in
>> this format string:
>>
>
> Thanks, this is clear.  I wish the docs made this clearer.
>
> You and I used __format__.  I understand that the use of double underscore
> functions is deprecated.  Is there some regular function which can achieve
> the same result?


>>> help(format)
format(...)
format(value[, format_spec]) -> string

Returns value.__format__(format_spec)
format_spec defaults to ""


 *In other words, "format(a, b)" is the correct way to write
"a.__format__(b)".*

This is in the same way that "a.__add__(b)" should be written "a + b", or
"a.__round__(b)" written "round(a, b)".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent behaviour os str.find/str.index when providing optional parameters

2012-11-22 Thread Joshua Landau
If you reply through Google Groups, please be careful not to do it the
traditional way as us poor saps get hundreds of lines of ">" added in.

I believe (but this is mere recollection) that a good way to use the site
is by selecting the text you want to quote before replying (even if it is
the whole post). I'm not too sure, though.

On 22 November 2012 18:22, Giacomo Alzetta wrote:

> 
>
> My point was not to change the behaviour but only to point out this
> possible inconsistency between what str.find/str.index do and what they
> claim to do in the documentation.
>
> Anyway I'm not so sure that changing the behaviour would break many
> programs... I mean, the change would only impact code that was looking for
> an empty string over the string's bounds. I don't see often using the lo
> and hi parameters for find/index, and I think I never saw someone using
> them when they get out of bounds. If you add looking for the empty string I
> think that the number of programs breaking will be minimum. And even if
> they break, it would be really easy to fix them.
>
> Anyway, I understand what you mean and maybe it's better to keep this (at
> least to me) odd behaviour for backwards compatibility.
>
> 
>
> Yeah, I understand what you say, but the logic you pointed out is never
> cited anywhere, while slices are cited in the docstring.
>
> 
>

>
Definitely. The sentence "Optional
> arguments start and end are interpreted as in slice notation." should be
> changed to something like:
> "Optional arguments start and end are interpreted as in slice notation,
> unless start is (strictly?) greater than the length of S or end is smaller
> than start, in which cases the search always fails."
>
> In this way the 'spam'.find('', 4) *is* documented because start=len(S) ->
> start and end are treated like in slice notation and 4 makes sense, while
> 'spam'.find('', 5) -> -1 because 5 > len('spam') and thus the search fails
> and also 'spam'.find('', 3, 2) -> -1 makes sense because 2 < 3(this edge
> case makes more sense, even though 'spam'[3:2] is still the empty
> string...).


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


Re: Yet another Python textbook

2012-11-22 Thread Colin J. Williams

On 22/11/2012 1:27 PM, Ian Kelly wrote:

On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams  wrote:

 From my reading of the docs, it seems to me that the three following should
be equivalent:

   (a) formattingStr.format(values)
with
   (b) format(values, formattingStr)
or
   (c) tupleOfValues.__format__(formattingStr

Example:
print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
print(format((-25.61, 95), '{:-^14f}{:^14d}'))
(-25.61, 95 ).__format__('{:-^14f}{:^14d}')

The second fails, perhaps because values can only be a single value.
The third fails, the reason is unclear.


The latter two (which are more or less equivalent) fail because they are
intended for invoking the formatting rules of a single value.  The
string argument to each of them is not a format string, but a "format
specification", which in a format string is only the part that goes
inside the curly braces and after the optional colon.  For example, in
this format string:


Thanks, this is clear.  I wish the docs made this clearer.

You and I used __format__.  I understand that the use of double 
underscore functions is deprecated.  Is there some regular function 
which can achieve the same result?





'Hello world {0!s:_>4s}'.format(42)

'Hello world __42'

The format specifier here is "_>4s":


format('42', '_>4s')

'__42'

The valid format specifiers depend upon the type of the object being formatted:


format(42, '04x')

'002a'


format(datetime(2012, 11, 22, 11, 17, 0), 'The time is %Y %d %m %H:%M:%S')

'The time is 2012 22 11 11:17:00'

Custom types can implement custom format specifications by overriding
the __format__ method:


class Foo:

... def __init__(self, value):
... self.value = value
... def __format__(self, spec):
... if spec == 'a':
... return str(self.value)
... if spec == 'b':
... return ''.join(reversed(str(self.value)))
... raise ValueError("Unknown format code {!r}".format(spec))
...

format(Foo(42), 'a')

'42'

format(Foo(42), 'b')

'24'

The same format specifications can then also be passed to str.format:


'{0:a} reversed is {0:b}'.format(Foo(42))

'42 reversed is 24'

Unfortunately, there does not seem to be a good reference to the
format specifications available for built-in types beyond basic
strings and numbers.  I only knew about the datetime example because
it is used in an example in the str.format docs.  The
datetime.__format__ implementation (which seems to be just a thin
wrapper of datetime.strftime) does not seem to be documented anywhere
in the datetime module docs.



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


Re: Yet another Python textbook

2012-11-22 Thread Terry Reedy

On 11/22/2012 7:24 AM, Colin J. Williams wrote:


 From my reading of the docs, it seems to me that the three following
should be equivalent:


We read differently...


   (a) formattingStr.format(values)


Where 'values' is multiple arguments


with
   (b) format(values, formattingStr)


"format(value[, format_spec])
Convert a value to a “formatted” representation, as controlled by 
format_spec."


I notice that you did not pass multiple args, but indeed just one.
A 'format_spec' is only part of a {} formatting field.


or
   (c) tupleOfValues.__format__(formattingStr


>>> tuple.__format__


Which of to say, not specific to tuples.


Example:
print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
print(format((-25.61, 95), '{:-^14f}{:^14d}'))


"The interpretation of format_spec will depend on the type of the value 
argument, however there is a standard formatting syntax that is used by 
most built-in types: Format Specification Mini-Language." (The latter is 
link to the FSML.


'-^14f' and '^14d' are format_specs.
'{:-^14f}{:^14d}' is a format string that includes two fields with 
format specs. It is not a format spec in itself and is therefore invalid 
by the doc.



(-25.61, 95 ).__format__('{:-^14f}{:^14d}')

The second fails, perhaps because values can only be a single value.


You only passed one, but you did not pass a format spec and indeed there 
is none for tuples. As delivered, format specs only format strings and 
numbers as strings. Collection classes other than str recursively format 
their members using str() or repr() until they reach strings, numbers, 
or customs class instances with custom .__format__ methods.



Should we retreat to %-formatting for now?


Nonsense. The issues above are the same for % formatting. If you try to 
format one object with two % format specs, it will fail for the same 
reason. Try the % equivalent of what failed.


'%-14f%14d' % ((-25.61, 95 ),)

--
Terry Jan Reedy


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


Re: Spam source (Re: Horror Horror Horror!!!!!)

2012-11-22 Thread Robert Miles
On Sunday, November 18, 2012 8:18:53 PM UTC-6, Mark Lawrence wrote:
> On 18/11/2012 19:31, Terry Reedy wrote:
> 
> > The question was raised as to how much spam comes from googlegroups.
> 
> I don't know the answer but I take the greatest pleasure in hurtling 
> onto the dread googlegroups and gmane to report spam. Thankfully it's 
> easy as the amount I receive via gmane is effectively zero.  YMMV?

It now takes two people reporting the same spam to get google groups
to do much about it.  I just reported this one as well, though.


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


Re: 10 sec poll - please reply!

2012-11-22 Thread Michael Herrmann
Hi,

thanks for your prompt reply; I agree that there is also this ambiguity. This 
would go away if we were to use `type` but as I said we don't dare to do that. 
That's the problem with short names - they're always ambiguous at least to some 
extent. 

The only alleviation I can offer for the valid concern you are raising is that 
the user will notice upon the very first use that Enter is not pressed after 
the text has been typed in, and then (if necessary) add a `press(ENTER)` 
afterwards.

It's a pity that `type` is taken... It's very tempting to just use it. But then 
again you might have people trying to `type(ALT + TAB)`, which in our current 
proposal can only be input using `press`...

What do the others think about this?

Cheers

On Thursday, November 22, 2012 8:08:39 PM UTC+1, Chris Angelico wrote:
> On Fri, Nov 23, 2012 at 5:00 AM, Michael Herrmann
> 
> <...> wrote:
> 
> > In our gut feeling, the words apart from `type` that would most normally be 
> > used in an everyday conversation to express the three examples I have given 
> > in my first mail are:
> 
> > press(CTRL + 'a')
> 
> > enter("Hello World")
> 
> > press(ENTER)
> 
> 
> 
> Looks fairly good, except for one possible problem: The verb "enter"
> 
> often means "type this, and then press the Enter key". (For instance,
> 
> "open up a terminal/shell and enter this command".) Is that likely to
> 
> be a point of confusion?
> 
> 
> 
> It's plenty plausible either way. I like the multiple-keystrokes version:
> 
> > press(ALT + 'f', 's')
> 
> and the split API does make good sense.
> 
> 
> 
> ChrisA

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


Re: 10 sec poll - please reply!

2012-11-22 Thread Chris Angelico
On Fri, Nov 23, 2012 at 5:00 AM, Michael Herrmann
 wrote:
> In our gut feeling, the words apart from `type` that would most normally be 
> used in an everyday conversation to express the three examples I have given 
> in my first mail are:
> press(CTRL + 'a')
> enter("Hello World")
> press(ENTER)

Looks fairly good, except for one possible problem: The verb "enter"
often means "type this, and then press the Enter key". (For instance,
"open up a terminal/shell and enter this command".) Is that likely to
be a point of confusion?

It's plenty plausible either way. I like the multiple-keystrokes version:
> press(ALT + 'f', 's')
and the split API does make good sense.

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


Re: Print value from array

2012-11-22 Thread Alister
On Thu, 22 Nov 2012 10:44:02 -0800, Mike wrote:

> Hello,
> I am noob en python programing,  i wrote a perl script for read from csv
> but now i wish print value but the value must be within double quote and
> I can not do this.
> 
> For example now the output is:
> 
> ma user@domain displayName Name SecondName givenName Name sn SecondName
> cn Name
> 
> and i wish
> 
> ma "user@domain" displayName "Name Lastname" givenName "Name" sn
> "SecondName" cn "Name"
> 
> My script is
> 
> #!/usr/bin/python import csv
> 
> with open ('file.csv', 'rb') as f:
>   reader = csv.reader (f, delimiter=';' )
>   for row in reader:
>   mail = row [0]
>   name = row [1]
>   lastname = row [2]
>   name2  = row [1] + ' ' + row [2]
>   
>   print  'ma ' + mail + ' displayName ' +  name2.title() + 
' givenName '
>   + name.title() + ' sn ' + lastname.title() + ' cn ' + 
name.title()
> 
>   #   print '\n'
> 
> f.close()

concatenation is not the python way to build strings
double quotes can be included in single quoted strings ( & vice Versa)
try using the string formatting options, something like


print 'ma "{}" display name "{}" Given Name "{}" sn "{}" cn "{}"'.format
((mail,name2.title(),name.title(),lastname.title(),name.title()))


-- 
"Plan to throw one away.  You will anyway."
- Fred Brooks, "The Mythical Man Month"
-- 
http://mail.python.org/mailman/listinfo/python-list


Print value from array

2012-11-22 Thread Mike
Hello,
I am noob en python programing,  i wrote a perl script for read from csv but 
now i wish print value but the value must be within double quote and I can not 
do this. 

For example now the output is:

ma user@domain displayName Name SecondName givenName Name sn SecondName cn Name

and i wish

ma "user@domain" displayName "Name Lastname" givenName "Name" sn "SecondName" 
cn "Name"

My script is

#!/usr/bin/python
import csv

with open ('file.csv', 'rb') as f:
reader = csv.reader (f, delimiter=';' )
for row in reader:
mail = row [0]
name = row [1]
lastname = row [2]
name2  = row [1] + ' ' + row [2]

print  'ma ' + mail + ' displayName ' +  name2.title() + ' 
givenName ' + name.title() + ' sn ' + lastname.title() + ' cn ' + name.title()  

#   print '\n'

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


Re: Yet another Python textbook

2012-11-22 Thread Ian Kelly
On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams  wrote:
> From my reading of the docs, it seems to me that the three following should
> be equivalent:
>
>   (a) formattingStr.format(values)
> with
>   (b) format(values, formattingStr)
> or
>   (c) tupleOfValues.__format__(formattingStr
>
> Example:
> print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
> print(format((-25.61, 95), '{:-^14f}{:^14d}'))
> (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
>
> The second fails, perhaps because values can only be a single value.
> The third fails, the reason is unclear.

The latter two (which are more or less equivalent) fail because they are
intended for invoking the formatting rules of a single value.  The
string argument to each of them is not a format string, but a "format
specification", which in a format string is only the part that goes
inside the curly braces and after the optional colon.  For example, in
this format string:

>>> 'Hello world {0!s:_>4s}'.format(42)
'Hello world __42'

The format specifier here is "_>4s":

>>> format('42', '_>4s')
'__42'

The valid format specifiers depend upon the type of the object being formatted:

>>> format(42, '04x')
'002a'

>>> format(datetime(2012, 11, 22, 11, 17, 0), 'The time is %Y %d %m %H:%M:%S')
'The time is 2012 22 11 11:17:00'

Custom types can implement custom format specifications by overriding
the __format__ method:

>>> class Foo:
... def __init__(self, value):
... self.value = value
... def __format__(self, spec):
... if spec == 'a':
... return str(self.value)
... if spec == 'b':
... return ''.join(reversed(str(self.value)))
... raise ValueError("Unknown format code {!r}".format(spec))
...
>>> format(Foo(42), 'a')
'42'
>>> format(Foo(42), 'b')
'24'

The same format specifications can then also be passed to str.format:

>>> '{0:a} reversed is {0:b}'.format(Foo(42))
'42 reversed is 24'

Unfortunately, there does not seem to be a good reference to the
format specifications available for built-in types beyond basic
strings and numbers.  I only knew about the datetime example because
it is used in an example in the str.format docs.  The
datetime.__format__ implementation (which seems to be just a thin
wrapper of datetime.strftime) does not seem to be documented anywhere
in the datetime module docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent behaviour os str.find/str.index when providing optional parameters

2012-11-22 Thread Giacomo Alzetta
Il giorno giovedì 22 novembre 2012 09:44:21 UTC+1, Steven D'Aprano ha scritto:
> On Wed, 21 Nov 2012 23:01:47 -0800, Giacomo Alzetta wrote:
> 
> 
> 
> > Il giorno giovedì 22 novembre 2012 05:00:39 UTC+1, MRAB ha scritto:
> 
> >> On 2012-11-22 03:41, Terry Reedy wrote: It can't return 5 because 5
> 
> >> isn't an index in 'spam'.
> 
> >> 
> 
> >> 
> 
> >> 
> 
> >> It can't return 4 because 4 is below the start index.
> 
> > 
> 
> > Uhm. Maybe you are right, because returning a greater value would cause
> 
> > an IndexError, but then, *why* is 4 returned???
> 
> > 
> 
>  'spam'.find('', 4)
> 
> > 4
> 
>  'spam'[4]
> 
> > Traceback (most recent call last):
> 
> >   File "", line 1, in 
> 
> > IndexError: string index out of range
> 
> > 
> 
> > 4 is not a valid index either. I do not think the behaviour was
> 
> > completely intentional.
> 
> 
> 
> 
> 
> The behaviour is certainly an edge case, but I think it is correct.
> 
> 
> 
> (Correct or not, it has been the same going all the way back to Python 
> 
> 1.5, before strings even had methods, so it almost certainly will not be 
> 
> changed. Changing the behaviour now will very likely break hundreds, 
> 
> maybe thousands, of Python programs that expect the current behaviour.)
> 


My point was not to change the behaviour but only to point out this possible 
inconsistency between what str.find/str.index do and what they claim to do in 
the documentation.

Anyway I'm not so sure that changing the behaviour would break many programs... 
I mean, the change would only impact code that was looking for an empty string 
over the string's bounds. I don't see often using the lo and hi parameters for 
find/index, and I think I never saw someone using them when they get out of 
bounds. If you add looking for the empty string I think that the number of 
programs breaking will be minimum. And even if they break, it would be really 
easy to fix them.

Anyway, I understand what you mean and maybe it's better to keep this (at least 
to me) odd behaviour for backwards compatibility.



> 
> By this logic, "spam".find("", 4) should return 4, because cut #4 is 
> 
> immediately to the left of the empty string. So Python's current 
> 
> behaviour is justified.
> 
> 
> 
> What about "spam".find("", 5)? Well, if you look at the string with the 
> 
> cuts marked as before:
> 
> 
> 
> 0-1-2-3-4
> 
> |s|p|a|m|
> 
> 
> 
> you will see that there is no cut #5. Since there is no cut #5, we can't 
> 
> sensibly say we found *anything* there, not even the empty string. If you 
> 
> have four boxes, you can't say that you found anything in the fifth box.
> 
> 
> 
> I realise that this behaviour clashes somewhat with the slicing rule that 
> 
> says that if the slice indexes go past the end of the string, you get an 
> 
> empty string. But that rule is more for convenience than a fundamental 
> 
> rule about strings.

Yeah, I understand what you say, but the logic you pointed out is never cited 
anywhere, while slices are cited in the docstring.


> 
> > The docstring does not describe this edge case, so I think it could be
> 
> > improved. If the first sentence(being an index in S) is kept, than it
> 
> > shouldn't say that start and end are treated as in slice notation,
> 
> > because that's actually not true. 
> 
> 
> 
> +1
> 
> 
> 
> I think that you are right that the documentation needs to be improved.

Definitely. The sentence "Optional
arguments start and end are interpreted as in slice notation." should be 
changed to something like:
"Optional arguments start and end are interpreted as in slice notation, unless 
start is (strictly?) greater than the length of S or end is smaller than start, 
in which cases the search always fails."

In this way the 'spam'.find('', 4) *is* documented because start=len(S) -> 
start and end are treated like in slice notation and 4 makes sense, while 
'spam'.find('', 5) -> -1 because 5 > len('spam') and thus the search fails
and also 'spam'.find('', 3, 2) -> -1 makes sense because 2 < 3(this edge case 
makes more sense, even though 'spam'[3:2] is still the empty string...).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 10 sec poll - please reply!

2012-11-22 Thread Michael Herrmann
Dear all,

thank you for your replies. After experimenting with your suggestions, we have 
arrived at a solution that we believe fits well with our existing API. However, 
before we implement this solution, we would like to ask you one last time to 
sign off on our proposal or raise any serious problems you see with it.

We took the fact that naming our one function 'type' was so difficult to name 
as an indicator that it may be trying to do too many things: On the one hand, 
it allows you to enter plain text as in `type("Hello World!")`; on the other 
hand, it lets you press single keys, possibly in combination with control keys 
as for instance in `type(CTRL + 'a')`. We believe it won't normally be 
necessary to combine the two. For instance, while you could see what
type(CTRL + 'a' + "Hello World!")
does, we think you would be more likely to use the two separate calls
type(CTRL + 'a')
type("Hello World!")

One of the main goals of our automation product is that using it should feel 
like giving instructions to a human being looking over their shoulder at a 
screen. For this reason, it's very useful for us if the function names in our 
API are short, if possible without underscores, and close to the vocabulary you 
would use in an everyday conversation. We hope that by offering an API with 
this property, we can not only make it easier to use for experienced 
programmers such as yourself, but also be approachable for people from a less 
technical background.

In our gut feeling, the words apart from `type` that would most normally be 
used in an everyday conversation to express the three examples I have given in 
my first mail are:
press(CTRL + 'a')
enter("Hello World")
press(ENTER)

We really quite like the word `type`, and a few people here seem to favour it 
too. In particular, Steven: We're glad you accidentally clicked on our mail. 
Thank you for your inputs and the great quote by Phil Karlton. We think you 
were right in everything you said. However, some people seem to be *really* put 
off when you override a built-in function. Even though of course you can avoid 
the overriding by saying
from automa.api import type *as* ...,
(as Tim pointed out) we'd like to avoid irritating those people. For this 
reason, we would rather not use `type`.

Many people here voted for send_keys(...). We agree with Dave and Neil that 
`type` may have too many uses already. As Chris and MRAB pointed out, 
'send_keys' is used in many other automation tools. This makes it intuitive for 
people with knowledge of such tools. However, as I said above (and should have 
probably said earlier), we are also trying to reach users from a less technical 
background. Since these people would not normally use 'send_keys' in an 
everyday conversion, we are afraid that it would not be an intuitive name for 
them. A similar argument applies to some extent to our 'type_keys', to our 
'generate_keystrokes', Ramit's 'simulate_keypress', 'simulate_key(s)_down', 
'send_kb_press', 'fake_typing' and 'send_char(s)' and Tim's 'feedkeys'. We 
thank you for your suggestions. Hopefully you can also agree with our choice!

Some suggestions were very nice, short and pretty unambiguous, such as Dennis' 
`emit` and particularly Alan's `strike`. However, they're unfortunately also 
rather rarely used and we'd be afraid that it'd be hard to remember them. Thank 
you though!

A final point that Evan made and that also we find very important is to have 
verbs in our function names. 

Our proposed solution is to split what we previously called `type` into two 
functions, 'press' and 'enter' (proposed by xDog Walker). 'press' could be used 
to press single keys or combinations of them, at once:
press(CTRL + 'a')
press(ENTER)
To open a menu via the keyboard, you could also supply several key combinations 
to be pressed, in sequence:
press(ALT + 'f', 's')
'enter' on the other hand would be used to enter longer strings of plain text:
enter("Hello World!")
With a functionality we already have, you could supply an optional 'into' 
parameter that selects a text field into which the text is entered:
enter("test.txt", into="File name")
'enter' currently does involve generating same system events that are fired 
when pressing (and releasing) sequences of keys. However, we did not want to 
include this technical detail in the function name - it keeps the name shorter, 
makes it more intuitive for users from a less technical background and also 
leaves us to change this implementation detail in the future.

These names aren't perfect. As Emile rightly pointed out, several tools 
distinguish between 'press' and 'release' and a user might wonder how to 
release a key that was pressed using 'press'. That's an ambiguity that is 
certainly there, however we hope that once the user has at least seen
press(ENTER)
it is clear what is meant. Distinguishing between pressing 

Re: Constructing JSON data structures from non-string key python dictionaries

2012-11-22 Thread saikari78
Thanks for all these very clarifying and useful replies

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


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Marc Aymerich
On Thursday, November 22, 2012 5:26:59 PM UTC+1, Dave Angel wrote:
> On 11/22/2012 11:12 AM, Thomas Bach wrote:
> 
> > On Thu, Nov 22, 2012 at 10:52:56AM -0500, Dave Angel wrote:
> 
> >> On 11/22/2012 10:14 AM, Marc Aymerich wrote:
> 
> >>> I want to create a method within a class that is able to accept either a 
> >>> class or an instance.
> 
> >>>
> 
> >> I haven't tried it, but how about if you do a @classmethod decorator,
> 
> >> and then just use isinstance(param, MyClass) ?
> 
> >>
> 
> > This won't work:
> 
> >
> 
> > In [22]: class Foo(object):
> 
> >: @classmethod
> 
> >: def bar(cls):
> 
> >: print repr(cls)
> 
> >: 
> 
> >
> 
> > In [23]: Foo.bar()
> 
> > 
> 
> >
> 
> > In [24]: Foo().bar()
> 
> > 
> 
> >
> 
> > Actually help(classmethod) explicitly says so:
> 
> > 
> 
> > It can be called either on the class (e.g. C.f()) or on an instance
> 
> > (e.g. C().f()).  The instance is ignored except for its class.
> 
> > 
> 
> 
> 
> OK, thanks.  I hadn't tried it, and hadn't noticed that that decorator
> 
> converts to the class.
> 
> 
> 
> >
> 
> > I think the way to go is via the descriptor protocol[1] as suggested
> 
> > by Peter.
> 
> >
> 
> > Regards,
> 
> > Thomas.
> 
> >
> 
> >
> 
> > Footnotes: 
> 
> > [1] http://docs.python.org/3/howto/descriptor.html
> 
> >
> 
> The OP should probably use this link instead, since he's not using Python 3.
> 
> 
> 
> http://docs.python.org/2.7/howto/descriptor.html
> 
> 
> 
> Marc:  I believe the descriptor stuff has changed in Python 3;  I don't
> 
> use it.  But if you've got to do this, and you have to do it in Python
> 
> 2.x, you'd better use the 2.x documentation.
> 


thanks for the links Thomas and Dave, I'm going to read this documentation 
right now, I love to learn this kind of python 'internals' :) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Marc Aymerich
On Thursday, November 22, 2012 4:51:30 PM UTC+1, Peter Otten wrote:
> Marc Aymerich wrote:
> 
> 
> 
> > Hi,
> 
> > 
> 
> > I want to create a method within a class that is able to accept either a
> 
> > class or an instance.
> 
> > 
> 
> > class MyClass(object):
> 
> > @magic_decorator
> 
> > def method(param):
> 
> > # param can be MyClass (cls) or an instance of MyClass (self)
> 
> > 
> 
> > so I can do something like:
> 
> > 
> 
> > instance = MyClass()
> 
> > 
> 
> > MyClass.method()
> 
> > instance.method()
> 
> > 
> 
> > I guess the way to go is implementing a custom decorator (@magic_decorator
> 
> > in my example), but, how can I know if the method has been called from the
> 
> > class o from an instance?
> 
> > 
> 
> > Thank you very much!!
> 
> 
> 
> Why would you overload a method that way?

Yep, it's an strange pattern sure it can be done in a better way but this is 
the best I can think on, the context is:

I'm developing a permission system which can give general permissions for a 
given class and also specific permissions for a given object.

class Node(object):
   @role
   def has_perm(instance, user)
  if is_class(instance): then global perm for user...
  else: then specific perm for user...


> 
> $ cat class_or_inst.py
> 
> import functools
> 
> 
> 
> class desc(object):
> 
> def __init__(self, f):
> 
> self._f = f
> 
> def __get__(self, inst=None, class_=None):
> 
> if inst is not None:
> 
> return functools.partial(self._f, self=inst)
> 
> elif class_ is not None:
> 
> return functools.partial(self._f, class_=class_)
> 
> raise TypeError("nobody expects the Spanish inquisition")
> 
> 
> 
> 
> 
> 
> 
> class A(object):
> 
> @desc
> 
> def f(self=None, class_=None):
> 
> if self is not None:
> 
> return "instance"
> 
> elif class_ is not None:
> 
> return "class"
> 
> return "unknown"
> 
> $ python -i class_or_inst.py 
> 
> >>> A.f()
> 
> 'class'
> 
> >>> A().f()
> 
> 'instance'
> 
> >>> A.__dict__["f"].__get__()
> 
> Traceback (most recent call last):
> 
>   File "", line 1, in 
> 
>   File "class_or_inst.py", line 11, in __get__
> 
> raise TypeError("nobody expects the Spanish inquisition")
> 
> TypeError: nobody expects the Spanish inquisition

you are a genius! I've implemented this on my code and it works as expected ! 
Thanks :D
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Dave Angel
On 11/22/2012 11:12 AM, Thomas Bach wrote:
> On Thu, Nov 22, 2012 at 10:52:56AM -0500, Dave Angel wrote:
>> On 11/22/2012 10:14 AM, Marc Aymerich wrote:
>>> I want to create a method within a class that is able to accept either a 
>>> class or an instance.
>>>
>> I haven't tried it, but how about if you do a @classmethod decorator,
>> and then just use isinstance(param, MyClass) ?
>>
> This won't work:
>
> In [22]: class Foo(object):
>: @classmethod
>: def bar(cls):
>: print repr(cls)
>: 
>
> In [23]: Foo.bar()
> 
>
> In [24]: Foo().bar()
> 
>
> Actually help(classmethod) explicitly says so:
> 
> It can be called either on the class (e.g. C.f()) or on an instance
> (e.g. C().f()).  The instance is ignored except for its class.
> 

OK, thanks.  I hadn't tried it, and hadn't noticed that that decorator
converts to the class.

>
> I think the way to go is via the descriptor protocol[1] as suggested
> by Peter.
>
> Regards,
>   Thomas.
>
>
> Footnotes: 
> [1] http://docs.python.org/3/howto/descriptor.html
>
The OP should probably use this link instead, since he's not using Python 3.

http://docs.python.org/2.7/howto/descriptor.html

Marc:  I believe the descriptor stuff has changed in Python 3;  I don't
use it.  But if you've got to do this, and you have to do it in Python
2.x, you'd better use the 2.x documentation.


-- 

DaveA

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


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Thomas Bach
On Thu, Nov 22, 2012 at 10:52:56AM -0500, Dave Angel wrote:
> On 11/22/2012 10:14 AM, Marc Aymerich wrote:
> > I want to create a method within a class that is able to accept either a 
> > class or an instance.
> >
> 
> I haven't tried it, but how about if you do a @classmethod decorator,
> and then just use isinstance(param, MyClass) ?
> 

This won't work:

In [22]: class Foo(object):
   : @classmethod
   : def bar(cls):
   : print repr(cls)
   : 

In [23]: Foo.bar()


In [24]: Foo().bar()


Actually help(classmethod) explicitly says so:

It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()).  The instance is ignored except for its class.


I think the way to go is via the descriptor protocol[1] as suggested
by Peter.

Regards,
Thomas.


Footnotes: 
[1] http://docs.python.org/3/howto/descriptor.html

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


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Dave Angel
On 11/22/2012 10:14 AM, Marc Aymerich wrote:
> Hi,
>
> I want to create a method within a class that is able to accept either a 
> class or an instance.
>
> class MyClass(object):
> @magic_decorator
> def method(param):
> # param can be MyClass (cls) or an instance of MyClass (self)
>
> so I can do something like:
>
> instance = MyClass()
>
> MyClass.method()
> instance.method()
>
> I guess the way to go is implementing a custom decorator (@magic_decorator in 
> my example), but, how can I know if the method has been called from the class 
> o from an instance?
>
> Thank you very much!!

I haven't tried it, but how about if you do a @classmethod decorator,
and then just use isinstance(param, MyClass) ?



-- 

DaveA

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


Re: method that can be called from a class and also from an instance

2012-11-22 Thread Peter Otten
Marc Aymerich wrote:

> Hi,
> 
> I want to create a method within a class that is able to accept either a
> class or an instance.
> 
> class MyClass(object):
> @magic_decorator
> def method(param):
> # param can be MyClass (cls) or an instance of MyClass (self)
> 
> so I can do something like:
> 
> instance = MyClass()
> 
> MyClass.method()
> instance.method()
> 
> I guess the way to go is implementing a custom decorator (@magic_decorator
> in my example), but, how can I know if the method has been called from the
> class o from an instance?
> 
> Thank you very much!!

Why would you overload a method that way?

$ cat class_or_inst.py
import functools

class desc(object):
def __init__(self, f):
self._f = f
def __get__(self, inst=None, class_=None):
if inst is not None:
return functools.partial(self._f, self=inst)
elif class_ is not None:
return functools.partial(self._f, class_=class_)
raise TypeError("nobody expects the Spanish inquisition")



class A(object):
@desc
def f(self=None, class_=None):
if self is not None:
return "instance"
elif class_ is not None:
return "class"
return "unknown"
$ python -i class_or_inst.py 
>>> A.f()
'class'
>>> A().f()
'instance'
>>> A.__dict__["f"].__get__()
Traceback (most recent call last):
  File "", line 1, in 
  File "class_or_inst.py", line 11, in __get__
raise TypeError("nobody expects the Spanish inquisition")
TypeError: nobody expects the Spanish inquisition



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


method that can be called from a class and also from an instance

2012-11-22 Thread Marc Aymerich
Hi,

I want to create a method within a class that is able to accept either a class 
or an instance.

class MyClass(object):
@magic_decorator
def method(param):
# param can be MyClass (cls) or an instance of MyClass (self)

so I can do something like:

instance = MyClass()

MyClass.method()
instance.method()

I guess the way to go is implementing a custom decorator (@magic_decorator in 
my example), but, how can I know if the method has been called from the class o 
from an instance?

Thank you very much!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another Python textbook

2012-11-22 Thread Colin J. Williams

From Yet another Python textbook
On 21/11/2012 5:17 PM, Chris Angelico wrote:

On Thu, Nov 22, 2012 at 4:03 AM, Colin J. Williams  wrote:

On 20/11/2012 4:00 PM, Chris Angelico wrote:

To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
strings. Take no notice; the rest of the world sees this as a huge
advantage. Python is now in a VERY small group of languages (I'm aware
of just one other) that have absolutely proper Unicode handling *and*
efficient string handling.

ChrisA


It's interesting to see that someone else finds the format function to be a
pain.  Perhaps the problem lies with the documentation.


Hang on, what? I'm not sure where the format function comes in. I was
referring to the underlying representation.

The OP wrote:
  "The absurd flexible string representation has practically
borrowed the idea to propose once Python has a teaching tool."

I perhaps stretched this to refer specifically on one aspect, formatting 
in my comment.


That said, though, I'm just glad that %-formatting is staying. It's an
extremely expressive string formatting method, and exists in many
languages (thanks to C's heritage). Pike's version is insanely
powerful, Python's is more like C's, but all three are compact and
convenient.

str.format(), on the other hand, is flexible. It strikes me as rather
more complicated than a string formatting function needs to be, but
that may be a cost of its flexibility.

ChrisA


Yes is is complicated.

From my reading of the docs, it seems to me that the three following 
should be equivalent:


  (a) formattingStr.format(values)
with
  (b) format(values, formattingStr)
or
  (c) tupleOfValues.__format__(formattingStr

Example:
print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
print(format((-25.61, 95), '{:-^14f}{:^14d}'))
(-25.61, 95 ).__format__('{:-^14f}{:^14d}')

The second fails, perhaps because values can only be a single value.
The third fails, the reason is unclear.

Steven D'Aprano earlier said that a better diagnostic tool is planned 
for Python 3.4.


Should we retreat to %-formatting for now?

Colin W.







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


Re: Simple Question regarding running .py program

2012-11-22 Thread Duncan Booth
Grant Edwards  wrote:

> [1] OK, so I'm am annoyed with them after my Google phone updated to
> Android 4.2 this afternoon and the lock-screen clock is now
> _physically_painful_ to look at.  However, I'm convinced that's
> not evil -- just a complete and utter lack of visual design
> ability.

You can select any other lock screen widget as the default, so why not 
download some more widgets from Play and choose something different. e.g. 
"Beautiful Clock Widgets" or "HD Widgets" but there are probably others.

To change the default lockscreen widget swipe left from the lockscreen 
until you get to a page with only a '+', add the new widget there, then 
long press that widget and drag it to be the rightmost page.

Then you should be sorted just so long as you don't have any friends with 
December birthdays.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitable software stacks for simple python web service

2012-11-22 Thread Kev Dwyer
Dieter Maurer wrote:


> 
> From your description (so far), you would not need a web framework
> but could use any way to integrate Python scripts into a web server,
> e.g. "mod_python", "cgi", "WSGI", 
> Check what ways your web server will suport.

Hello Dieter

Thanks for your comment.  I certainly want a lightweight solution so 
CGI or one of the micro-frameworks are what I am considering. 

Cheers

Kev

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


Re: Update slider widget range

2012-11-22 Thread Mark Lawrence

On 21/11/2012 13:59, moadeep wrote:

I am trying to write a small bit of code that interactively deletes selected 
slices in an image series using matplotlib. I have created a button 'delete' 
which stores a number of indices to be deleted when the button 'update' is 
selected. However, I am currently unable to reset the range of my slider 
widget, i.e. removing the number of deleted slices from valmax. What is the 
pythonic solution to this problem?

 self.nframes =  len(self.raw_dicom_stack)


If I've read your intentions correctly the line above should read

self.slider.valmax = len(self.raw_dicom_stack)

If I'm wrong then please ask on the matplotlib users mailing list or 
possibly stackoverflow.


--
Cheers.

Mark Lawrence.

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


Re: Web Frameworks Excessive Complexity

2012-11-22 Thread Thomas Bach
On Wed, Nov 21, 2012 at 12:49:52PM -0800, rh wrote:
> 
> wheezy + "myvirtualenv" = 3.3MB
> pyramid = 92MB

$ mkvirtualenv --no-site-packages -p python2.7 pyramid
$ pip install -U distribute
$ pip install pyramid
$ du -h .virtualenvs/pyramid 
22M .virtualenvs/pyramid
$ du -s .virtualenvs/pyramid/lib/python2.7/site-packages/* | sort -n | tail -n 
5 
728 .virtualenvs/pyramid/lib/python2.7/site-packages/pip-1.1-py2.7.egg
1556.virtualenvs/pyramid/lib/python2.7/site-packages/setuptools
1724.virtualenvs/pyramid/lib/python2.7/site-packages/zope
2044.virtualenvs/pyramid/lib/python2.7/site-packages/chameleon
6312.virtualenvs/pyramid/lib/python2.7/site-packages/pyramid

I think 22 MB are OK given the functionality Pyramid has to offer.

Just my 2 cents,
 Thomas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Constructing JSON data structures from non-string key python dictionaries

2012-11-22 Thread Paul Kölle

Am 21.11.2012 17:04, schrieb hfo...@gmail.com:

Thanks for your reply, but the javascript function expects option
names to be unquoted, otherwise it won't work.
Others have shown you how to solve this, but I would like to note that 
the function does NOT expect JSON but a simple javascript object literal.


cheers
 Paul



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


Re: Inconsistent behaviour os str.find/str.index when providing optional parameters

2012-11-22 Thread Steven D'Aprano
On Wed, 21 Nov 2012 23:01:47 -0800, Giacomo Alzetta wrote:

> Il giorno giovedì 22 novembre 2012 05:00:39 UTC+1, MRAB ha scritto:
>> On 2012-11-22 03:41, Terry Reedy wrote: It can't return 5 because 5
>> isn't an index in 'spam'.
>> 
>> 
>> 
>> It can't return 4 because 4 is below the start index.
> 
> Uhm. Maybe you are right, because returning a greater value would cause
> an IndexError, but then, *why* is 4 returned???
> 
 'spam'.find('', 4)
> 4
 'spam'[4]
> Traceback (most recent call last):
>   File "", line 1, in 
> IndexError: string index out of range
> 
> 4 is not a valid index either. I do not think the behaviour was
> completely intentional.


The behaviour is certainly an edge case, but I think it is correct.

(Correct or not, it has been the same going all the way back to Python 
1.5, before strings even had methods, so it almost certainly will not be 
changed. Changing the behaviour now will very likely break hundreds, 
maybe thousands, of Python programs that expect the current behaviour.)

Consider your string as a sequence of boxes, with index positions 
labelled above the string:


0-1-2-3-4
|s|p|a|m|

The indexing model is that positions represent where you would cut 
*between* characters, not the character itself. Slices are the substring 
between cuts:

"spam"[1:3] => "pa"

while single indexes return the character to the right of the cut:

"spam"[1] => "p"

If there is no character to the right of the cut, indexing raises an 
error.


Now, consider "spam".find(substring, start). This should return the 
number of the first cut immediately to the left of the substring, 
beginning the search at cut #start.

"spam".find("pa", 1) => 1

because cut #1 is immediately to the left of "pa" at index 1.

By this logic, "spam".find("", 4) should return 4, because cut #4 is 
immediately to the left of the empty string. So Python's current 
behaviour is justified.

What about "spam".find("", 5)? Well, if you look at the string with the 
cuts marked as before:

0-1-2-3-4
|s|p|a|m|

you will see that there is no cut #5. Since there is no cut #5, we can't 
sensibly say we found *anything* there, not even the empty string. If you 
have four boxes, you can't say that you found anything in the fifth box.

I realise that this behaviour clashes somewhat with the slicing rule that 
says that if the slice indexes go past the end of the string, you get an 
empty string. But that rule is more for convenience than a fundamental 
rule about strings.

I think there is legitimate room for disagreement about the "right" 
behaviour here, but backwards compatibility trumps logical correctness 
here, and it is very unlikely to be changed.


> The docstring does not describe this edge case, so I think it could be
> improved. If the first sentence(being an index in S) is kept, than it
> shouldn't say that start and end are treated as in slice notation,
> because that's actually not true. 

+1

I think that you are right that the documentation needs to be improved.




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


Re: mysql insert with tuple

2012-11-22 Thread Christian
Am Mittwoch, 21. November 2012 20:49:14 UTC+1 schrieb Hans Mulder:
> On 21/11/12 18:19:15, Christian wrote:
> 
> > Hi ,
> 
> > 
> 
> > my purpose is a generic insert via  tuple , because the number of fields 
> > and can differ. But  I'm stucking .
> 
> > 
> 
> > ilist=['hello',None,7,None,None]
> 
> > 
> 
> > #This version works, but all varchar fields are in extra '' enclosed.
> 
> > con.execute(""" INSERT INTO {} VALUES %r; """.format(table) , 
> > (tuple(ilist),))
> 
> > 
> 
> > #This produce (1054, "Unknown column 'None' in 'field list'"),
> 
> > #but without None values it works.
> 
> > con.execute(""" INSERT INTO {} VALUES %r; """.format(table) % 
> > (tuple(ilist),))
> 
> 
> 
> How about:
> 
> 
> 
> con.execute("""INSERT INTO {} VALUES ({})"""
> 
> .format(table, ",".join("%s" for _ in ilist)), ilist)
> 
> 
> 
> Or perhaps break it down into smaller steps:
> 
> 
> 
> bind_variables = ",".join("%s" for _ in ilist))
> 
> query = "INSERT INTO {} VALUES ({})".format(table, bind_variables)
> 
> con.execute(query, ilist)
> 
> 
> 
> 
> 
> Hope this helps,
> 
> 
> 
> -- HansM

Thank you both!. However, for future issues  I'll take Chris advise about a ORM 
into account . It's  only a sort of  data crunching (offline), so SQL Injection 
isn't a problem.
-- 
http://mail.python.org/mailman/listinfo/python-list