Re: How to waste computer memory?

2016-03-19 Thread Steven D'Aprano
On Sun, 20 Mar 2016 03:12 am, Marko Rauhamaa wrote:

> Steven D'Aprano :
> 
>> On Sun, 20 Mar 2016 02:02 am, Marko Rauhamaa wrote:
>>> Yes, but UTF-16 produces 16-bit values that are outside Unicode.
>>
>> Show me.
>>
>> Before you answer, if your answer is "surrogate pairs", that is
>> incorrect. Surrogate pairs is how UTF-16 encodes astral characters.
> 
> UTF-16 inputs a Unicode stream and produces a stream of 16-bit numbers.
> Thus, the output of UTF-16 is not Unicode.

I'm not sure what point you think you are making.

Unicode (the character set part of it) is a set of abstract 23-bit numbers,
or code points, representing (among other things) characters, and numbered
from U+ to U+10. Any UTF is, by definition, a transformation from
such abstract code points to sequences of machine words or bytes (and vice
versa). What's your point?

If your point is that the data you get from running UTF-16 on a sequence of
code points is "not Unicode, but 2-byte words", then I agree, but I'm not
sure why you think that's significant.

If you want to call those words "numbers", I cannot really object, but if
so, they aren't abstract numbers (like code points, which may have any
implementation you like), but have their actual base-2 structure specified
by the standard.

If your point is that a UTF-16 encoded stream of bytes is not the same as an
abstract sequence of code points, then I can't disagree, but I don't
understand why you think that's important.


-- 
Steven

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


[issue26576] Tweak wording of decorator docos

2016-03-19 Thread Terry J. Reedy

Terry J. Reedy added the comment:

Guido, the discrepancy between the decorator doc's 'equivalent code' and 
actual, optimized, behavior with regard to skipping an intermediate binding of 
the function to the name came up soon after decorators were added.  I cannot 
find the issue, but as I remember, you said at the time that the doc's 
'equivalent' code was good enough, and perhaps that you did not want to force 
the optimization on other implementations (not sure of this latter).

This issue has come up often enough on Python list and SO that many think that 
the actual behavior should be documented.  But should it be documented as a 
guaranteed language feature or as just an optional optimization?

--
nosy: +gvanrossum, terry.reedy

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: How to waste computer memory?

2016-03-19 Thread sohcahtoa82
On Thursday, March 17, 2016 at 7:34:46 AM UTC-7, wxjm...@gmail.com wrote:
> Very simple. Use Python and its (buggy) character encoding
> model.
> 
> How to save memory?
> It's also very simple. Use a programming language, which
> handles Unicode correctly.

*looks at the other messages in this thread*

...

Whatever happened to the idea of not feeding the trolls?  This image depicts 
this thread perfectly:

http://i.imgur.com/sVtpZDK.png
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue18140] urlparse, urlsplit confused when password includes fragment (#), query (?)

2016-03-19 Thread Martin Panter

Changes by Martin Panter :


--
title: urlparse.urlsplit confused to fragment when password include # -> 
urlparse, urlsplit confused when password includes fragment (#), query (?)
versions: +Python 3.5, Python 3.6

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Case Statements

2016-03-19 Thread Steven D'Aprano
On Thursday 17 March 2016 16:45, Gregory Ewing wrote:

> Steven D'Aprano wrote:
>> On Thu, 17 Mar 2016 11:31 am, Chris Angelico wrote:
>> 
>>>orig = globals()[cls.__name__]
>> 
>> I wouldn't want to rely on it working with decorator syntax either. Even
>> if it does now, I'm not sure that's a language guarantee.
> 
> The following idiom relies on similar behaviour:
> 
>  @property
>  def x(self):
>  return self._x
> 
>  @x.setter
>  def x(self, value):
>  self._x = value
> 
> That's taken from the official docs, so I don't think
> this is likely to change any time soon.


I don't think that property is a similar situation. I think what happens 
here is that the first call to property sets:

# @property def x...
x = property(x)

Then the second decorator does:

# @x.setter def x...
x = x.setter(x)

which replaces x with a brand new property object.

What happens if you use different names?

@property
def x(self):
pass

@x.setter
def y(self, arg):
pass


Now you have two different properties:

py> x

py> y



Both x and y's getter points to the same function (our original def x):

py> y.fget

py> x.fget



But x's setter is None, while y has a valid setter:

py> x.fset is None
True
py> y.fset



I don't think that either x or y will misbehave, but the behaviour will 
certainly be surprising if you're not expecting it.

I think the documentation in Python 2.7 is misleading. help(x.setter) says:

setter(...)
Descriptor to change the setter on a property.

which is, I believe, a lie. It doesn't "change the setter" (modify the 
property object in place), but returns a new property object. Here's my 
pseudo-code for what I think property.setter does:

class property:
def setter(self, func):
return property(self.fget, func, self.fdel, self.__doc__)



As far as I can tell, none of this behaviour relies on the decorator being 
called before the name of the decorated thing is bound.




-- 
Steve

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


[issue26575] lambda not closed on specific value in comprehension

2016-03-19 Thread Martin Panter

Martin Panter added the comment:

https://docs.python.org/3.5/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

--
nosy: +martin.panter
resolution:  -> not a bug
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26569] pyclbr.readmodule() and pyclbr.readmodule_ex() don't support namespace packages

2016-03-19 Thread Eric Snow

Eric Snow added the comment:

Yeah, I've opened issue26584 to keep the matters separate.  We can address a 
more comprehensive cleanup there.

--
resolution:  -> fixed
stage: commit review -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26250] no document for sqlite3.Cursor.connection

2016-03-19 Thread Roundup Robot

Roundup Robot added the comment:

New changeset 52660878c833 by Ezio Melotti in branch '3.5':
#26250: document the sqlite3.Cursor.connection attribute.  Initial patches by 
Aviv Palivoda and Varpu Rantala.
https://hg.python.org/cpython/rev/52660878c833

New changeset 6fed752fd88e by Ezio Melotti in branch 'default':
#26250: merge with 3.5.
https://hg.python.org/cpython/rev/6fed752fd88e

New changeset 6dcf60bf855b by Ezio Melotti in branch '2.7':
#26250: document the sqlite3.Cursor.connection attribute.  Initial patches by 
Aviv Palivoda and Varpu Rantala.
https://hg.python.org/cpython/rev/6dcf60bf855b

--
nosy: +python-dev

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Bash-like pipes in Python

2016-03-19 Thread Sivan Greenberg
If I understand correctly, the binary right or overloading that's seen here
can be applied to any other computational objects.

I could also think of implementing it for input / output pipes overloading
the __ror__ method with .communicate() method of the Popen object [0].

-Sivan

[0]: https://docs.python.org/2/library/subprocess.html#popen-objects

On Thu, Mar 17, 2016 at 1:49 PM, Marko Rauhamaa  wrote:

> Steven D'Aprano :
>
> > On Thu, 17 Mar 2016 02:20 am, Random832 wrote:
> >> fpipe("abcd12345xyz", pfilter(str.isdigit), pmap(int), preduce(mul))
> >
> > Intriguing! Thank you for the suggestion.
>
> Still want the pipeline syntax!
>
>
> Marko
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Sivan Greenberg
Co founder & CTO
Vitakka Consulting
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sobering observation, python vs. perl

2016-03-19 Thread BartC

On 17/03/2016 18:53, Marko Rauhamaa wrote:

BartC :



sub replacewith{
$s = $_[0];
$t = $_[1];
$u = $_[2];
$s =~ s/$t/$u/;
return $s;
}

Although once done, the original task now looks a proper language:

print (replacewith("I have a dream","have","had"));


Now try your function with:

print (replacewith("I have a dream",".","had"));


Yeah, it needs your quotemeta line (whatever that does). But the call is 
unaffected as the clutter is in the function.


--
bartc

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


Re: Case Statements

2016-03-19 Thread Chris Angelico
On Thu, Mar 17, 2016 at 8:23 PM, Antoon Pardon
 wrote:
> Op 17-03-16 om 03:02 schreef Chris Angelico:
>> On Thu, Mar 17, 2016 at 12:54 PM, Steven D'Aprano  
>> wrote:
>>
>>> I wouldn't want to rely on it working with decorator syntax either. Even if
>>> it does now, I'm not sure that's a language guarantee.
>> That's the thing, though. It's not a guarantee, yet it does work in
>> every Python interpreter that I tried it in.
>
> That depends on what you mean by work. This failes:
> [doing the same thing in a function]

Very true; I could have messed around with getframe, but most classes
are global, and it keeps things simple.

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


[issue26396] Create json.JSONType

2016-03-19 Thread Brett Cannon

Brett Cannon added the comment:

Here is a preliminary patch with docs. I didn't do any tests because I just 
don't know what kind of test we would want. Use isinstance() to make sure it 
covers the types we expect? And I'm not sure how to test the key type for 
mappings.

--
keywords: +patch
stage: needs patch -> patch review
Added file: http://bugs.python.org/file42206/jsontype.diff

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26553] Write HTTP in uppercase

2016-03-19 Thread Aatish Neupane

Changes by Aatish Neupane :


Added file: http://bugs.python.org/file42197/fix_2.7.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26567] ResourceWarning: Use tracemalloc to display the traceback where an object was allocated when a ResourceWarning is emitted

2016-03-19 Thread Roundup Robot

Roundup Robot added the comment:

New changeset 2428d794b0e1 by Victor Stinner in branch 'default':
On ResourceWarning, log traceback where the object was allocated
https://hg.python.org/cpython/rev/2428d794b0e1

--
nosy: +python-dev

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26257] Eliminate buffer_tests.py

2016-03-19 Thread Ezio Melotti

Changes by Ezio Melotti :


--
nosy: +ezio.melotti, serhiy.storchaka

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: monkey patching __code__

2016-03-19 Thread Ian Kelly
On Mar 18, 2016 8:33 AM, "Sven R. Kunze"  wrote:
>
> On 18.03.2016 14:47, Ian Kelly wrote:
>>
>> Your patched version takes two extra arguments. Did you add the
>> defaults for those to the function's __defaults__ attribute?
>
>
> That's it! :-) Thanks a lot.
>
> Just to understand this better: why is that not part of the code object
but part of the function?

Well I didn't design it, so I'm not really sure. But it could be argued
that the defaults are intrinsic to the function declaration, not the code
object, as not all code objects even have arguments. It also makes it
straight-forward to create a new function that uses the same code but with
different defaults or globals.

>> This sounds like a pretty hairy thing that you're trying to do. Surely
>> there must be some better way to accomplish the same goal.
>
>
> We are open for suggestions. We featured our own reverse function for a
while but it lead to inconsistent behaviors across the field. Especially
considering that Django provides an {% url %} template tag which would then
use yet another reverse implementation.

I don't really have a good suggestion. I was mostly hoping that Django
provided a way to hook in a different implementation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Case Statements

2016-03-19 Thread Steven D'Aprano
On Thu, 17 Mar 2016 12:15 am, l0r0m0a0...@gmail.com wrote:

> What hath I wrought?


Dr Ray Stantz: Fire and brimstone coming down from the skies! Rivers and
seas boiling!

Dr Egon Spengler: Forty years of darkness! Earthquakes, volcanoes...

Winston Zeddemore: The dead rising from the grave!

Dr Peter Venkman: Human sacrifice, dogs and cats living together... mass
hysteria! 



-- 
Steven

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


[issue22758] Regression in Python 3.2 cookie parsing

2016-03-19 Thread Berker Peksag

Berker Peksag added the comment:

I will commit this to the 3.2 branch today.

--
status: closed -> open

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: submodules

2016-03-19 Thread Peter Otten
ast wrote:

> Hello
> 
> Since in python3 ttk is a submodule of tkinter, I was expecting this
> to work:
> 
> from tkinter import *
> 
> root = Tk()
> nb = ttk.Notebook(root)
> 
> but it doesnt, ttk is not known.
> 
> I have to explicitely import ttk with
> 
> from tkinter import ttk
> 
> why ?

If there's no tkinter.__all__

from tkinter import *

is basically

import tkinter
globals().update(
 (name, value) for name, value in 
 vars(tkinter).items() if not name.startswith("_")
)
del tkinter

so if "from tkinter import *" doesn't inject ttk in your namespace this 
means that there is no variable tkinter.ttk. This is because there is no

from . import ttk

in tkinter/__init__.py, and automagically importing all candidate submodules 
is inefficient (and unsafe).

However, once you import tkinter.ttk the name is added

>>> import tkinter.ttk
>>> from tkinter import *
>>> ttk


so what you get with the *-import depends on what has been imported before, 
perhaps by other modules. 

Personally I'd avoid the *-import altogether...

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


Re: sobering observation, python vs. perl

2016-03-19 Thread Charles T. Smith
On Thu, 17 Mar 2016 10:52:30 -0500, Tim Chase wrote:

>> Not saying this will make a great deal of difference, but these two
> items jumped out at me.  I'd even be tempted to just use string
> manipulations for the isready aspect as well.  Something like
> (untested)

well, I don't want to forgo REs in order to have python's numbers be better
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bash-like pipes in Python

2016-03-19 Thread Marko Rauhamaa
Sivan Greenberg :

> If I understand correctly, the binary right or overloading that's seen
> here can be applied to any other computational objects.
>
> I could also think of implementing it for input / output pipes
> overloading the __ror__ method with .communicate() method of the Popen
> object [0].

I'm thinking it's all of the above and more!

At the bottom is the generic pipelining of generators.

Then there's the special case of integrating external commands with the
generic framework:

cmd('cat /etc/passwd', stdin=None) | List

(Is "stdin=None" needed?)

Then there's the enriching of data formats. The line-based delineation
is old-school and unsafe, and should be considered for legacy only. The
internal data format is arbitrary Python object sequences, but
externally, JSON should be preferred. Thus, we'll need converters
from/to JSON.

What is still missing is the true generator lambdas:

produce_data | (
lambda name, value:
yield value) | \
consume_values

as in bash:

produce_data |
while read name value; do
echo $value
done |
consume_values


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


[issue26583] test_timestamp_overflow of test_importlib fails if PYTHONDONTWRITEBYTECODE is set

2016-03-19 Thread Ned Deily

Ned Deily added the comment:

Ah, setting PYTHONDONTWRITEBYTECODE explains it.  When running the tests via 
"make test", python is invoked with -E to avoid issues like that.  But here's a 
patch that skips test_timestamp_overflow if bytecode files cannot be written 
(Issue20796 documents a similar problem and workaround for test_import).

--
components:  -Macintosh
keywords: +patch
nosy: +brett.cannon -ronaldoussoren
stage:  -> patch review
title: test_timestamp_overflow fails -> test_timestamp_overflow of 
test_importlib fails if PYTHONDONTWRITEBYTECODE is set
versions: +Python 3.5
Added file: http://bugs.python.org/file42189/issue26583.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: sobering observation, python vs. perl

2016-03-19 Thread Marko Rauhamaa
"Charles T. Smith" :

> well, I don't want to forgo REs in order to have python's numbers be
> better

http://stackoverflow.com/questions/12793562/text-processing-pytho
n-vs-perl-performance>


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


[issue26040] Improve coverage and rigour of test.test_math

2016-03-19 Thread Jeff Allen

Changes by Jeff Allen :


Added file: http://bugs.python.org/file42191/extra_cmath_testcases.py

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: How to waste computer memory?

2016-03-19 Thread Random832


On Fri, Mar 18, 2016, at 11:17, Ian Kelly wrote:
> > Just to play devil's advocate, here, why is it so bad for indexing to be
> > O(n)? Some simple caching is all that's needed to prevent it from making
> > iteration O(n^2), if that's what you're worried about.
> 
> What kind of caching do you have in mind?

The byte index of the last character index accessed. When accessing a
new index greater than that one, start from there (_maybe_ also support
iterating backwards in this way, if accessing an index that is much
closer to the cached one than to zero). And even that's only necessary
if you actually _care_ about forward iteration by character indices
(i.e. "for i in range(len(s))"), rather than writing it off as bad
coding style.

 If you're just going to
> index the string, then that's at least an extra byte per character,
> which mostly kills the memory savings that is usually the goal of
> using UTF-8 in the first place.
> 
> It's not the only drawback, either. If you want to know anything about
> the characters in the string that you're looking at, you need to know
> their codepoints.

Nonsense. That depends on what you want to know about it. You can
extract a single character from a string, as a string, without knowing
anything about it except what range the first byte is in. You can use
this string directly as an index to a hash table containing information
such as unicode properties, names, etc.

> If the string is simple UCS-2, that's easy. Just
> take the two bytes and cast them as a 16-bit integer (assuming that
> the endianness of the string matches the machine). If the string is
> UTF-8 then it has to be decoded, so you need to figure out exactly how
> many bytes are in this particular character, and then from those
> determine which bits you need and then mash those bits together to
> form the actual integer codepoint.

I think you're overestimating the actual performance impact of this, but
okay...

> Now think about doing that over and
> over again in the context of a lexicographical sort.

Er... UTF-8 byte lexicographical order is isomorphic to codepoint
lexicographical order. Which is more than can be said for UTF-16.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: empty clause of for loops

2016-03-19 Thread Chris Angelico
On Sat, Mar 19, 2016 at 7:49 AM, Sven R. Kunze  wrote:
> On 18.03.2016 20:10, Palpandi wrote:
>>
>> You can do like this.
>>
>> if not my_iterable:
>>  
>> for x in my_iterable:
>>  
>
>
> Thanks for you help here, however as already pointed out, my_iterable is not
> necessarily a list but more likely an exhaustible iterator/generator.

The sentinel option has already been mentioned:

x = sentinel = object()
for x in my_iterable:
...
if x is sentinel:
was_empty

Python does offer another way to do this: instead of a sentinel
object, use an exception.

def process(iterable):
"""Process the iterable. If it was completely empty, raise
UnboundLocalError."""
for x in iterable:
...
x


Just for completeness :)

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


Re: empty clause of for loops

2016-03-19 Thread Peter Otten
alister wrote:

> On Wed, 16 Mar 2016 11:47:31 +0100, Peter Otten wrote:
 

>> I'm kidding, of course. Keep it simple and use a flag like you would in
>> any other language:
>> 
>> empty = True:
>> for item in items:
>> empty = False ...
>> if empty:
>> ...
> 
> or even use the loop variable as the flag
> 
> item=None
> for item in items:
> #do stuff
  if item is None:
> #do something else

I like that better now I see it. I've always used

i = -1
for i, v in enumerate(...):
   ...
if i != -1:
   ...

which led me to think that enumerate() was necessary for the idiom.


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


Re: WP-A: A New URL Shortener

2016-03-19 Thread Daniel Wilcox
I dare say I'm with Rick on this point -- keep it up, go learn stuff, put
things together and see how they break -- I think it's the best way to get
feel for how things fit together and, somewhat inevitably, fall over (when
the conditions they were designed in no longer apply).

*quick glance at source*
The raw SQL scares me a bit, there is a lot of escaping that you could add
to protect from sql injections (at least for mysql, sqlite I'm not sure).
And since you want to run this on the Internet I highly recommend putting a
mariadb/mysql database behind it.  Glancing over the Flash documentation
they seem to suggest SQLAlchemy which sounds like a reasonable choice for
an ORM.

An neat idea I've seen before that was neat was a sematic shorten-er where
you could specify the shortened URL to make it easy to remember and
reference.  A lot of security, aka input sanitation, involved but might be
fun -- and who knows it could spark a land rush to claim useful short URLs
like wp-a.co/flask-tips. :)

Speak up if you need any pointers!

Daniel

On Tue, Mar 15, 2016 at 12:56 PM, Vinicius Mesel  wrote:

> Hey guys,
>
> I'm a 16 year old Python Programmer that wanted to do something different.
> But, like we know, ideas are quite difficult to find.
> So I decided to develop a URL Shortener to help the Python community out
> and share my coding knowledge, and today the project was launched with its
> first stable version.
> So if you want to see the software working, go check it out at:
> http://wp-a.co/
> Or if you want to see the source code to contribute and help the project:
> https://github.com/vmesel/WP-A.CO
>
>
> Hugs,
> Vinicius Mesel
> Brazilian and Portuguese Speaker
> http://www.vmesel.com
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue26581] Double coding cookie

2016-03-19 Thread Serhiy Storchaka

New submission from Serhiy Storchaka:

When Python source file contains double coding cookies on different lines, the 
first wins. When it contains double coding cookies on the same line, the last 
wins.

PEP 263 was sufficiently vague about this. Now this is clarified 
(22490711c870). The first coding cookie should always win.

Proposed patch fixes Python tokenizer, the tokenize module, and other places. 
Tests are taken from issue25643.

--
components: Interpreter Core, Library (Lib)
files: tokenize_double_coding.patch
keywords: patch
messages: 261909
nosy: gvanrossum, haypo, serhiy.storchaka
priority: normal
severity: normal
stage: patch review
status: open
title: Double coding cookie
type: behavior
versions: Python 2.7, Python 3.5, Python 3.6
Added file: http://bugs.python.org/file42185/tokenize_double_coding.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: How to waste computer memory?

2016-03-19 Thread Chris Angelico
On Fri, Mar 18, 2016 at 8:08 AM, Grant Edwards  wrote:
> On 2016-03-17, Chris Angelico  wrote:
>> On Fri, Mar 18, 2016 at 7:31 AM,   wrote:
>>> Rick Johnson  wrote:

 In the event that i change my mind about Unicode, and/or for
 the sake of others, who may want to know, please provide a
 list of languages that *YOU* think handle Unicode better than
 Python, starting with the best first. Thanks.

>>> How about a list of languages that Unicode handles better than ASCII?
>>> Like almost every language *except* English.
>>
>> Like every language *including* English. You can pretend that ASCII is
>> enough, but you do lose some information.
>
> And I suppose you youngsters really think you need both upper and
> lower case and all those fancy curly braces, pipes, backslashes
> asterisks, and semi-colons and whatnot.  [Yes, I've written software
> that had to deal with baudot because that's all the paper tape reader
> could handle.]

You can pretend that only 1 and 0 are enough. Good luck making THAT work.

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


[issue26572] urlparse does not handle passwords with ? in them.

2016-03-19 Thread Martin Panter

Martin Panter added the comment:

I think this is the same as Issue 18140. Perhaps you can answer my question at 
the bottom there about why the question mark is not encoded, and why splitting 
at the at (@) symbol should be higher priority than the query (?) symbol.

--
nosy: +martin.panter
resolution:  -> duplicate
status: open -> closed
superseder:  -> urlparse, urlsplit confused when password includes fragment 
(#), query (?)

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Any sqledit/sqlkit users here?

2016-03-19 Thread cl
Does anyone here use sqledit/sqlkit?  It's a sqlite database
browser/editor which does most of its work by introspection (at least
I think that's the right name for it).

Thus it's trivially simple to write a gui program to edit data in a
database:-

#!/usr/bin/python

from sqlkit.widgets import SqlTable
from sqlkit.db import proxy

import gtk

db = proxy.DbProxy(bind="sqlite:home/chris/tmp/odinlog.db")

t = SqlTable('tripLog',dbproxy=db, order_by='Date' )
t.reload()

gtk.main()


(Yes, I know exit/close is missing)

Just run the above (against an existing database) and you get a very
neat looking, editable, grid view.

I was wondering if there are any active users with whom I could share
ideas, the mailing list is quite quiet though there is activity to
move the code to bitbucket and allow more contributions.

I'm just a bit overwhelmed by it at the moment and need some feedback.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: empty clause of for loops

2016-03-19 Thread Random832
On Wed, Mar 16, 2016, at 13:01, Sven R. Kunze wrote:
> On 16.03.2016 17:56, Sven R. Kunze wrote:
> > On 16.03.2016 17:37, Random832 wrote:
> >> for item in collection:
> >> if good(item):
> >>thing = item
> >>break
> >> else:
> >> thing = default # or raise an exception, etc
> >
> > I was thinking about why we don't use it that often. My response to 
> > this example:
> >
> > thing = item if item in collection else default
> 
> Time for a break. That is not going to work.
> 
> Will still think about why we don't use it (often/at all).

Yeah, well, you can *almost* get there with:

try:
thing = next(item for item in collection if good(item))
except StopIteration:
thing = default

But the for/else thing seems like a more natural way to do it. Plus,
this is a toy example, if the body is more than one statement or doesn't
involve returning a value comprehensions aren't a good fit.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to waste computer memory?

2016-03-19 Thread Steven D'Aprano
On Sat, 19 Mar 2016 02:31 am, Random832 wrote:

> On Fri, Mar 18, 2016, at 11:17, Ian Kelly wrote:
>> > Just to play devil's advocate, here, why is it so bad for indexing to
>> > be O(n)? Some simple caching is all that's needed to prevent it from
>> > making iteration O(n^2), if that's what you're worried about.
>> 
>> What kind of caching do you have in mind?
> 
> The byte index of the last character index accessed. 

Some people, when faced with a problem, think, I know, I'll use a cache. Now
they have 99 problems (but a bitch ain't one).


> When accessing a 
> new index greater than that one, start from there (_maybe_ also support
> iterating backwards in this way, if accessing an index that is much
> closer to the cached one than to zero). And even that's only necessary
> if you actually _care_ about forward iteration by character indices
> (i.e. "for i in range(len(s))"), rather than writing it off as bad
> coding style.

Without locking, this kills thread safety for strings. With locking, it
probably kills performance. Worse, even in single-threaded code, functions
can mess up the cache, destroying any usefulness it may have:


x = mystring[]  # sets the cache to index 
spam(mystring)  # calls mystring[0], setting the cache back to 0
y = mystring[1]


And I don't understand this meme that indexing strings is not important.
Have people never (say) taken a slice of a string, or a look-ahead, or
something similar?

i = mystring.find(":")
next_char = mystring[i+1]

# Strip the first and last chars from a string 
mystring[1:-1]


Perhaps you might argue that for some applications, O(N) string operations
don't matter. After all, in Linux, terminals usually are set to UTF-8, and
people can copy and paste substrings out of the buffer, etc. So there may
be a case to say that for applications with line-oriented buffers typically
containing 70 or 170 characters per line, like a terminal, UTF-8 is
perfectly adequate. I have no argument against that.

But I think that for a programming language which may be dealing with
strings of multiple tens of megabytes in size, I'm skeptical that UTF-8
doesn't cause a performance hit for at least some operations.


>> It's not the only drawback, either. If you want to know anything about
>> the characters in the string that you're looking at, you need to know
>> their codepoints.
> 
> Nonsense. That depends on what you want to know about it. You can
> extract a single character from a string, as a string, without knowing
> anything about it except what range the first byte is in. You can use
> this string directly as an index to a hash table containing information
> such as unicode properties, names, etc.

I don't understand your comment. If I give you the index of the character,
how do you know where its first byte is? With UTF-8, character i can be
anywhere between byte i and 4*i.

(And by character I actually mean code point -- let's not get into arguments
about normalisation.)



>> If the string is simple UCS-2, that's easy. 

Hmmm, well, nobody uses UCS-2 any more, since that only covers the first
65536 code points. Rather, languages like Javascript and Java, and the
Windows OS, use UTF-16, which is a *variable width* extension to UCS-2. I
don't know about Windows, but Javascript implements this badly, so that
4-byte UTF-16 code points are treated as *two* surrogate code points
instead of the single code point they are meant to be. We can get the same
result in Python 2.7 narrow builds:

py> s = u'\U0010'  # definitely a single code point
py> len(s)  # WTF?
2
py> s[0]  # a surrogate.
u'\udbff'
py> s[1]  # another surrogate
u'\udfff'

The only fixed-width encoding of the entire Unicode character set is UTF-32.




-- 
Steven

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


Re: WP-A: A New URL Shortener

2016-03-19 Thread Thomas 'PointedEars' Lahn
Daniel Wilcox wrote:

> Cool thanks, highly recommended to use an ORM to deter easy SQL
> injections. 

That is to crack a nut with a sledgehammer.  SQL injection can be easily and 
more efficiently prevented with prepared statements.  While an Object-
Relational Mapper (ORM) can use those, and there are benefits to using an 
ORM, avoiding SQL injection should not be the primary reason to use an ORM.  
In fact, using an ORM is often not only overkill, but effectively *reduces* 
application performance.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue26588] _tracemalloc: add support for multiple address spaces (domains)

2016-03-19 Thread STINNER Victor

STINNER Victor added the comment:

Patch version 2:

- modify _tracemalloc._get_traces() to include domain in traces
- add tracemalloc.DomainFilter(domain)
- add domain optional parameter to tracemalloc.Filter constructor

Currently, Snapshot._group_by() ignores domain information. I don't know how 
the domain should be exposed, *if* it should be exposed.

By the way, maybe we don't need to export the domain at the Python level at 
all? (Don't expose it in _tracemalloc._get_traces()).

--
Added file: http://bugs.python.org/file42210/tracemalloc-2.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26252] Add an example to importlib docs on setting up an importer

2016-03-19 Thread Roundup Robot

Roundup Robot added the comment:

New changeset dc24ab548e2b by Brett Cannon in branch 'default':
Issue #26252: Add an example on how to register a finder
https://hg.python.org/cpython/rev/dc24ab548e2b

--
nosy: +python-dev

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue25720] Fix curses module compilation with ncurses6

2016-03-19 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

I suspect that the patch can break build with non-ncurses implementations or 
with old ncurses (when is_pad() was added?). Needed more direct feature check.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Descriptors vs Property

2016-03-19 Thread Ethan Furman

On 03/11/2016 09:59 PM, Veek. M wrote:


A property uses the @property decorator and has @foo.setter
@foo.deleter.

A descriptor follows the descriptor protocol and implements the __get__
__set__ __delete__ methods.


`property` is a descriptor combined with a decorator, so is a little 
more complex to understand.


--
~Ethan~

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


Re: Case Statements

2016-03-19 Thread l0r0m0a0i0l
What hath I wrought?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to waste computer memory?

2016-03-19 Thread Terry Reedy

On 3/18/2016 7:58 AM, Steven D'Aprano wrote:

On Fri, 18 Mar 2016 10:46 pm, Steven D'Aprano wrote:


I think it is typical of JMF that his idea of a language where Unicode
"just works" is one where it *does work at all* (at least not as strings).


Er, does NOT work at all.


Python 1.5 strings supported Unicode just as well as Go's string class.


Since I'm replying to myself, I guess I can take the opportunity to expand
on this. Go's concept of strings is, more or less, byte strings:

https://blog.golang.org/strings

They are handled as an array of bytes and indexing produces bytes. That's
exactly the same functionality as Python strings provided in version 1.5.
In fairness, Go does provide a second type, "runes", which is equivalent to
Python 2.7 unicode using a wide build (i.e. equivalent to UTF-32).


To be exact, a rune is equivalent to a codepoint, so '[]rune' (array of 
runes) is the equivalent to 'unicode'.


Go was written by Google for use by Google, so it is not surprising that 
its design is influenced by what Google does.  Google mainly gathers, 
stores, and disperses 'humongabytes' of data.  Storing as utf-32 would 
perhaps triple its storage space.  So it stores and indexes text as the 
same bytes it will most likely transmit.


Python's space-saving FSR was developed years after Go was.

--
Terry Jan Reedy

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


RE: pdf version of python tutorial

2016-03-19 Thread Joaquin Alzola
Den 13-03-2016 kl. 14:45 skrev kamaraju kusumanchi:
> Is there a pdf version of the python tutorial
> https://docs.python.org/3/tutorial/index.html that I can download? The
> idea is to have everything in one file so I can search easily, be able
> to work offline.
>
> thanks
> raju
>

>Try here: https://docs.python.org/3.5/download.html.

>I found the tutorial in the zip-file "PDF(A4 paper size)", which contains a 
>lot of PDFs, amongst these many of howto-documents.

Download the HTML one.

--
Venlig hilsen / Best regards
Jesper K. Brogaard

(remove upper case letters in my e-mail address)
--
https://mail.python.org/mailman/listinfo/python-list
This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: empty clause of for loops

2016-03-19 Thread Sven R. Kunze

On 16.03.2016 16:02, Tim Chase wrote:

On 2016-03-16 15:29, Sven R. Kunze wrote:

I would re-use the "for-else" for this. Everything I thought I
could make use of the "-else" clause, I was disappointed I couldn't.

Hmm...this must be a mind-set thing.  I use the "else" clause with
for/while loops fairly regularly and would be miffed if their behavior
changed.

Could I work around their absence?  Certainly.

Does it annoy me when I have to work in other languages that lack
Python's {for/while}/else functionality?  You bet.


I can imagine that. Could you describe the general use-case? From what I 
know, "else" is executed when you don't "break" the loop. When is this 
useful?



Btw., I don't have any issue with else or whatever it is called. It's 
just a word but it must fit intuition. And this is why I would rather 
see "else" being used there. But this may result because of the lack of 
usage of mine.



We can also re-use "except" for it. ;-)


Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: Bash-like pipes in Python

2016-03-19 Thread Omar Abou Mrad
On Wed, Mar 16, 2016 at 4:57 PM, Steven D'Aprano 
wrote:

> There's a powerful technique used in shell-scripting languages like bash:
> pipes. The output of one function is piped in to become the input to the
> next function.
>
> According to Martin Fowler, this was also used extensively in Smalltalk:
>
> http://martinfowler.com/articles/collection-pipeline/
>
> and can also be done in Ruby, using method chaining.
>
> Here is a way to do functional-programming-like pipelines to collect and
> transform values from an iterable:
>
> https://code.activestate.com/recipes/580625-collection-pipeline-in-python/
>
> For instance, we can take a string, extract all the digits, convert them to
> ints, and finally multiply the digits to give a final result:
>
> py> from operator import mul
> py> "abcd12345xyz" | Filter(str.isdigit) | Map(int) | Reduce(mul)
> 120
>
> <..snip..>
>

Would be nice if this was possible:

>>> get_digits = Filter(str.isdigit) | Map(int)
>>> 'kjkjsdf399834' | get_digits

Also, how about using '>>' instead of '|' for "Forward chaining"

Regards,

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


[issue26530] tracemalloc: add C API to manually track/untrack memory allocations

2016-03-19 Thread STINNER Victor

STINNER Victor added the comment:

> So you guarantee tracemalloc itself won't use such a hack for other
purposes? ;-)

Hum, maybe we can make the "hack" "official": add two C macro to store and 
retrieve the domain from a pointer. The macro can validate that the domain is 
smaller or equal to 8 using an assertion (only in debug mode?).

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Experimenting with PyPyJS

2016-03-19 Thread Salvatore DI DIO
Le samedi 19 mars 2016 19:52:45 UTC+1, Terry Reedy a écrit :
> On 3/19/2016 1:06 PM, Salvatore DI DIO wrote:
> > Le samedi 19 mars 2016 18:00:05 UTC+1, Vincent Vande Vyvre a écrit :
> >> Le 19/03/2016 16:32, Salvatore DI DIO a écrit :
> >>> Le samedi 19 mars 2016 16:28:36 UTC+1, Salvatore DI DIO a écrit :
>  Hy all,
> 
>  I am experimenting PyPyJS and found it not so bad at all.
>  The virtual machine loads on a few seconds (using firefox).
> 
>  It s really nice for  learning Python, you have all the standard 
>  libraries,
>  and traceback on errors. I don't have to choose anymore with all 
>  transpilers around
> 
>  You can try it here, but please don't tell it s too long to load the VM.
>  After all, don't you wait when you start a desktop application, or an 
>  heavy game online ?
> 
>  Just try it and tell your feeling
> 
>  Regards
> 
>  http://salvatore.diodev.fr/pypybox/
> >>> Use Firefox...
> >>
> >> That's look fine but:
> >>
> >> PID USER  PR  NI  VIRT  RES  SHR S %CPU %MEMTIME+  COMMAND
> >>4917 vincent   20   0 1081m 305m  52m R *50.3* 15.4   5:23.75 firefox
> >>1094 root  20   0 48152  15m 7180 S *35.0*  0.8   4:43.28 Xorg
> >>5421 vincent   20   0  162m  14m  10m R  2.0  0.7   0:02.49 
> >> mate-terminal
> >>   1 root  20   0  3660 1984  ...
> >>
> >> 85.3 % (50.3 + 35) CPU usage just for a rotating square it's too much cost.
> >>
> >> Vincent
> >
> > Thank you for testing :-)
> > Strange on Windows I have an average 6% CPU with Firefox 45.0.1
> 
> Win10, same FF, 6 core pentium, 1% +- CPU, 110 MB memory increase.
> 
> 
> -- 
> Terry Jan Reedy

Thanks Terry
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-19 Thread Ben Finney
anyanwuchukwueme...@gmail.com writes:

> What was the final answer for the create class bankaccount question?

The final answer is: homework entails that you do the work, not us.

-- 
 \  “I tell you the truth: some standing here will not taste death |
  `\before they see the Son of Man coming in his kingdom.” —Jesus, |
_o__) c. 30 CE, as quoted in Matthew 16:28 |
Ben Finney

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


[issue26583] test_timestamp_overflow fails

2016-03-19 Thread SilentGhost

Changes by SilentGhost :


--
components: +Macintosh, Tests
nosy: +ned.deily, ronaldoussoren
type:  -> behavior

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26543] imaplib noop Debug

2016-03-19 Thread gigaplastik

Changes by gigaplastik :


--
nosy: +gigaplastik

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Case Statements

2016-03-19 Thread BartC

On 16/03/2016 12:21, Marko Rauhamaa wrote:

BartC :



That's the first time I've heard a language feature common in C
described as sexy.


Scheme has a "switch" statement (a "case" form). However, it is slightly
better equipped for it than Python:

  * Scheme has an atom type ("symbol"). It corresponds to interned
strings and is supposed to be compared by reference.

  * Scheme has defined three equality operators: "eq?", "eqv?" and
"equal?". Python only has two: "is" (~ "eq?") and "==" (~ "equal?").
The "case" form makes use of the operator "eqv?" that is missing from
Python ("eqv?" compares numbers numerically but is otherwise the same
as "eq?").



Yes, a few scripting languages can do interesting things with switch or 
case statements. Perl for example (where I think it is created out other 
language features, but it looks a regular part of the syntax).


Even Ruby has one. It doesn't do anything 'sexy' with it, but it does 
have this:


 case
 when this

 when that

 when other
...
 end

which is exactly equivalent to if this... elif that... (when the tests 
are ordered), with one difference:


Each test starts with "when", instead of "if" for the first and "elif" 
for subsequent ones. That makes it easier to reorder tests, temporarily 
comment out the first test, copy a test from elsewhere, insert a new 
first test (you get the idea).


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


[issue26040] Improve coverage and rigour of test.test_math

2016-03-19 Thread Jeff Allen

Changes by Jeff Allen :


Removed file: http://bugs.python.org/file42190/stat_math.py

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Bash-like pipes in Python

2016-03-19 Thread Stefan Otte
I use the pipe style a lot, but one of the annoyances is that many
functions in the python standardlib expect the first argument to be a
callable and the second an iterable. I tend to write a lot of
"p-functions" (functions which switch that order and make them
compatible to `pipe`).


from pelper import pipe
from operator import mul

def pfilter(iterable, f): return filter(f, iterable)
def pmap(iterable, f): return map(f, iterable)
def preduce(iterable, f): return reduce(f, iterable)

pipe("abcd12345xyz",
 (pfilter, str.isdigit),
 (pmap, int),
 (preduce, mul)
)

`pipe` also allows you to us named arguments which would be difficult
if you use operator overloading:
pipe("sentaoisrntuwyo", (sorted, {"reverse": True}))


Beste Grüße,
 Stefan



On Wed, Mar 16, 2016 at 4:39 PM, Steven D'Aprano  wrote:
> On Thu, 17 Mar 2016 02:22 am, Omar Abou Mrad wrote:
>
>> Would be nice if this was possible:
>>
> get_digits = Filter(str.isdigit) | Map(int)
> 'kjkjsdf399834' | get_digits
>
>
> Yes it would. I'll work on that.
>
>
>> Also, how about using '>>' instead of '|' for "Forward chaining"
>
> Any particular reason you prefer >> over | as the operator?
>
>
>
>
> --
> Steven
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: DSLs in perl and python (Was sobering observation)

2016-03-19 Thread Peter Otten
Rustom Mody wrote:

> On Friday, March 18, 2016 at 4:17:06 AM UTC+5:30, MRAB wrote:
>> Stick an "x" on the end of the regex: /something/x or s/old/new/x.
> 
> Thanks!
> 
> Is there somewhere a regexp 'introspection' API/capability available?
> 
> ie if the re looks like
> rexp = r"""
> # DSL (instantiation) for describing NYSE symbology
> ^
> (?P [A-Z]*) # The base scrip
> (?P   [.+-])? # Series type char
> (?P[A-Z])? # Series
> (?P   [#])?   # issued char indicator
> $  # Thats all (there should be!)
> """
> 
> I would like to know that the named-groups are
> {scrip, serchar, series, issued}
> without doing match/search etc

Is that a Perl or a Python question? If the latter:

>>> r = re.compile(rexp, re.VERBOSE)
>>> r.groupindex
{'serchar': 2, 'issuedc': 4, 'scrip': 1, 'series': 3}



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


Re: monkey patching __code__

2016-03-19 Thread Matt Wheeler
On 18 March 2016 at 11:49, Sven R. Kunze  wrote:
> Hi,
>
> we got an interesting problem. We need to monkeypatch Django's reverse
> function:
>
>
> First approach:
>
> urlresolvers.reverse = patched_reverse
>
>
> Problem: some of Django's internal modules import urlresolvers.reverse
> before we can patch it for some reasons.
>
>
> Second approach:
>
> urlresolvers.reverse.__code__ = patched_reverse.__code__
>
>
> Unfortunately, we got this error:
>
 reverse('login')
>
> patched_reverse() takes at least 3 arguments (1 given)
>
>
> These are the functions' signatures:
>
> def patched_reverse(viewname, urlconf=None, args=None, kwargs=None,
> prefix=None, current_app=None, get=None, fragment=None):
> def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None,
> current_app=None):
>
>
> Some ideas?

I know you have a working solution now with updating the code &
defaults of the function, but what about just injecting your function
into the modules that had already imported it after the
monkeypatching?

Seems perhaps cleaner, unless you'd end up having to do it to lots of modules...

-- 
Matt Wheeler
http://funkyh.at
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue26574] replace_interleave can be optimized for single character byte strings

2016-03-19 Thread Josh Snider

New submission from Josh Snider:

replace_interleave in Objects/bytesobject.c and Objects/bytearrayobject.c can 
be optimized for the special case where the interleaving byte string is a 
single character.

Here's some quick results from timeit showing that it's about three times 
faster for the special case.
* Before (cold start):
>>> timeit.timeit('(b"x" * 200).replace(b"", b".")', number=1000)
7.619218342995737
* After (cold start):
>>> timeit.timeit('(b"x" * 200).replace(b"", b".")', number=1000)
2.7605581780080684

For the non-special case, running timeit.timeit('(b"x" * 200).replace(b"", 
b".0")', number=1) takes ~173 seconds on both versions.

--
components: Library (Lib)
files: bytes.patch
keywords: patch
messages: 261870
nosy: Josh Snider
priority: normal
severity: normal
status: open
title: replace_interleave can be optimized for single character byte strings
type: performance
versions: Python 3.6
Added file: http://bugs.python.org/file42179/bytes.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: empty clause of for loops

2016-03-19 Thread Sven R. Kunze

On 16.03.2016 18:08, Random832 wrote:

Yeah, well, you can *almost* get there with:

try:
 thing = next(item for item in collection if good(item))
except StopIteration:
 thing = default

But the for/else thing seems like a more natural way to do it. Plus,
this is a toy example, if the body is more than one statement or doesn't
involve returning a value comprehensions aren't a good fit.


Sure, YMMV.

What I don't understand is why Python features "if break, then no else 
clause", but "if empty, then empty clause".


I found this excellent post: 
https://shahriar.svbtle.com/pythons-else-clause-in-loops


The described break-else replacement greatly resembles the answers of 
this thread:


condition_is_met = False
for x in data:
if meets_condition(x):
condition_is_met = True

if not condition_is_met:
# raise error or do additional processing

Compared to the proposed empty clause replacement:

empty = True:
for item in items:
empty = False
...

if empty:
...


In order to explain why this might be slightly more important to us than 
to other folks: we work in the field of Web development. As humans are 
no machines, they usually expect an empty list to be marked as such OR 
special actions when lists are not filled as expected.


Even Django ({% empty %}) and jinja ( {% else %}) features this type of 
construct. You might think it's enough when template engines work this 
way (the output layer). However, I quite regularly could find this 
useful within the logic part (the actions) of our applications.


Do you think this would be worth posting on python-ideas?

Best,
Sven

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


Re: Beginner Python Help

2016-03-19 Thread Martin A. Brown

Greetings Alan and welcome to Python,

>I just started out python and I was doing a activity where im 
>trying to find the max and min of a list of numbers i inputted.
>
>This is my code..
>
>num=input("Enter list of numbers")
>list1=(num.split())
>
>maxim= (max(list1))
>minim= (min(list1))
>
>print(minim, maxim)
>
>So the problem is that when I enter numbers with an uneven amount 
>of digits (e.g. I enter 400 20 36 85 100) I do not get 400 as the 
>maximum nor 20 as the minimum. What have I done wrong in the code?

I will make a few points, as will probably a few others who read 
your posting.

  * [to answer your question] the builtin function called input [0]
returns a string, but you are trying to get the min() and max() 
of numbers; therefore you must convert your strings to numbers

You can determine if Python thinks the variable is a string or 
a number in two ways (the interactive prompt is a good place to
toy with these things).  Let's look at a string:

  >>> s = '200 elephants'
  >>> type(s) # what type is s?
 # oh! it's a string
  >>> s   # what's in s?
  '200 elephants' # value in quotation marks!

   The quotation marks are your clue that this is a string, not a 
   number; in addition to seeing the type.  OK, so what about a 
   number, then?  (Of course, there are different kinds of numbers, 
   complex, real, float...but I'll stick with an integer here.)

  >>> n = 42
  >>> type(n) # what type is n?
 # ah, it's an int (integer)
  >>> n   # what's in n?
  42  # the value

  * Now, perhaps clearer?  max(['400', '20', '36', '85', '100'])
is sorting your list of strings lexicographically instead of 
numerically (as numbers); in the same way that the string 
'rabbit' sorts later than 'elephant', so too does '85' sort 
later than '400'

  * it is not illegal syntax to use parentheses as you have, but you
are using too many in your assignment lines; I'd recommend 
dropping that habit before you start; learn when parentheses are 
useful (creating tuples, calling functions, clarifying 
precedence); do not use them here:

   list1 = (num.split())  # -- extraneous and possibly confusing
   list1 = num.split()# -- just right

  * also, there is also Tutor mailing list [1] devoted to helping 
with Python language acquisition (discussions on this main list 
can sometimes be more involved than many beginners wish to read)

I notice that you received several answers already, but I'll finish 
this reply and put your sample program back together for you:

  num = input("Enter list of numbers: ")
  list1 = list(map(int, num.split()))
  print(list1)
  maxim = max(list1)
  minim = min(list1)
  print(minim, maxim)

You may notice that map [2] function in there.  If you don't 
understand it, after reading the function description, I'd give you 
this example for loop that produces the same outcome.

  list1 = list()
  for n in num.split():
  list1.append(int(n))

The map function is quite useful, so it's a good one to learn early.

Good luck,

-Martin

 [0] https://docs.python.org/3/library/functions.html#input
 [1] https://mail.python.org/mailman/listinfo/tutor/
 [2] https://docs.python.org/3/library/functions.html#map

-- 
Martin A. Brown
http://linux-ip.net/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: WP-A: A New URL Shortener

2016-03-19 Thread Chris Warrick
On 15 March 2016 at 20:56, Vinicius Mesel  wrote:
> Hey guys,
>
> I'm a 16 year old Python Programmer that wanted to do something different.
> But, like we know, ideas are quite difficult to find.
> So I decided to develop a URL Shortener to help the Python community out and 
> share my coding knowledge, and today the project was launched with its first 
> stable version.
> So if you want to see the software working, go check it out at: 
> http://wp-a.co/
> Or if you want to see the source code to contribute and help the project: 
> https://github.com/vmesel/WP-A.CO
>
>
> Hugs,
> Vinicius Mesel
> Brazilian and Portuguese Speaker
> http://www.vmesel.com
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list

This is a great exercise — however, your code is bad. You use string
formatting to create SQL, which leads to SQL injection
vulnerabilities. Please educate yourself on what those mean and how to
avoid that in Python (hint: prepared statements). Also, you should not
commit your sqlite database to git.

That said, an URL shortener can be written in Django in less than an
hour, and it will be even neater.

(PS. the page’s really ugly. Consider using Bootstrap or some other
existing framework if you’re not good at designing pretty things.)
-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: monkey patching __code__

2016-03-19 Thread Ian Kelly
On Fri, Mar 18, 2016 at 9:01 AM, Sven R. Kunze  wrote:
> On 18.03.2016 15:48, Ian Kelly wrote:
>>
>> Well I didn't design it, so I'm not really sure. But it could be argued
>> that the defaults are intrinsic to the function declaration, not the code
>> object, as not all code objects even have arguments. It also makes it
>> straight-forward to create a new function that uses the same code but with
>> different defaults or globals.
>
>
> It occurred to me after I sent that email.
>
> However, changing globals is not possible.

Well it may not work for your case, but in general you can do:

from types import FunctionType

new_function = FunctionType(old_function.__code__, new_globals, ...)
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue26257] Eliminate buffer_tests.py

2016-03-19 Thread Serhiy Storchaka

Serhiy Storchaka added the comment:

It looks to me that all tests from CommonTest except test_capitalize_nonascii 
can be merged into BaseTest.

A number of tests from MixinStrUnicodeUserStringTest could be applied to bytes 
and bytearray too.

I think we should left only two classes in string_tests: common tests for str, 
UserString, bytes and bytearray, and common tests for str and UserString that 
are not applicable to bytes and bytearray.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: monkey patching __code__

2016-03-19 Thread Sven R. Kunze

On 18.03.2016 14:47, Ian Kelly wrote:

Your patched version takes two extra arguments. Did you add the
defaults for those to the function's __defaults__ attribute?


That's it! :-) Thanks a lot.

Just to understand this better: why is that not part of the code object 
but part of the function?



This sounds like a pretty hairy thing that you're trying to do. Surely
there must be some better way to accomplish the same goal.


We are open for suggestions. We featured our own reverse function for a 
while but it lead to inconsistent behaviors across the field. Especially 
considering that Django provides an {% url %} template tag which would 
then use yet another reverse implementation.


Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: empty clause of for loops

2016-03-19 Thread Tim Chase
On 2016-03-16 11:23, Sven R. Kunze wrote:
> for x in my_iterable:
>  # do
> empty:
>  # do something else
> 
> What's the most Pythonic way of doing this?

If you can len() on it, then the obvious way is

  if my_iterable:
for x in my_iterable:
  do_something(x)
  else:
something_else()

However, based on your follow-up that it's an exhaustible iterator
rather than something you can len(), I'd use enumerate:

  count = 0 # have to set a default since it doesn't get assigned
# if no iteration happens
  for count, x in enumerate(my_iterable, 1):
do_something(x)
  if not count:
something_else()

I do a lot of ETL work, and my code often has to report how many
things were processed, so having that count is useful to me.
Otherwise, I'd use a flag:

  empty = True
  for x in my_iterable:
empty = False
do_something(x)
  if empty:
something_else()

-tkc




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


Re: Beautifulsoap

2016-03-19 Thread Joel Goldstick
On Wed, Mar 16, 2016 at 9:36 AM,  wrote:

> Greetings NG
>
> please I need a little help.
>
> I have this bs object tag:
>
> 
>
> I want extract 5.69
>
> Some have pity of me :-)
>
> Thanks
>
>
> Show the code you have, and what isn't working.  Which verision of python
and BS

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



-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue26587] Possible duplicate entries in sys.path if .pth files are used with zip's

2016-03-19 Thread Mandeep Singh Grang

Mandeep Singh Grang added the comment:

Here is a testcase to reproduce the issue:

> cat test.py
import site, sys
site.addsitedir('/foo/bar')
print (sys.path)

This prints just a single instance of '/foo/bar':

['/local/mnt/workspace/python/tst', '/foo/bar', '/usr/local/lib/python36.zip', 
'/local/mnt/workspace/python/src/Lib', 
'/local/mnt/workspace/python/src/Lib/plat-linux', 
'/local/mnt/workspace/python/build/build/lib.linux-x86_64-3.6-pydebug']

Now if we explicitly set PYTHONPATH to include '/foo/bar'
> export PYTHONPATH=/foo/bar

and then run test.py here is the output:

['/local/mnt/workspace/python/tst', '/foo/bar', '/usr/local/lib/python36.zip', 
'/local/mnt/workspace/python/src/Lib', 
'/local/mnt/workspace/python/src/Lib/plat-linux', 
'/local/mnt/workspace/python/build/build/lib.linux-x86_64-3.6-pydebug', 
'/foo/bar']

We see that there are duplicate entries for '/foo/bar'.

As Wolfgang rightly said the issue comes from the check for
"if os.path.isdir(dir)" inside _init_pathinfo() in site.py.
On removing this check I no longer see the duplicate entry for '/foo/bar'.

But since this is the first bug I am looking at I am not sure of the 
implications of removing this check. Can someone please confirm that what I see 
is indeed a failing test case, or is this the intended behavior?

Thanks,
Mandeep

--
nosy: +Mandeep Singh Grang

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Python directory

2016-03-19 Thread Xerma Palmares
Hello,
I have just downloaded Python latest version on to PC running windows 10.
Unfortunately, after the completion of the download the Python icon was not
showing up on the Desktop and could not found the Python files on the
Programs folder either. I uninstalled Python, I will try it again.
Thanks,
"

Xerma

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


[issue26578] Bad BaseHTTPRequestHandler response when using HTTP/0.9

2016-03-19 Thread Xiang Zhang

Xiang Zhang added the comment:

I think you are right. Simply run http.server.test() and then telnet to send 
"GET /", the client hangs. Or add a timeout to BaseHTTPRequestHandler, you can 
see the timeout error on server output.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Case Statements

2016-03-19 Thread Marko Rauhamaa
l0r0m0a0...@gmail.com:

> Gratified to see that with all this back-and-forth this thread still
> has a sense of humor. Perhaps, we can all just agree to disagree? :)

I might agree with you if you tell me what we disagree about.


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


Re: sobering observation, python vs. perl

2016-03-19 Thread Marko Rauhamaa
"Charles T. Smith" :

> Here's the programs:
>
> #!/usr/bin/env python
> # vim: tw=0
> import sys
> import re
>
> isready = re.compile ("(.*) is ready")
> relreq = re.compile (".*release_req")
> for fn in sys.argv[1:]: # logfile name
> tn = None
> with open (fn) as fd:
> for line in fd:
> #match = re.match ("(.*) is ready", line)
> match = isready.match (line)
> if match:
> tn = match.group(1)
> #match = re.match (".*release_req", line)
> match = relreq.match (line)
> if match:
> #print "%s: %s" % (tn, line),
> print tn
>
> vs.
>
> while (<>) {
> if (/(.*) is ready/) {
> $tn = $1;
> }
> elsif (/release_req/) {
> print "$tn\n";
> }
> }
>
> Look at those numbers:
> 1 minute for python without precompiled REs
> 1/2 minute with precompiled REs
> 5 seconds with perl.

Can't comment on the numbers but the code segments are not quite
analogous. What about this one:

#!/usr/bin/env python
# vim: tw=0
import sys
import re

isready = re.compile("(.*) is ready")
for fn in sys.argv[1:]:
tn = None
with open(fn) as fd:
for line in fd:
match = isready.match(line)
if match:
tn = match.group(1)
elif "release_req" in line:
print tn


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


Re: empty clause of for loops

2016-03-19 Thread Sven R. Kunze

On 16.03.2016 11:47, Peter Otten wrote:


What would you expect?


A keyword filling the missing functionality? Some Python magic, I 
haven't seen before. ;-)





class Empty(Exception): pass

...

def check_empty(items):

... items = iter(items)
... try:
... yield next(items)
... except StopIteration:
... raise Empty
... yield from items
...

try:

...for item in check_empty("abc"): print(item)
... except Empty: print("oops")
...
a
b
c

try:

...for item in check_empty(""): print(item)
... except Empty: print("oops")
...
oops


He will be highly delighted so see such a simplistic solution. ;-)


I'm kidding, of course. Keep it simple and use a flag like you would in any
other language:

empty = True:
for item in items:
 empty = False
 ...
if empty:
 ...



He likes this approach. Thanks. :-)


Although, I for one would like a keyword. I remember having this issue 
myself, and found that the "empty" variable approach is more like a 
pattern. As usual, patterns are workarounds for features that a language 
misses.


Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: sobering observation, python vs. perl

2016-03-19 Thread Charles T. Smith
On Thu, 17 Mar 2016 18:30:29 +0200, Marko Rauhamaa wrote:

> "Charles T. Smith" :
> 
>> I need the second check to also be a RE because it's not
>> separate tokens.
> 
> The string "in" check doesn't care about tokens.
> 
> 
> Marko


Ah, yes.  Okay.
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue17603] AC_LIBOBJ replacement of fileblocks

2016-03-19 Thread Roundup Robot

Roundup Robot added the comment:

New changeset acbeb33dc76a by Martin Panter in branch '2.7':
Issue #17603: Check for st_blocks field without requiring fileblocks.o
https://hg.python.org/cpython/rev/acbeb33dc76a

New changeset 0774398c3433 by Martin Panter in branch '3.5':
Issue #17603: Check for st_blocks field without requiring fileblocks.o
https://hg.python.org/cpython/rev/0774398c3433

New changeset 628bd1ebfa22 by Martin Panter in branch 'default':
Issue #17603: Merge configure.ac fix from 3.5
https://hg.python.org/cpython/rev/628bd1ebfa22

--
nosy: +python-dev

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Is this an error in python-babel or am I missing something?

2016-03-19 Thread cl
I am getting the following error when running some code that uses
python-sqlkit.  This uses python-babel to handle dates for different
locales.

Traceback (most recent call last):
  File 
"/usr/local/lib/python2.7/dist-packages/sqlkit-0.9.6.1-py2.7.egg/sqlkit/widgets/table/columns.py",
 line 169, in cell_data_func_cb formatted_value = self.field.format_value(value)
  File 
"/usr/local/lib/python2.7/dist-packages/sqlkit-0.9.6.1-py2.7.egg/sqlkit/fields.py",
 line 1114, in format_value return dates.format_date(value, format=format or 
self.format, locale=self.locale)
  File "/usr/lib/python2.7/dist-packages/babel/dates.py", line 569, in 
format_date return pattern.apply(date, locale)
  File "/usr/lib/python2.7/dist-packages/babel/dates.py", line 892, in 
apply return self % DateTimeFormat(datetime, locale)
  File "/usr/lib/python2.7/dist-packages/babel/dates.py", line 889, in 
__mod__ return self.format % other
  File "/usr/lib/python2.7/dist-packages/babel/dates.py", line 948, in 
__getitem__ return self.format_milliseconds_in_day(num)
  File "/usr/lib/python2.7/dist-packages/babel/dates.py", line 1029, in 
format_milliseconds_in_day self.value.minute * 6 + self.value.hour * 360
AttributeError: 'datetime.date' object has no attribute 'microsecond'

I'm handling a date in my sqlite database, *not* a datetime.  The
sqlkit code seems to be calling the correct method - format_date() -
in the python-babel dates.py file.

However it seems that python-babel ends up trying to hand the date
down to a method that's expecting a datetime.

I've tried searching for reports of this error but I can't see any
which makes me wonder if it's not a bug in python-babel, however if
it's not a bug then I'm confused about what has gone wrong.

Is it a bug or is sqlkit doing something wrong?

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the common technique used to cross-reference in module's method?

2016-03-19 Thread Peter Otten
jf...@ms4.hinet.net wrote:

> There are two modules (say model.py and piece.py) which has methods need
> to refer to each other module's methods. I saw in a book using the way
> below, by assigning one (the Model) object to an attribute of the other
> (the Piece) bject. -
> ##model.py
> import piece
> ...
> class Model(dict):
> ...
> def all_occupied_positions(self):
> ...
> 
> def reset_to_initial_locations(self):
> self.clear()
> for position, value in START_PIECES_POSITION.items():
> self[position] = piece.create_piece(value)
> self[position].model = self

I'd pass self to the factory

  self[position] = piece.create_piece(self, value)
> ...
> 
> ##piece.py
> ...
> def create_piece(value):  # Note: it's a function
>...
>return eval(...)  # the returned object is a Piece object

and would avoid the eval().

> class Piece():
> ...
> def moves_available(self):
> model = self.model
> ...
> if item not in model.all_occupied_positions():
> ...
> ...
> ---
> Is it a common way of doing this?

Yes, but it creates a reference cycle; if you want to avoid that for 
philosophical reasons or to save memory when there are many children (here: 
pieces) you have to provide the context (the model in this case) explicitly

def moves_available(self, model):
   ...
 
> Why the author use the same module name "model" for those attribute and
> local names? Is it a good idea or bad?

The name "model" and "piece" look natural for both the module and the 
instance. Does it confuse you? then it's bad ;)

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


retrieve key of only element in a dictionary (Python 3)

2016-03-19 Thread Fillmore


I must be missing something simple, but...

Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = dict()
>>> d['squib'] = "007"
>>> # I forget that 'squib' is my key to retrieve the only element in d
...
>>> type(d.items())

>>> key = d.items()[0]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'dict_items' object does not support indexing
>>> key,_ = d.items()
Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 1 value to unpack
>>> key,b = d.items()
Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 1 value to unpack
>>> print(d.items())
dict_items([('squib', '007')])
>>> print(d.items()[0])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'dict_items' object does not support indexing
>>>

what am I missing? I don't want to iterate over the dictionary.
I know that there's only one element and I need to retrieve the key

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


Re: from a module return a class

2016-03-19 Thread Laurent Pointal
John Gordon wrote:

> In 
> kevind0...@gmail.com writes:
> 
>> ##  prompt the user for a User name a& pWord
>> user_pword = promptUser_PWord()
> 
>> I get the error
>>   File "H:\dev\eclipse\workspace\genXls\src\genXls\promptUser_PWord.py",
>>   line 58
>> return user_pword
>> SyntaxError: 'return' outside function
> 
> Show us the complete definition of promptUser_PWord().

AFAIU It looks to be the module…

> 

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


Re: from a module return a class

2016-03-19 Thread kevind0718
On Thursday, March 17, 2016 at 1:21:16 PM UTC-4, John Gordon wrote:
> In  
> kevind0...@gmail.com writes:
> 
> > ##  prompt the user for a User name a& pWord
> > user_pword = promptUser_PWord()   
> 
> > I get the error 
> >   File "H:\dev\eclipse\workspace\genXls\src\genXls\promptUser_PWord.py", 
> > line 58
> > return user_pword
> > SyntaxError: 'return' outside function
> 
> Show us the complete definition of promptUser_PWord().
> 
> -- 
> 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"

As requested code for promptUser_PWord


import base64
import os

import _winreg
import winerror

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from Tkinter import *

from unamepword import Unamepword

def butContinue():
global dbUser 
global pWord
global pwKey 
dbUser = entryName.get()
pWord  = entryPWord.get()
root1.quit()


dbUser = ""
pWord  = ""
root1 = Tk()
##root1.geometry("500x250")


lblTop = Label(root1, text=  'Please enter Database User Name & Password   ', 
font="Helvetica 14").grid(row=0, column=0, columnspan=3 , pady=5)
lblDB =Label(root1,text= 'User Name').grid(row=2, column=0 )
lblPWord = Label(root1, text= 'Password').grid(row=3,column=0)

entryName = Entry(root1)
entryName.grid(row=2, column=1, pady=5)

entryPWord = Entry(root1)
entryPWord.grid(row=3, column=1, pady = 5)

butGo  =  Button(root1, text="   Continue "  , command=butContinue 
).grid(row=5, column=1, sticky=W, pady=10)

root1.mainloop()

print "After the MainLoop"
print  dbUser
print  pWord


if dbUser is None or pWord is None  or  dbUser.strip() == ""   or  
pWord.strip() ==  ""  :
print "** ** ** ** ** ** ** ** ** **  ** **  ** ** ** ** ** ** ** ** ** **  
** **"
print "**  Missing a value CANNOT continue  ** ** ** "
print "**  Bye "
##  sys.exit()

user_pword =  Unamepword(dbUser, pWord)

return user_pword

   
 









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


Re: retrieve key of only element in a dictionary (Python 3)

2016-03-19 Thread Tim Chase
On 2016-03-18 17:33, Fillmore wrote:
> >>> d = dict()
> >>> d['squib'] = "007"
> >>> key = d.items()[0]

I posted a similar question about 1-element-sets[1] a while back and
Peter Otten & Rene Pijlman both suggested

  >>> s = set(["hello"])
  >>> element, = s

which, in your case would translate to

  >>> d = {"squib": "007"}
  >>> key, = d
  >>> key
  'squib'

I'd put a comment on the line to make it clear what's going on since
that comma is easy to miss, but based on Alex Martelli's testing[2],
it was the fastest of the proposed solutions.

-tkc

[1]
https://mail.python.org/pipermail/python-list/2006-January/392144.html

[2]
https://mail.python.org/pipermail/python-list/2006-January/382654.html



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


[issue26576] Tweak wording of decorator docos

2016-03-19 Thread Georg Brandl

Georg Brandl added the comment:

(Also, toggled your "is committer" bit so you get the Python logo next to your 
name.)

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Replace weird error message?

2016-03-19 Thread Chris Angelico
On Thu, Mar 17, 2016 at 5:39 AM, Joel Goldstick
 wrote:
> can you show the complete code?  It doesn't start with "{:02} I don't think

Actually, yes it does; I can confirm the OP's concern:

$ python3
Python 3.6.0a0 (default:ae76a1046bb9, Mar 17 2016, 05:45:31)
[GCC 5.3.1 20160121] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "{:02}".format(1)
'01'
>>> "{:02}".format("1")
Traceback (most recent call last):
  File "", line 1, in 
ValueError: '=' alignment not allowed in string format specifier
>>>

And I agree with the OP; the error message should not refer to the
equals sign if that wasn't present. Check the bug tracker at
bugs.python.org to see if it already exists, and if it doesn't, create
an issue. The message _is_ technically correct; here's what the docs
say:

"""
Preceding the width field by a zero ('0') character enables sign-aware
zero-padding for numeric types. This is equivalent to a fill character
of '0' with an alignment type of '='.
"""

However, this is definitely confusing; for positive integers,
alignment '=' is identical to alignment '>', which is (a) the default
for numbers, and (b) valid for strings (using "{:>02}" cures the
error). So go ahead and create the tracker issue, suggesting
alternative wording for the message.

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


Re: sobering observation, python vs. perl

2016-03-19 Thread Marko Rauhamaa
BartC :

> On 17/03/2016 18:53, Marko Rauhamaa wrote:
>> BartC :
>
>>> sub replacewith{
>>> $s = $_[0];
>>> $t = $_[1];
>>> $u = $_[2];
>>> $s =~ s/$t/$u/;
>>> return $s;
>>> }
>>>
>>> Although once done, the original task now looks a proper language:
>>>
>>> print (replacewith("I have a dream","have","had"));
>>
>> Now try your function with:
>>
>> print (replacewith("I have a dream",".","had"));
>
> Yeah, it needs your quotemeta line (whatever that does). But the call
> is unaffected as the clutter is in the function.

Well, you fell in the trap. Most perl programmers would fall in it. Same
with bash programmers, including myself.

That's why I'm wondering if Python could come to the rescue and offer a
solid alternative to bash. You have to go out of your way to get into
accidental quoting/escaping problems in Python.


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


Re: empty clause of for loops

2016-03-19 Thread Sven R. Kunze

On 18.03.2016 20:10, Palpandi wrote:

You can do like this.

if not my_iterable:
 
for x in my_iterable:
 


Thanks for you help here, however as already pointed out, my_iterable is 
not necessarily a list but more likely an exhaustible iterator/generator.


Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


[issue26470] Make OpenSSL module compatible with OpenSSL 1.1.0

2016-03-19 Thread Christian Heimes

Christian Heimes added the comment:

Here is a first working patch. It requires 1.1.0-pre4. The failing ALPN test is 
caused by a regression in OpenSSL.

--
keywords: +patch
stage: needs patch -> patch review
versions: +Python 3.6
Added file: 
http://bugs.python.org/file42184/0001-Port-Python-s-SSL-module-to-OpenSSL-1.1.0-WIP.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-19 Thread Mark Lawrence

On 19/03/2016 21:40, anyanwuchukwueme...@gmail.com wrote:

What was the final answer for the create class bankaccount question?



42.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: empty clause of for loops

2016-03-19 Thread Peter Otten
André Roberge wrote:

> On Wednesday, 16 March 2016 07:23:48 UTC-3, Sven R. Kunze  wrote:
>> Hi,
>> 
>> a colleague of mine (I write this mail because I am on the list) has the
>> following issue:
>> 
>> 
>> for x in my_iterable:
>>  # do
>> empty:
>>  # do something else
>> 
>> 
>> What's the most Pythonic way of doing this?
>> 
>> Best,
>> Sven
> 
> for x in my_iterable:
># do something
> 
> if not my_iterable:
># do something else
> 
> André

This will only work for sequences:

>>> items = iter("abc")
>>> bool(items)
True
>>> list(items)
['a', 'b', 'c']
>>> bool(items) # still true...
True
>>> list(items) # ... but empty
[]


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


[issue26567] ResourceWarning: Use tracemalloc to display the traceback where an object was allocated when a ResourceWarning is emitted

2016-03-19 Thread STINNER Victor

STINNER Victor added the comment:

It looks like io.FileIO has a strong implementation of the destructor. If the 
object becomes alive again because of random code called in the destructor, the 
object is not removed.

socket and os.scandir have a classical unsafe destructor.

Moreover, I'm no more sure about the chosen design. When 
warnings.catch_warnings() is used and an unclosed io.FileIO is destroyed, the 
object is kept alive because it is stored in the "source" attribute of a 
warnings.WarningMessage.

I don't know if keeping WarningMessaging alive longer than the call to 
showwarning() (or _showarnmsg) is a common use case or not. The issue #26568 
wants to promote the WarningMessage class, so some users may start to keep it 
alive.

An alternative is to format the object traceback and pass the traceback to 
WarningMessage. It requires to decide the format of the traceback (list of ..., 
string, something else?).

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-19 Thread Joel Goldstick
On Sat, Mar 19, 2016 at 5:40 PM,  wrote:

> What was the final answer for the create class bankaccount question?
> --
> https://mail.python.org/mailman/listinfo/python-list
>


Was it 14?

-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-19 Thread anyanwuchukwuemeka9
What was the final answer for the create class bankaccount question?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: WP-A: A New URL Shortener

2016-03-19 Thread Mark Lawrence

On 17/03/2016 22:34, Daniel Wilcox wrote:

+list



You will be far more welcome here if you intersperse your replies or 
bottom post.  Top posting is very heavily frowned upon.  Thanks.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[issue26577] inspect.getclosurevars returns incorrect variable when using class member with the same name as other variable

2016-03-19 Thread Ryan Fox

New submission from Ryan Fox:

If a variable 'x' exists in the global or local scope, and a function (also 
defined in the same scope as 'x', or lower) refers only to a member named 'x' 
of an object, inspect.getclosurevars will include a reference to the variable, 
rather than the member.

Okay, that's kind of confusing to describe, so here's a small example in code 
form:

import inspect

class Foo:
x = int()

x = 1
f = Foo()
assert(f.x != x)

func = lambda: f.x == 0
assert(func())

cv = inspect.getclosurevars(func)
assert(cv.globals['f'] == f)
assert(cv.globals.get('x') != x) # <--- Assertion fails


It is expected that 'x' would not exist in cv.globals, since func does not 
refer to it. Also, there should be a 'f.x' included somewhere in the 
ClosureVariables object returned.

--
components: Library (Lib)
messages: 261897
nosy: Ryan Fox
priority: normal
severity: normal
status: open
title: inspect.getclosurevars returns incorrect variable when using class 
member with the same name as other variable
versions: Python 3.3, Python 3.4, Python 3.5, Python 3.6

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26553] Write HTTP in uppercase

2016-03-19 Thread Aatish Neupane

Changes by Aatish Neupane :


Added file: http://bugs.python.org/file42198/fix_3.5.patch

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue26519] Cython doesn't work anymore on Python 3.6

2016-03-19 Thread Stefan Behnel

Stefan Behnel added the comment:

Our CI build server says it's all fine. The fix will eventually be released, 
certainly before Py3.6 comes out.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Bash-like pipes in Python

2016-03-19 Thread Chris Angelico
On Thu, Mar 17, 2016 at 4:04 AM, Marko Rauhamaa  wrote:
> Question: Could the generators define __repr__ so you wouldn't need to
> terminate the pipeline with "List" in interactive use?

No no no no. You do NOT want __repr__ to fundamentally change the
state of the object (which it would in that case - it'd consume the
generator!). What you want instead is to change sys.displayhook, which
affects *only* interactive use:

$ python3
Python 3.6.0a0 (default:ae76a1046bb9, Mar 17 2016, 05:45:31)
[GCC 5.3.1 20160224] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys, types
>>> def displayhook(obj):
... if isinstance(obj, types.GeneratorType):
... obj = list(obj)
... print("(%r)" % obj)
... else:
... print(repr(obj))
... __builtins__._ = obj
...
>>> def gen():
... yield 1
... yield 2
... yield 5
...
>>> gen()

>>> sys.displayhook = displayhook
>>> gen()
([1, 2, 5])
>>> _
[1, 2, 5]


To be properly reliable, you'd want to import this function from
another module, rather than create it interactively (imagine what
happens if you shadow the built-in 'list'); and you might want to
handle the conversion to concrete recursively (which __repr__ would
have do automatically). But it's still a *lot* safer than messing
around with repr!

(By the way, I'd really love to be able to write "def
sys.displayhook(obj):". But maybe that's more cute than truly useful.)

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


Re: AIX build and (potentially missing modules

2016-03-19 Thread Terry Reedy

On 3/17/2016 7:02 PM, Michael Felt wrote:

I have been packaging python for AIX - and wanting minimal dependancies
I have been ignoring the final messages from make.


You must be packaging 2.x rathar than 3.x


Personally, I do not see any real harm in the missing *audio "bits", but
how terrible are the other missing "bits" for normal python programs?


Some are gone in 3.x.


building dbm using ndbm
INFO: Can't locate Tcl/Tk libs and/or headers

Python build finished, but the necessary bits to build these modules
were not found:
_bsddb _curses_panel  _sqlite3
_tkinter   bsddb185   dl
gdbm   imageoplinuxaudiodev
ossaudiodevreadline   spwd
sunaudiodev


_tkinter is needed for tkinter, IDLE, turtle, and and user programs that 
use the tkinter GUI framework or turtle and any users that want the IDLE 
IDE.


_sqlite3 is needed for sqlite3 database module.

--
Terry Jan Reedy

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


Re: How to waste computer memory?

2016-03-19 Thread Mark Lawrence

On 17/03/2016 21:13, Chris Angelico wrote:


You can pretend that only 1 and 0 are enough. Good luck making THAT work.

ChrisA



The sales and marketing "thing", for lack of a better expression, that 
was used in the UK by Racal Telecommunications during the 1990s.  Well 
I'm telling a fib, IIRC it was 0 1.  Sales and marketing did not get the 
joke about it being a "two bit company".


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[issue26567] ResourceWarning: Use tracemalloc to display the traceback where an object was allocated when a ResourceWarning is emitted

2016-03-19 Thread STINNER Victor

STINNER Victor added the comment:

I used this patch to identify a ResourceWarning in test_faulthandler when the 
test is interrupted by CTRL+c: it's really efficient!

I will be very useful to identify all ResourceWarning that I saw in 
test_asyncio, like the ones seen on the AIX buildbot.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Case Statements

2016-03-19 Thread Steven D'Aprano
On Wed, 16 Mar 2016 09:34 pm, BartC wrote:


> (BTW why does Python have 'elif' when if-else is all that is really
> needed?)

To save indentation.


if condition:
block
else:
if other:
block
else:
if third:
block
else:
block


versus:

if condition:
block
elif other:
block
elif third:
block
else:
block


Python could have spelled "elif" as "else if", but that's just a matter of
spelling. Either way, the important thing is that the else-if/elif keeps
the same indentation as the if.



-- 
Steven

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


Re: How to waste computer memory?

2016-03-19 Thread Mark Lawrence

On 18/03/2016 21:02, Marko Rauhamaa wrote:

Chris Angelico :

On Sat, Mar 19, 2016 at 2:26 AM, Marko Rauhamaa  wrote:

It may be that Python's Unicode abstraction is an untenable illusion
because the underlying reality is 8-bit and there's no way to hide it
completely.


The underlying reality is 1-bit. Or maybe the underlying reality is
actually electrical signals that don't even have a clear definition of
"bits" and bounce between two states for a few fractions of a second
before settling. And maybe someone's implementing Python on the George
Banks Kite CPU, which consists of two cents' worth of paper and
string, on which text is actually represented by glyph. They're all
equally valid notions of "underlying reality".

Text is an abstract concept, just as numbers are.


The question is how tenable the illusion is. If the OS gave the
appropriate guarantees (say, all pathnames are encoded Unicode strings),
the abstraction could be maintained. Unfortunately, the legacy shines
through making you wonder if Python has overreached prematurely with its
Unicode HAL.

Marko



I have no idea at what the above can mean, other than that you are 
agreeing with the RUE.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[issue26567] ResourceWarning: Use tracemalloc to display the traceback where an object was allocated when a ResourceWarning is emitted

2016-03-19 Thread STINNER Victor

STINNER Victor added the comment:

When warnings._showwarnmsg(), the io.FileIO object is not closed yet, so all 
attributes are accessible, which can be useful. Hopefully, the file is closed 
even if it is kept alive by the warning logger. So maybe it's ok to keep the 
Python object alive, if the underlying resource (the file descriptor) is 
released. I mean, it's not a big deal.

--

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



file -SAS

2016-03-19 Thread Val Krem via Python-list
Hi all,

I am trying to read sas7bdat file using the following



from sas7bdat import SAS7BDAT

with SAS7BDAT('test.sas7bdat') as f:
for row in f:
 print row   ### I want print the first 10 row. how can I do that?


I got error message of 


from sas7bdat import SAS7BDAT
ImportError: No module named sas7bdat

What did I miss?
Val
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Simple exercise

2016-03-19 Thread boffi
Rodrick Brown  writes:

> BANANA FRIES 12
> POTATO CHIPS 30
> APPLE JUICE 10
> CANDY 5
> APPLE JUICE 10
> CANDY 5
> CANDY 5
> CANDY 5
> POTATO CHIPS 30
>
> I'm expecting the following output
> BANANA FRIES 12
> POTATO CHIPS 60
> APPLE JUICE 20
> CANDY 20

>>> data =["BANANA FRIES 12",
..."POTATO CHIPS 30",
..."APPLE JUICE 10",
..."CANDY 5",
..."APPLE JUICE 10",
..."CANDY 5",
..."CANDY 5",
..."CANDY 5",
..."POTATO CHIPS 30"]
>>> d = {}
>>> for el in data:
... el = el.split()
... name, n = ' '.join(el[:-1]), int(el[-1])
... d[name] = d[name]+n if name in d else n
...
>>> d
{'POTATO CHIPS': 60, 'BANANA FRIES': 12, 'APPLE JUICE': 20, 'CANDY': 20}
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   >