Tkinter - cannot import tklib

2022-06-20 Thread Wolfgang Grafen
Hello all,

I am an experienced Python user and struggle with following statement:

>>> from tklib import *
Traceback (most recent call last):
File "", line 1, in 
ModuleNotFoundError: No module named 'tklib'

I tried to import tklib as shown above on following of my Python installations: 
Anaconda Python 3.8.3, Portable Python 3.9, Python 3.10.1, Python 2.7.10 with 
the same negative result.

I also tried to find help by googling - without success. Also I did not find a 
python module called tklib to install. Tkinter, ttk is working fine.

There are numerous examples using "from tklib import *" so I assume it works 
for most. In the tk-tutorial below tklib is used without special explanation, 
so I assume it should be installed by default with every python installation 
which has Tkinter integrated. 

https://tk-tutorial.readthedocs.io/en/latest/intro/intro.html?highlight=app#

First time that I cannot help myself. Please help, what do I do wrong?

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


use set notation for repr of dict_keys?

2021-02-20 Thread Wolfgang Stöcher

Having a dict like
  d = {'one': 1, 'two': 2}
the representation of its keys
  repr(d.keys())
gives
  "dict_keys(['one', 'two'])"

But since the keys are unique, wouldn't a representation using the set  
notation
be more intuitive, i.e. what about changing the output of  
dict_keys.__repr__ to

"dict_keys({'one', 'two'})"
(using curly braces instead of brackets)

Wolfgang

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


Re: Spread a statement over various lines

2019-09-18 Thread Wolfgang Maier
On 17.09.19 20:59, Manfred Lotz wrote:
> I have a function like follows
> 
> def regex_from_filepat(fpat):
> rfpat = fpat.replace('.', '\\.') \
>   .replace('%', '.')  \
>   .replace('*', '.*')
> 
> return '^' + rfpat + '$'
> 
> 
> As I don't want to have the replace() functions in one line my
> question is if it is ok to spread the statement over various lines as
> shown above, or if there is a better way?
> 

One problem with explicit line continuation using \ is that it is
dependent on the backslash being the last character on the line, i.e.
a single space at the end of the line will result in a SyntaxError.
This is why implicit line continuation relying on opened parentheses,
brackets or curly braces is often preferred, and recommended over
backslash continuation in PEP8
(https://www.python.org/dev/peps/pep-0008/#maximum-line-length).
To use implicit line continuation you could either introduce extra
surrounding parentheses as suggested by others, or you may make use
of the parentheses you have already, like so:

def regex_from_filepat(fpat):
rfpat = fpat.replace(
'.', '\\.'
).replace(
'%', '.'
).replace(
'*', '.*'
)

return '^' + rfpat + '$'


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


Re: Can pip install packages for all users (on a Linux system)?

2018-07-24 Thread Wolfgang Maier

On 24.07.2018 20:07, John Ladasky wrote:

I've been using "sudo pip3 install" to add packages from the PyPI repository.  
I have multiple user accounts on the computer in question.  My goal is to install 
packages that are accessible to all user accounts.  I know that using the Synaptic 
Package Manager in Ubuntu will install for all users, but not every Python package is 
included in the Canonical repository.

I hadn't noticed any discrepancies until recently.  I upgraded from Ubuntu 
17.10 to 18.04.  In parallel, I upgraded tensorflow-gpu 1.4.0 to 1.8.0.  
Everything worked on my main account.  However, attempting to import tensorflow 
from Python on a secondary account failed.  Eventually I checked the pip lists 
in each account, and I found a reference to the old tensorflow 1.4 on the 
secondary account.  Uninstalling that, and reinstalling tensorflow-gpu 1.8 on 
the secondary account fixed the problem.



One possible explanation for your finding: user installs normally take 
precedence over system-wide installs both at import time and for pip 
(list, uninstall, etc.). So if you, or your users, have installed 
tensorflow 1.4.0 using pip install --user before, then a system-wide pip 
install tensorflow 1.8.0 won't override this previous version (though if 
your admin account has the user install, too, pip would warn you).
Otherwise, a pip install without --user is effectively a system-wide 
install as long as your Python is a system-wide install.



I believe that I now have tensorflow 1.8 installed twice on my system, once for 
each user.  If anyone can share how to convince pip to behave like Synaptic, I 
would appreciate it.  Thanks.



If a user has a user install of tensorflow, it will always shadow the 
system-wide version. The only solution I know (except manipulating 
Python's import path list) is to pip uninstall the per-user version.


Best,
Wolfgang

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


Re: 转发: No pip for my Python 3.6.5!

2018-07-09 Thread Wolfgang Maier

On 07/09/2018 10:14 AM, 卢 嘉幸 wrote:


Hi~

I am a beginner with Python.
My computer is of Windows version.
And I dowloaded the lastest version of python on the https://www.python.org/ .
My book, Automate the Boring Stuff With Python, teaches me to install a 
third-party module with the command line: pip install send2trash (for example).
But there comes the error message !!!

What is going wrong?
It makes no sense since my Python is 3.6.5 version.
I doubt that my poor Python doesn’t have a pip.



Does the following work for you?

py -3 -m pip install send2trash

work for you? If so, you can either continue to run pip like this (it is 
a good way) or you'll have to make pip.exe discoverable from your PATH 
as suggested by Abdur-Rahmaan.


Best,
Wolfgang

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


Re: Question : Input after all prompts in python

2018-06-11 Thread Wolfgang Maier

On 06/11/2018 04:19 PM, moha...@gmail.com wrote:


BTW i tried the code above, but i encountered a syntax error.

print(u"\u001b[{}A".format(n), flush=True, end="")
  ^
SyntaxError :invalid syntax



That's probably because you have been running it in Python2.
Most people here assume you mean Python3 nowadays if you say Python, 
especially when you ask a beginner's question.



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


Re: please test the new PyPI (now in beta)

2018-03-27 Thread Wolfgang Maier
For me, that's a window width issue. The sidebar with the filters only 
shows when the window is wide enough. Unfortunately, the text mentioning 
it doesn't change, so this should be fixed.



On 03/27/2018 12:06 PM, Steven D'Aprano wrote:

On Tue, 27 Mar 2018 10:48:15 +0100, Paul Moore wrote:


By the way, on the search page:

https://pypi.org/search/


it says "Enter a search query above, or select a filter from the list
of classifiers on the left" but there is no such filter or list of
classifiers.


Do you not get the section

"""

Filter Projects

By Programming Language
By License
By Framework
...
"""

on the left of the page?


There's nothing on the left of the page. It has:

(pypi logo) (search projects text box)

("Enter a search query..." with examples)

(Add filter button)


then the blue footer with "Get Help", "About PyPI", etc.





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


Re: Entering a very large number

2018-03-23 Thread Wolfgang Maier

On 03/23/2018 01:30 PM, Wolfgang Maier wrote:

On 03/23/2018 01:16 PM, ast wrote:

Hi

I found this way to put a large number in
a variable.

C = int(
"28871482380507712126714295971303939919776094592797"
"22700926516024197432303799152733116328983144639225"
"94197780311092934965557841894944174093380561511397"
"4215424169339729054237110027510420801349667317"
"5515285922696291677532547505856101949404200039"
"90443211677661994962953925045269871932907037356403"
"22737012784538991261203092448414947289768854060249"
"76768122077071687938121709811322297802059565867")



A very simple improvement would be to use a single
triple-quoted string. Assuming you are copy/pasting
the number from somewhere that will save a lot of your
time.


Like this, for example:

n = int(
''.join("""
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
""".split())
)

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


Re: Entering a very large number

2018-03-23 Thread Wolfgang Maier

On 03/23/2018 01:16 PM, ast wrote:

Hi

I found this way to put a large number in
a variable.

C = int(
"28871482380507712126714295971303939919776094592797"
"22700926516024197432303799152733116328983144639225"
"94197780311092934965557841894944174093380561511397"
"4215424169339729054237110027510420801349667317"
"5515285922696291677532547505856101949404200039"
"90443211677661994962953925045269871932907037356403"
"22737012784538991261203092448414947289768854060249"
"76768122077071687938121709811322297802059565867")



A very simple improvement would be to use a single
triple-quoted string. Assuming you are copy/pasting
the number from somewhere that will save a lot of your
time.


It works but is it not optimal since there is a
string to int conversion.

I was not able to put an integer directly because
character '\' for line cut doesnt work inside an
integer

C = \
28871482380507712126714295971303939919776094592797\
22700926516024197432303799152733116328983144639225\
...
76768122077071687938121709811322297802059565867

doesn't work

Do you have a better idea ?

Thx




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


Re: curious asymmetry in range limiting

2018-03-20 Thread Wolfgang Maier

On 03/20/2018 03:21 PM, Robin Becker wrote:

I don't know how I never came across this before, but there's a curious 
asymmetry in the way ranges are limited

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  >>> s = '0123456789'
  >>> print(repr(s[-5:5]))
''
  >>> print(repr(s[5:15]))
'56789'
  >>>

why is the underflow start index treated so differently from the limit index 
overflow? I suppose there must be some reason, but it
eludes me.



It's because in the slice [-5:5] the -5 is not trying to access an 
element at an index < 0, but indicating the fifth-last element in the 
sequence.



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


Re: Console

2018-03-07 Thread Wolfgang Maier

On 03/07/2018 03:41 PM, Jeremy Jamar St. Julien wrote:

I had an problem when trying to start the python GUI. It said there was a subprocess 
startup error. I was told to start IDLE in a console with idlelib and see what python 
binary i was runnning IDLE with. Im using windows 10 and i guess console refers to the 
terminal window and i have no idea what they meant by "the binary its running 
with"



The simplest way to open the console on Windows is to press Win+R (the 
Windows key together with the r key that is). In the run dialog that 
appears then, type cmd and the console window should appear.

To start IDLE from there type:
py -m idlelib

Good luck,
Wolfgang

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


Re: Ways to make a free variable local to a function?

2018-03-06 Thread Wolfgang Maier

On 03/05/2018 07:44 PM, Terry Reedy wrote:

On 3/5/2018 9:34 AM, Chris Angelico wrote:

On Tue, Mar 6, 2018 at 12:52 AM, Terry Reedy  wrote:

On 3/5/2018 7:12 AM, Kirill Balunov wrote:

# 1. By passing through local variable's default values

   def func_local_1(numb, _int = int, _float = float, _range = range):



You are not required to mangle the names.

def func_local_1(numb, int = int, float = float, range = range):
...



Even so, this does mess up the function's signature,


Which I why I only said that using the original names solves the syntax
highlighting issue (of marking built-ins as built-ins).


leaving your
callers wondering if they can call it with some sort of range
parameter. (Though in this particular instance, range() is only called
once, so it's pretty much useless to try to optimize it.)

In theory, the CPython bytecode compiler (don't know about other
Python implementations) could just add these as constants.


Yes, what we really want for this sort of thing are unrebindable local
constants.  A simple syntax change could do it.

   def func_local_1(numb; int = int, float = float, range = range):

The binding after ';' belong in the header because they should be done once.



Ah, I did not really understand initially what Kirill was trying to 
achieve by putting the name binding into the function signature.
Now I do, but I don't think it is a good idea. Sanctioning this with 
dedicated syntax would only make Python more static because for any 
function defined this way, you would lose the ability to alter the 
behavior of that function through changing the global binding after the 
function has been called (in the example above, you could no longer mock 
replace int, float and range on subsequent func_local_1 calls) and I 
don't think this is something that should be encouraged.


Wolfgang


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


Re: Is there are good DRY fix for this painful design pattern?

2018-02-27 Thread Wolfgang Maier

On 26.02.2018 15:41, Steven D'Aprano wrote:

I have a class with a large number of parameters (about ten) assigned in
`__init__`. The class then has a number of methods which accept
*optional* arguments with the same names as the constructor/initialiser
parameters. If those arguments are None, the defaults are taken from the
instance attributes.



Others have pointed out good solutions already, in particular, combining 
inspect and decorators or encapsulating the parameters in an object.


Alternatively, you could reconsider your class design. Although I can't 
tell from your example whether this idea would be acceptable for your 
use case, consider removing your parameters from the class methods 
(except from __init__) altogether so the values passed during 
instantiation cannot be changed later. In exchange, add module-level 
functions corresponding to each of your class methods that accept 
**kwargs and that generate new instances of your class passing **kwargs 
on to __init__, then call the corresponding instance method.

The stdlib textwrap module, for example, uses this approach.

Best,
Wolfgang

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


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Gro

2018-02-09 Thread Wolfgang Maier

On 02/09/2018 12:23 PM, John Ladasky wrote:

On Friday, February 9, 2018 at 12:50:16 AM UTC-8, Tim Golden wrote:

Gmane offers a newsgroup interface to the mailing list


I haven't visited GMane in a few years, but I found it difficult to navigate.  
In particular, I found searching to be cumbersome.  Weren't the archives broken 
into 30-day blocks?

I just tried GMane again two minutes ago.  I can't confirm my recollections, 
but right now what I'm seeing is worse.  If you follow this link right now... 
(http://gmane.org/find.php?list=comp.lang.python)... you get this:

"Not all of Gmane is back yet - We're working hard to restore everything"

And if you follow the link labeled "The latest news is at Gmane News" at the 
bottom of that page, it takes you here... (http://home.gmane.org/)... and the top blog 
post discussing site repairs is dated September 2016!

I'm not too excited about trying GMane again after seeing that.



You are certainly right about the gmane *Web Interface*. However, you 
can access their newsgroup interface through any newsgroup reader 
(including e.g. Thunderbird) and that's a really nice way of following 
things.


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


Re: replacing `else` with `then` in `for` and `try`

2017-11-02 Thread Wolfgang Maier

On 11/02/2017 06:09 PM, Skip Montanaro wrote:

Eh, what can I say? I guess I was paying too much attention to the baseball
game. Yes, "else" handles the "fall off the end" termination, not the "exit
early" termination. My apologies. I do think that having a way to spell "do
this when the loop exits early" makes things clearer. So, perhaps while and
for loops could someday grow except clauses. :-)



... and even this idea has been discussed before:

https://mail.python.org/pipermail/python-ideas/2017-March/044932.html

There wasn't much enthusiasm about it though because few people (ok, 
maybe even just me) thought it had interesting use cases.


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


Re: A use-case for for...else with no break

2017-11-02 Thread Wolfgang Maier

On 11/02/2017 12:45 PM, Alberto Berti wrote:

"Steve" == Steve D'Aprano  writes:


 py> for x in "abcdefgh":
 Steve> ... print(x, end='')
 Steve> ...
 py> efghpy>


 Steve> "For ... else" to the rescue!

 py> for char in "abcdefgh":
 Steve> ... print(char, end='')
 Steve> ... else:
 Steve> ... print()
 Steve> ...
 Steve> abcdefgh
 py>

else doesn't seem to bring any advantage over:

for char in "abcdefgh":
 print(char, end='')
print()



Try running it interactively and you'll see,
wolfgang

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


Re: Code Snippets

2017-11-01 Thread Wolfgang Maier

On 01.11.2017 18:25, Stefan Ram wrote:

   I started to collect some code snippets:

   Sleep one second

__import__( "time" ).sleep( 1 )

   Get current directory

__import__( "os" ).getcwd()

   Get a random number

__import__( "random" ).random()

   And so on. You get the idea.

   However, reportedly, all those snippets are anti-patterns
   because they use »__import__«.

   But what I like about them: You just paste them in where
   you want them to be, and your done.

   What I'm supposed to do instead, I guess, is:

   Sleep one second

import time
...
time.sleep( 1 )

   Get current directory

import os
...
os.getcwd()

   Get a random number

import random
...
random.random()

   Now, the user has to cut the import, paste it to the top
   of his code, then go back to the list of snippets, find
   the same snippet again, copy the expression, go to his code,
   then find the point where he wanted to insert the snippet again,
   and finally insert the snippet. And still there now is a
   risk of name collisions. So, it seems to me that __import__
   is just so much better!



I'm not sure why you think this has to do with import vs __import__.
If you're worried bout having things on separate lines, you could write:

import os; os.getcwd()

,etc., which is actually saving a few characters :)



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


Re: matplot plot hangs

2017-11-01 Thread Wolfgang Maier

On 01.11.2017 00:40, Andrew Z wrote:

hello,
  learning python's plotting by using matplotlib with python35 on fedora 24
x86.

Installed matplotlib into user's directory.
tk, seemed to work -
http://www.tkdocs.com/tutorial/install.html#installlinux - the window shows
up just fine.
but when trying to run the simple plot (
https://matplotlib.org/examples/pylab_examples/simple_plot.html) the script
is hanging on;

plt.plot(t, s)

attempts to
matplotlib.interactive(True) didn't bring anything,



Hi Andrew,

From which environment are you trying to run the example? In the 
terminal, from within some IDE, inside a jupyter notebook?


Are you sure the script "is hanging on plt.plot(t, s)" and not after that?

Best,
Wolfgang

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


Re: Textwrap doesn't honour NO-BREAK SPACE

2017-09-29 Thread Wolfgang Maier

On 29.09.2017 11:05, Wolfgang Maier wrote:

On 29.09.2017 07:25, Steve D'Aprano wrote:

I'm pretty sure this is a bug.



Yes, it is a bug, but a known one: https://bugs.python.org/issue20491

The fix got backported even to 3.5, but I guess it depends which minor 
version you are running. I'm pretty sure that explains why people report 
different outcomes.


Best,
Wolfgang



To be specific, this should be fixed from 3.5.3 and 3.6.0b3 onwards.

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


Re: Textwrap doesn't honour NO-BREAK SPACE

2017-09-29 Thread Wolfgang Maier

On 29.09.2017 07:25, Steve D'Aprano wrote:

I don't have Python 3.6 installed, can somebody check to see whether or not it
shows the same (wrong) behaviour?


import textwrap
text = ('Lorum ipsum dolor sit amet, consectetur adipiscing'
 ' elit ZZZ\xa0ZZZ sed do euismod tempor incididunt'
 ' ut labore et dolore magna aliqua.')
print(textwrap.fill(text, 59))



Expected result:


Lorum ipsum dolor sit amet, consectetur adipiscing elit
ZZZ ZZZ sed do euismod tempor incididunt ut labore et
dolore magna aliqua.


Actual result in Python 3.5 and older:


Lorum ipsum dolor sit amet, consectetur adipiscing elit ZZZ
ZZZ sed do euismod tempor incididunt ut labore et dolore
magna aliqua.


I'm pretty sure this is a bug.



Yes, it is a bug, but a known one: https://bugs.python.org/issue20491

The fix got backported even to 3.5, but I guess it depends which minor 
version you are running. I'm pretty sure that explains why people report 
different outcomes.


Best,
Wolfgang


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


Re: Simple board game GUI framework

2017-09-12 Thread Wolfgang Maier

On 11.09.2017 12:58, Paul Moore wrote:

I'm doing some training for a colleague on Python, and I want to look
at a bit of object orientation. For that, I'm thinking of a small
project to write a series of classes simulating objects moving round
on a chess-style board of squares.

I want to concentrate on writing the classes and their behaviour, and
not on display issues, but I would like it if the resulting program
was reasonably interesting. To that end, I was thinking of putting
together a frontend that displayed the objects moving round on a board
(rather than, for example, just printing out lists of co-ordinates).
I'd build the frontend, then my student could write the object classes
and drop them into the framework.



Maybe not exactly what you are asking for, but something I thought about 
for a Python class earlier this year: There are several Minecraft mods 
that let you interact with the game from Python. Of course, Minecraft 
itself is Java code, but it's a prime example of OOP and you are getting 
a very sophisticated and fully tested display engine for free. It's a 
bit complicated to get started with (which eventually made me postpone 
this experiment to next year's class), but I think it may be a lot of 
fun, especially if you've played Minecraft before. Here's a link to get 
you started: http://www.instructables.com/id/Python-coding-for-Minecraft/


Best,
Wolfgang

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


Re: Proposed new syntax

2017-08-10 Thread Wolfgang Maier

On 08/10/2017 04:28 PM, Steve D'Aprano wrote:

Every few years, the following syntax comes up for discussion, with some people
saying it isn't obvious what it would do, and others disagreeing and saying
that it is obvious. So I thought I'd do an informal survey.

What would you expect this syntax to return?


As one of the people who have suggested this or similar syntax once I 
hope I'm not too far off a potential consensus :)




[x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]



[1, 2, 3]



For comparison, what would you expect this to return? (Without actually trying
it, thank you.)

[x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]



[1, 2, 3, 4, 5]



How about these?

[x + y for x in (0, 1, 2, 999, 3, 4) while x < 5 for y in (100, 200)]



[100, 200, 101, 201, 102, 202]


[x + y for x in (0, 1, 2, 999, 3, 4) if x < 5 for y in (100, 200)]



[100, 200, 101, 201, 102, 202, 103, 203, 104, 204]



Thanks for your comments!





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


Re: Write this accumuator in a functional style

2017-07-10 Thread Wolfgang Maier

On 07/11/2017 08:11 AM, Steven D'Aprano wrote:

I have a colleague who is allergic to mutating data structures. Yeah, I
know, he needs to just HTFU but I thought I'd humour him.

Suppose I have an iterator that yields named tuples:

Parrot(colour='blue', species='Norwegian', status='tired and shagged out')

and I want to collect them by colour:

accumulator = {'blue': [], 'green': [], 'red': []}
for parrot in parrots:
 accumulator[parrot.colour].append(parrot)


That's pretty compact and understandable, but it require mutating a bunch
of pre-allocated lists inside an accumulator. Can we re-write this in a
functional style?

The obvious answer is "put it inside a function, then pretend it works by
magic" but my colleague's reply to that is "Yes, but I'll know that its
actually doing mutation inside the function".


Help me humour my colleague.





Hmm, isn't this just asking for itertools.groupby on the parrots sorted 
by colour?


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


Re: Transitioning from Linux to Windows

2017-06-03 Thread Wolfgang Maier

On 03.06.2017 15:44, chitt...@uah.edu wrote:

I am looking for suggestions, ideas.

I have developed python (3.6.x, 2.7.x) scripts that run well as a user on an 
ubuntu/16.04 system - the scripts look for files, parses the files, assembles 
an output for the user.

I first cd into a particular directory on the system (where I know the files 
exist) and run the script - the final result is in my working directory.

What I am now trying to do is ... figure out the least painful way to have 
other users do the same - BUT sitting in front of a Windows desktop (7 or 10).

Ideally, I would like to set up the user on their Windows 7/10 system so that they can 
"login" to the ubuntu system (say putty) - change working directory (to where 
desired) - run the script (on the ubuntu system) - and scp the file back to the windows 
desktop.

("porting" the ubuntu script to anaconda(3) on the windows desktop IS possible (but it 
has not been as easy as I had hoped!) (django and programs like that do seem to provide a 
"GUI" to have python scripts run on ubuntu/systems - but the setup looks 
mysterious/complicated (to me anyway))

I stumbled onto "paramiko" - is that a possible answer?

Any suggestion/ideas would be greatly appreciated!

(I am perfectly willing to stick to 3.6.x, unless there is a clean/easy
solution using 2.7.x)

krishnan



An alternative to writing your own server app using django, though 
admittedly less exciting from a developer's point of view, could be
x2goclient/server (http://wiki.x2go.org/doku.php/start). That would be 
more like your putty suggestion, but a lot more user-friendly.


Wolfgang

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


Re: Python not able to find package but it is installed

2017-05-31 Thread Wolfgang Maier

On 05/30/2017 09:27 PM, Mahmood Naderan via Python-list wrote:

Well yes. It looks in other folders


But

$ find /opt -name openpyxl
/opt/rocks/lib/python2.6/site-packages/openpyxl



So, your pip knows about a search path that python doesn't know.
That can have a number of reasons still and one would be Pavol's 
suggestion that your pip command may run on a different python than the 
python you invoke with the commmand 'python'. However, this would 
require that you have two separate installs of python2.6 on your system, 
which sounds rather unlikely.


Another possibility is that pip picks up additional directories from a 
pip config file somewhere. To check this you could compare


pip show openpyxl
to
pip show --isolated openpyxl
(which would ignore any pip config file or environment variable)

or (since I don't remember what commands your rather old version of pip 
will support):


pip list vs pip list --isolated
(which should give all installed packages pip knows about with and 
without additional config settings.


Wolfgang

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


Re: Python not able to find package but it is installed

2017-05-30 Thread Wolfgang Maier

On 05/30/2017 10:18 AM, Mahmood Naderan via Python-list wrote:

Hello,
Although I have installed a package via pip on a centos-6.6, python interpreter 
still says there is no such package!

Please see the output below

$ python exread2.py input.xlsx tmp/output
Traceback (most recent call last):
File "/home/mahmood/excetest/exread2.py", line 1, in 
from openpyxl import load_workbook
ImportError: No module named openpyxl


$ pip install openpyxl
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please 
upgrade your Python. A future version of pip will drop support for Python 2.6
Requirement already satisfied: openpyxl in 
/opt/rocks/lib/python2.6/site-packages

...



In addition to checking sys.path as suggested, also try running

python -V

to check if it's Python2.6 as reported by pip or if you have two 
different versions of Python installed.


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


Re: How to update python from 3.5.2 to 3.5.3 on Linux

2017-05-03 Thread Wolfgang Maier

On 03.05.2017 17:11, Thomas Nyberg wrote:

On 05/03/2017 11:04 AM, Daiyue Weng wrote:

nope, I was thinking it might be good to update to 3.5.3 for security
reasons?



(CCing back in python-list since I accidentally dropped it.)

I wouldn't worry about it. Package managers tend to usually take care of
security updates. (Of course there is criticism of Linux Mint saying
they're not as great at this...) Looking at Ubuntu 16.04, they are still
on 3.5.1 (plus Ubuntu's own patches):

http://packages.ubuntu.com/xenial/python3



Maybe I'm mistaken here, but I don't think that is fully true. With an 
LTS version of Ubuntu you I don't think you will *ever* get upgraded to 
a new Python version. Instead Canonical will backport changes from new 
maintainance releases like 3.5.2/3.5.3 to older releases of the same 
minor version (like the 3.5 series). So while the package for Python3.5 
for Ubuntu 16.04 will seem pinned at version 3.5.1 over the lifetime of 
the OS, the actual Python version you are running may be newer. In fact, 
on my 16.04:


% apt list python3
python3/xenial,now 3.5.1-3 amd64 [installed]

% python3 -V
Python 3.5.2

I have no clue how Mint handles this though.

Wolfgang

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


Re: Python 3.5+ Arrow keys and others in the console

2017-04-16 Thread Wolfgang Maier

On 16.04.2017 10:56, Vincent Vande Vyvre wrote:

Hi,

I'm using Python 3.5 and 3.6 in venv and I see a strange behaviour in
the interactive interpreter.

The arrow keys can't be used to move the cursor into the current line of
code or to rewrite the last lines.

With the 3.5 I can use the backspace and erase the code but not in 3.6

Python 3.5.2 (default, Dec 19 2016, 11:46:33)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

f = "kjhfgt"^[[D# Left Arrow Key
^[[A# Up Arrow Key



Python 3.6.1 (default, Apr 12 2017, 11:39:17)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

f = "lkjgh"
^[[A^[[B# Up Arrow Key and Backspace Key

  File "", line 1

^
SyntaxError: invalid syntax






Make sure you build Python (I guess you did this for 3.6, but are 
probably using your OS Python3.5) with readline. This needs the dev 
version of the readline library installed at build time.

So, step 1 would be to get the library, then rebuild Python3.6 by running:

1) make clean
2) ./configure
3) make

It could be worthwhile checking for other missing optional C libraries 
first though. If you want to make sure you have all of them, follow the 
steps described here:


https://docs.python.org/devguide/setup.html#build-dependencies

Best,
Wolfgang


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


Re: Disallowing instantiation of super class

2017-02-24 Thread Wolfgang Maier

On 24.02.2017 01:19, Irv Kalb wrote:

Hi,
I have built a set of three classes:
-  A super class, let's call it: Base

-  A class that inherits from Base, let's call that: ClassA

-  Another class that inherits from Base, let's call that: ClassB

ClassA and ClassB have some code in their __init__ methods that set some 
instance variables to different values.  After doing so, they call the the 
__init__ method of their common super class (Base) to set some other instance 
variables to some common values.  This all works great.  Instances of ClassA 
and ClassB do just what I want them to.



[...]


If I can find a way to determine that the caller is attempting to instantiate 
Base directly, I will raise an exception.



A pattern I'm using sometimes to achieve this is:

class Base:
def __init__(self):
self.set_common()
self.set_specific()

def set_common(self):
self.a = 10

def set_specific(self):
raise NotImplementedError()


class A(Base):
def set_specific(self):
self.b = 20


class B(Base):
def set_specific(self):
self.b = 30


Of course, MRAB's and Peter's suggestion are very similar ideas.

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


Re: PTH files: Abs paths not working as expected. Symlinks needed?

2017-02-15 Thread Wolfgang Maier

On 15.02.2017 13:42, poseidon wrote:

On 15/02/17 12:16, Wolfgang Maier wrote:

On 15.02.2017 10:33, poseidon wrote:

In /usr/lib/python3.6/site-packages I wrote a file tau4.pth. It contains
the line

/home/poseidon/tau4/swr/py3/src

In /home/poseidon/tau4/swr/py3/src there's an __init__.py file, so it
should be possible to write

import tau4

in my programs.



No, that's not what you should expect!
A path file contains paths to be added at interpreter startup to the
package/module search path stored in sys.path. That is, in your example,
if you put a file tau4.py or a tau4 directory with the __init__.py file
inside into /home/poseidon/tau4/swr/py3/src, *then* you could import
tau4.


It works, if I set a symlink to /home/poseidon/tau4/swr/py3/src in the
site-packages dir:

ln -s /home/poseidon/tau4/swr/py3/src
/usr/lib/python3.6/site-packages/tau4



Well this works because now Python finds (following the symlink) a tau4
package (i.e., a directory with that name and an __init__.py file
inside) in /usr/lib/python3.6/site-packages. The .pth file is not
involved in this at all.



Yes, removed it (symlink still there) and it still works. But then, what
are pth files for? I'd just place a symlink to the package and am done
with. The path doesn't seem to be needed in sys.path (where it would go
if placed in a pth file). If I write

from tau4 import datalogging

that works, too. So no need for the path being in sys.path (i.e. in a
pth file)?



I guess a major point of .pth files is that you only have one or a small 
number of files with a clear purpose polluting the containing directory. 
Of course, you could put symlinks to all your packages and modules into 
site-packages, but what's the point of putting them somewhere else in 
the first place? Also, you cannot create symlinks across devices, but 
.pth files will work.


Best,
Wolfgang

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


Re: PTH files: Abs paths not working as expected. Symlinks needed?

2017-02-15 Thread Wolfgang Maier

On 15.02.2017 10:33, poseidon wrote:

In /usr/lib/python3.6/site-packages I wrote a file tau4.pth. It contains
the line

/home/poseidon/tau4/swr/py3/src

In /home/poseidon/tau4/swr/py3/src there's an __init__.py file, so it
should be possible to write

import tau4

in my programs.



No, that's not what you should expect!
A path file contains paths to be added at interpreter startup to the 
package/module search path stored in sys.path. That is, in your example, 
if you put a file tau4.py or a tau4 directory with the __init__.py file 
inside into /home/poseidon/tau4/swr/py3/src, *then* you could import tau4.



It works, if I set a symlink to /home/poseidon/tau4/swr/py3/src in the
site-packages dir:

ln -s /home/poseidon/tau4/swr/py3/src /usr/lib/python3.6/site-packages/tau4



Well this works because now Python finds (following the symlink) a tau4 
package (i.e., a directory with that name and an __init__.py file 
inside) in /usr/lib/python3.6/site-packages. The .pth file is not 
involved in this at all.



https://docs.python.org/3.6/library/site.html suggests that PTH files
only work relative to the site-packages dir. But digging around in e.g.
StackOverflow I got the impression that absolute paths should work as
well. If so, what am I doing wrong?

I'm on Arch Linux, Python 3.6.

Kind regards
Paul




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


Re: subprocess problem

2017-02-09 Thread Wolfgang Maier

On 09.02.2017 01:56, Andreas Paeffgen wrote:

The Problem with the subprocess code is: Using the sourcecode
functioning as normal.
The frozen app with cx_freeze on every platform just returns an empty
result

Here is the code in short:
def get_path_pandoc():




   settings = QSettings('Pandoc', 'PanConvert')

   path_pandoc = settings.value('path_pandoc','')




   if not os.path.isfile(path_pandoc):




   if platform.system() == 'Darwin' or os.name == 'posix':

   args = ['which', 'pandoc']

   p = subprocess.Popen(

   args,

   stdin=subprocess.PIPE,

   stdout=subprocess.PIPE)




   path_pandoc =
str.rstrip(p.communicate(path_pandoc.encode('utf-8'))[0].decode('utf-8'))


The whole problematic code can be checked on
http://github.com/apaeffgen/panconvert
in source/converters/interface_pandoc.py



Checking your repo I found that get_path_pandoc, the function from which 
you took the code snippet above, will always return None if 
os.path.isfile(path_pandoc).


This is probably not what you are intending. Do you know if path_pandoc 
is maybe set to an existing file in your frozen code already so the 
whole 'which' or 'where' branch is never executed?


Best,
Wolfgang

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


Re: subprocess problem

2017-02-09 Thread Wolfgang Maier

On 09.02.2017 01:56, Andreas Paeffgen wrote:

The Problem with the subprocess code is: Using the sourcecode
functioning as normal.
The frozen app with cx_freeze on every platform just returns an empty
result

Here is the code in short:
def get_path_pandoc():




   settings = QSettings('Pandoc', 'PanConvert')

   path_pandoc = settings.value('path_pandoc','')




   if not os.path.isfile(path_pandoc):




   if platform.system() == 'Darwin' or os.name == 'posix':

   args = ['which', 'pandoc']

   p = subprocess.Popen(

   args,

   stdin=subprocess.PIPE,

   stdout=subprocess.PIPE)




   path_pandoc =
str.rstrip(p.communicate(path_pandoc.encode('utf-8'))[0].decode('utf-8'))


The whole problematic code can be checked on
http://github.com/apaeffgen/panconvert
in source/converters/interface_pandoc.py



Checking your repo I found that get_path_pandoc, the function from which 
you took the code snippet above, will always return None if 
os.path.isfile(path_pandoc).


This is probably not what you are intending. Do you know if path_pandoc 
is maybe set to an existing file in your frozen code already so the 
whole 'which' or 'where' branch is never executed?


Best,
Wolfgang

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


Re: Rename file without overwriting existing files

2017-01-30 Thread Wolfgang Maier

On 01/30/2017 03:49 AM, Steve D'Aprano wrote:

This code contains a Time Of Check to Time Of Use bug:

if os.path.exists(destination)
raise ValueError('destination already exists')
os.rename(oldname, destination)


In the microsecond between checking for the existence of the destination and
actually doing the rename, it is possible that another process may create
the destination, resulting in data loss.

Apart from keeping my fingers crossed, how should I fix this TOCTOU bug?



There is a rather extensive discussion of this problem (with no good 
cross-platform solution if I remember correctly):


https://mail.python.org/pipermail/python-ideas/2011-August/011131.html

which is related to http://bugs.python.org/issue12741

Wolfgang

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


Re: Search a sequence for its minimum and stop as soon as the lowest possible value is found

2017-01-06 Thread Wolfgang Maier

On 1/6/2017 15:04, Peter Otten wrote:

Example: you are looking for the minimum absolute value in a series of
integers. As soon as you encounter the first 0 it's unnecessary extra work
to check the remaining values, but the builtin min() will continue.

The solution is a minimum function that allows the user to specify a stop
value:


from itertools import count, chain
stopmin(chain(reversed(range(10)), count()), key=abs, stop=0)

0

How would you implement stopmin()?



How about:

def stopmin (iterable, key, stop):
def take_until ():
for e in iterable:
yield e
if key(e) <= stop:
break
return min(take_until(), key=key)

?

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


Re: is modulefinder.ModuleFinder working at all?

2016-11-10 Thread Wolfgang Maier

On 10.11.2016 01:02, Steve D'Aprano wrote:

On Thu, 10 Nov 2016 08:08 am, Wolfgang Maier wrote:


Hi,

I just used the stdlib's modulefinder.ModuleFinder (intended to find
modules used by a script) for the first time in my life and it just
doesn't seem to work like documented at all.
Not sure what is going on, but if I try the usage example from
https://docs.python.org/3/library/modulefinder.html
it's reporting every single module from the stdlib whether imported or
not!


I see what you mean, but it's not quite *every* module. After I run the
example from the docs, I get 197 modules, and here's at least two that
aren't included:

py> len(finder.modules)
197
py> 'statistics' in finder.modules
False
py> 'cmath' in finder.modules
False


Curiously, it includes modules that aren't cached in sys.modules:

py> len(finder.modules.keys() - sys.modules.keys())
107


So I'm not sure how that's possible.

According to the example module, it imports re and itertools. Both of those
have already been imported, and so will be cached in sys.modules, as will
all their dependencies. So I don't see how it is possible that ModuleFinder
can find dependencies that aren't cached.

Theoretically, of course some dependency might import a bunch of modules,
then delete them from sys.modules. If it were only one or two, I'd believe
that. But not 107 of them.

After running the module finder on the sample file, I ran the report()
method to get a nicer display of the imported modules:

py> finder = ModuleFinder()
py> finder.run_script('/tmp/bacon.py')
py> finder.report()

  Name  File
    
m __future__/usr/local/lib/python3.5/__future__.py
m __main__  /tmp/bacon.py
m _ast
m _bootlocale   /usr/local/lib/python3.5/_bootlocale.py
m _bz2  
/usr/local/lib/python3.5/lib-dynload/_bz2.cpython-35m-i386-linux-gnu.so
[...]


which shows the unittest package being loaded, which is pretty dubious.


On the other hand, here's a simpler example which seems to work fine:


py> with open('/tmp/do_little.py', 'w') as f:
... f.write('import math\n')
...
12
py> finder = ModuleFinder()
py> finder.run_script('/tmp/do_little.py')
py> finder.report()

  Name  File
    
m __main__  /tmp/do_little.py
m math  
/usr/local/lib/python3.5/lib-dynload/math.cpython-35m-i386-linux-gnu.so


So I'm not really sure what's going on.



Thanks for the detailed analysis.
You are right that it seems to work with certain imports. I verified 
your example with import math and found a few additional examples.


Things seem to work with imports of any of the following (alone or in 
combination):

io, itertools, math, sys

OTOH, I doubt that it reports correctly with:
os, heapq, operator, re

Personally, I fail to see a pattern here, but maybe somebody else can 
explain that behaviour.
I'd really like to report this to the bug tracker, but at the moment I'm 
not sure as what exactly. It seems that at least the documentation is 
incorrect since the usage example there is not working.


Best,
Wolfgang

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


Re: is modulefinder.ModuleFinder working at all?

2016-11-09 Thread Wolfgang Maier

On 09.11.2016 22:48, Skip Montanaro wrote:

I've not used it before, but I suspect it's meant to be used in
"freeze" type environments. In that situation, you really do want
everything reachable, whether the script imported it or not.


Hmm, but that's exactly the problem. It *is* supposed to report only 
what's imported and *not* everything that's available. At least that's 
how I understand the docs.



It doesn't take much to wind up importing much of the stdlib either. Try:

python -m modulefinder -m /path/to/os.py

This is from Python 2.7, YMMV slightly in Py3.



Yeah, I have tried this as well (with other stdlib modules), but you 
shouldn't wind up things with the example bacon.py from the docs.


Best,
Wolfgang

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


is modulefinder.ModuleFinder working at all?

2016-11-09 Thread Wolfgang Maier

Hi,

I just used the stdlib's modulefinder.ModuleFinder (intended to find 
modules used by a script) for the first time in my life and it just 
doesn't seem to work like documented at all.

Not sure what is going on, but if I try the usage example from
https://docs.python.org/3/library/modulefinder.html
it's reporting every single module from the stdlib whether imported or 
not! I tried with Python3.5, 3.4, 3.3, 3.2 and 2.7, but no success.

Has anybody here used this successfully and, if so, how?

Thanks for any help,
Wolfgang

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


Re: difference with parenthese

2016-10-17 Thread Wolfgang Maier

On 17.10.2016 16:45, chenyong20...@gmail.com wrote:

Hi Wolfgang,

thanks for your kind reply. I try to explain what I got from your reply:

for code1, when running "foo = outer()", since outer() is callable, function outer() is running and it 
returns an object, which referring to function inner(). When "foo" is running, it indicates it is referring 
to object inner(). When "foo()" is running, object inner() is called, so it prints "inside inner".

for code2, when running "foo = outer()", since outer() is callable, function outer() is running and returns 
results from function inner(), which prints "inside inner". so "foo" now is a string, which 
contains "inside inner". since this string isn't a function, foo() will make an error.

Do you think my understanding is right? thanks.


regards
skyworld chen



Not quite. Your understanding of code 1 is correct.
In your example code 2, however:

> code 2---
> >>> def outer():
> ...   def inner():
> ... print 'inside inner'
> ...   return inner()
> ...
> >>> foo = outer()
> inside inner
> >>> foo
> >>> foo()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'NoneType' object is not callable

calling outer returns the result of inner, as you are saying, but that 
result is *not* the string 'inside inner', but None (implicitly 
returned). As I explained before, the printed string is a side-effect of 
the function inner, but it is *not* what that function returns.


So:

foo = outer()

*prints* the string 'inside inner', but sets foo to refer to None. 
That's why the following TypeError mentions NoneType.


Best,
Wolfgang

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


Re: difference with parenthese

2016-10-17 Thread Wolfgang Maier

On 17.10.2016 10:52, chenyong20...@gmail.com wrote:

Hi,

i'm confused by a piece of code with parenthese as this:

code 1--

def outer():

...   def inner():
... print 'inside inner'
...   return inner
...

foo = outer()
foo



foo()

inside inner



code 2---

def outer():

...   def inner():
... print 'inside inner'
...   return inner()
...

foo = outer()

inside inner

foo
foo()

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'NoneType' object is not callable


the difference between these two piece of code is that the code 2 has a "()" when 
"return inner".

My questions are:
(1) what is the function difference between these two pieces of code? what does "return 
inner()" and "return inner" mean?
(2) when foo = outer() is run, why output is defferent for two pieces of code?

thanks



I suggest you look at a simpler example first:

def func():
print('inside func')

func()
a = func
b = func()

print(a)
print(b)

and see what that gives you.
There are two things you need to know here:

- functions are callable objects and the syntax to call them (i.e., to 
have them executed) is to append parentheses to their name; without 
parentheses you are only referring to the object, but you are *not* 
calling it


- functions without an explicit return still return something and that 
something is the NoneType object None. So the function above has the 
side-effect of printing inside func, but it also returns None and these 
are two totally different things


Once you have understood this you can try to go back and study your 
original more complicated example.


Best,
Wolfgang

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


Re: Appending to a list, which is value of a dictionary

2016-10-15 Thread Wolfgang Maier

On 15.10.2016 18:16, Steve D'Aprano wrote:

# Python 3 only: use a dict comprehension
py> d = {x:[] for x in (1, 2, 3)}
py> d
{1: [], 2: [], 3: []}


dict (and set) comprehensions got backported so this works just as well 
in Python 2.7


Wolfgang

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


Re: cmd prompt does not recognizes python command on Windows 7

2016-08-10 Thread Wolfgang Maier
Try py instead of python. That invokes a thing called the python 
launcher (see 
https://docs.python.org/3/using/windows.html#python-launcher-for-windows 
for more details).


Best,
Wolfgang


On 10.08.2016 06:46, sh.aja...@gmail.com wrote:

Hi Everyone

i have installed python 3.5 , but the python command is not recognized

C:\Users\sharmaaj>python
'python' is not recognized as an internal or external command,
operable program or batch file.

what should i do to run python commands.

thanks everyone for reading my post.

From Ajay



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


Re: from a module return a class

2016-03-19 Thread Wolfgang Maier

On 18.03.2016 16:08, John Gordon wrote:

In  kevind0...@gmail.com 
writes:


As requested , full code for promptUser_PWord




So promptUser_PWord is a module?  Well, I'm confused.  You gave us this
bit of code:

 user_pword = promptUser_PWord()

But that can't work if promptUser_PWord is a module; modules aren't
callable.  promptUser_PWord() has to be a function or a class.



Yes, but I guess the OP's program will run into the SyntaxError when 
trying to import the module, i.e., before it ever encounters the 
TypeError: 'module' object is not callable.


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


Re: from a module return a class

2016-03-18 Thread Wolfgang Maier

On 3/18/2016 20:19, kevind0...@gmail.com wrote:


so what I get from the various postings is promptUser_PWord must be
converted to a class.  True?



A simple function would also do. Just make sure that the return is 
inside a callable block.


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


Re: non printable (moving away from Perl)

2016-03-11 Thread Wolfgang Maier

On 11.03.2016 15:23, Fillmore wrote:

On 03/11/2016 07:13 AM, Wolfgang Maier wrote:

One lesson for Perl regex users is that in Python many things can be
solved without regexes.
How about defining:

printable = {chr(n) for n in range(32, 127)}

then using:

if (set(my_string) - set(printable)):
 break


seems computationally heavy. I have a file with about 70k lines, of
which only 20 contain "funny" chars.



Not sure what you call computationally heavy. I just test-parsed a 30 MB 
file (28k lines) with:


with open(my_file) as i:
for line in i:
if set(line) - printable:
continue

and it finished in less than a second.

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


Re: non printable (moving away from Perl)

2016-03-11 Thread Wolfgang Maier

On 11.03.2016 13:13, Wolfgang Maier wrote:

One lesson for Perl regex users is that in Python many things can be
solved without regexes. How about defining:

printable = {chr(n) for n in range(32, 127)}

then using:

if (set(my_string) - set(printable)):
 break



Err, I meant:

if (set(my_string) - printable):
break

of course. No need to attempt another set conversion.

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


Re: non printable (moving away from Perl)

2016-03-11 Thread Wolfgang Maier
One lesson for Perl regex users is that in Python many things can be 
solved without regexes. How about defining:


printable = {chr(n) for n in range(32, 127)}

then using:

if (set(my_string) - set(printable)):
break



On 11.03.2016 01:07, Fillmore wrote:


Here's another handy Perl regex which I am not sure how to translate to
Python.

I use it to avoid processing lines that contain funny chars...

if ($string =~ /[^[:print:]]/) {next OUTER;}

:)



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


Re: Continuing indentation

2016-03-02 Thread Wolfgang Maier

On 3/2/2016 21:43, Skip Montanaro wrote:

Running flake8 over some code which has if statements with multiple
conditions like this:

 if (some_condition and
 some_other_condition and
 some_final_condition):
 play_bingo()

the tool complains that the indentation of the conditions is the same
as the next block.  In this particular case, the overall conditions
are too long to string together on a single line. I tried placing a
second space after the if keyword:

 if  (some_condition and
  some_other_condition and
  some_final_condition):
 play_bingo()

which solves the matching indentation problem, but creates a multiple
spaces after keyword problem.  My guess is that adding a space after
the open paren would provoke a message as well.

I use GNU Emacs as my text editor, and its python mode.  I'm pretty
happy with everything (been using it in its current state for several
years).  Aside from manually or configure-ologically suppressing E129,
is there a better way to break lines I'm missing which will make
flake8 happy?



I don't know about flake8, but pep8 says all these are acceptable though 
the first version (like yours) has the readability problem flake8 
complains about:


# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()

Maybe version 2 would make the tool happy?


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


Re: subprocess startup error

2016-02-26 Thread Wolfgang Maier

On 26.02.2016 15:57, Emile van Sebille wrote:

On 2/26/2016 6:49 AM, Oscar Benjamin wrote:

On 26 February 2016 at 13:30, Peter Otten <__pete...@web.de> wrote:

Shweta Dinnimani wrote:

i saved my file as string.py since than i'm facing this error


Rename that file to something that does not clash with the module
names in
the standard library, mystring.py for example, and IDLE should work
again.


It's ridiculous that it's this easy to accidentally crash IDLE and the
Python shell.


I don't think there's a way to protect against it -- how could you work
on string.py otherwise?



Emitting a warning message in such situations is being discussed in 
http://bugs.python.org/issue23809 though it is not a very lively discussion.


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


Re: How to read from a file to an arbitrary delimiter efficiently?

2016-02-24 Thread Wolfgang Maier

On 25.02.2016 07:50, Steven D'Aprano wrote:

I have a need to read to an arbitrary delimiter, which might be any of a
(small) set of characters. For the sake of the exercise, lets say it is
either ! or ? (for example).



You are not alone with your need.

http://bugs.python.org/issue1152248 discusses the problem and has some 
code snippets that you may be interested in. While there is no trivial 
solution there are certainly faster ways than your first attempt.


Wolfgang

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


Re: Finding in which class an object's method comes from

2016-02-04 Thread Wolfgang Maier

On 04.02.2016 10:00, Chris Angelico wrote:

On Thu, Feb 4, 2016 at 7:54 PM, ast  wrote:

It is strange but I dont have the same result that you:
(Python 3.4)


class A:


def a(self):pass


class B(A):

def b(self):pass


class C(B):

def c(self):pass


obj = C()



obj.a


>


Curious. It appears to have changed between 3.4 and 3.5; my original
copy/paste was from 3.6.



I think http://bugs.python.org/issue21389 causes the difference. I think 
the change was introduced with Python3.5.



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


Re: [STORY-TIME] THE BDFL AND HIS PYTHON PETTING ZOO

2016-02-03 Thread Wolfgang Maier

On 03.02.2016 04:26, Rick Johnson wrote:



  [STORY-TIME] THE BDFL AND HIS PYTHON PETTING ZOO


A long, long time a ago, in a sleepy little Scandinavian
village, somewhere outside of Stockholm, a wee little boy


... long long story

Just one question: do you really think the Netherlands are a part of 
Scandinavia and that Stockholm is their capital?


If so maybe you'll find this comforting:

https://www.washingtonpost.com/news/monkey-cage/wp/2014/04/07/the-less-americans-know-about-ukraines-location-the-more-they-want-u-s-to-intervene/

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


Re: python-2.7.3 vs python-3.2.3

2016-01-26 Thread Wolfgang Maier

On 26.01.2016 15:34, Matt Wheeler wrote:


The only slight issue you might encounter is that Python 3.2 is quite
old now and actually not as well supported as Python 2.7 (many
projects support Python 2.7 or 3.3+ only). Best to just try out your
script and find out though.



Right. For example, pip dropped support for Python 3.2 last week. So if 
you need to install it make sure you do it via:


curl https://bootstrap.pypa.io/3.2/get-pip.py | python3.2

see: https://github.com/pypa/get-pip

then ignore the upgrade advice because pip versions 8.0.0 and above will 
not work for you.


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


Re: python-2.7.3 vs python-3.2.3

2016-01-26 Thread Wolfgang Maier

I have used 2.7 and 3.2 side-by-side for two years or so on Ubuntu 12.04.
Never encountered any problem except for a few times that I accidentally 
tried to run something with python when I should have used python3.


Cheers,
Wolfgang


On 26.01.2016 13:26, Gene Heskett wrote:

Greetings;

I have need of using a script written for python3, but the default python
on wheezy is 2.7.3.

I see in the wheezy repos that 3.2.3-6 is available.

Can/will they co-exist peacefully?

Thank you.

Cheers, Gene Heskett



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


Re: Installing on linux - missing devel packages

2016-01-21 Thread Wolfgang Maier

On 1/21/2016 8:27, Chris Angelico wrote:


This is a Linux packaging question, more than a Python one. On Debian
systems, the way to do that is "apt-get build-dep python3"; check your
own package manager for an equivalent - it'll probably be called
builddep or similar.



Yes, you'd run:

dnf builddep python3

The list of packages this returns (30 to install freshly on Fedora23) is 
impressive though so I'm not sure you really need all of these.



---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus


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


Re: How to simulate C style integer division?

2016-01-21 Thread Wolfgang Maier

On 1/21/2016 15:00, Jussi Piitulainen wrote:

Steven D'Aprano writes:


So my guess is that the fastest, and certainly the most obvious, way
to get the same integer division behaviour as C99 would be:

def intdiv(a, b):
 # C99 style integer division with truncation towards zero.
 n = a//b
 if (a < 0) != (b < 0):
 n += 1
 return n


You should only increment if there is a (non-zero) remainder.



Right. Merging Steven's suggestion and fractions.Fraction.__trunc__ 
implementation I think the right answer may be:


def intdiv2(a,b):
# C99 style integer division with truncation towards zero.
if (a < 0) != (b < 0):
return -(-a // b)
else:
return a // b

Cheers,
Wolfgang


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus


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


Re: Powerful perl paradigm I don't find in python

2016-01-18 Thread Wolfgang Maier

On 1/18/2016 14:05, Charles T. Smith wrote:

On Fri, 15 Jan 2016 14:20:17 +0100, Wolfgang Maier wrote:


pattern = pattern_str.compile()
try:
  matches = pattern.findall(some_str, endpos=some_str.index(tail))
except ValueError:
  # do something if tail is not found
  pass


Oh!  I think that's it!


matches = findall (pattern, string)
for file in matches:
 use (file)

Totally cool!  Thank you.



Great if it helps you. Just beware that this simplified version is not 
exactly equivalent to your initial perl snippet:


Generally, findall will find ALL occurrences of pattern, not just 
adjacent ones.


Since your perl example would never terminate if something non-matching 
is interleaved with pattern matches I figured you never expect that case.


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus


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


Re: Powerful perl paradigm I don't find in python

2016-01-15 Thread Wolfgang Maier

On 15.01.2016 12:04, Charles T. Smith wrote:

On Fri, 15 Jan 2016 11:42:24 +0100, Wolfgang Maier wrote:


On 15.01.2016 10:43, Peter Otten wrote:

Charles T. Smith wrote:


while ($str != $tail) {
  $str ~= s/^(head-pattern)//;
  use ($1);
}






things = []
while some_str != tail:
  m = re.match(pattern_str, some_str)
  things.append(some_str[:m.end()])
  some_str = some_str[m.end():]

# do something with things



Okay, I guess it's not a lot more work to use the end() method to manually
cut out the found portion.

What the original snippet does is parse *and consume* a string - actually,
to avoid maintaining a cursor traverse the string.  The perl feature is that
substitute allows the found pattern to be replaced, but retains the group
after the expression is complete.

The end() method is actually such a cursor, but already set up for you
by the class, and then the slicing considerably simplifies its use.



I see. If consuming the string is not essential for you, but just a 
handy trick to avoid the cursor, you may prefer this (most likely 
faster) solution:


pattern = pattern_str.compile()
try:
matches = pattern.findall(some_str, endpos=some_str.index(tail))
except ValueError:
# do something if tail is not found
pass

Best,
Wolfgang


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


Re: Powerful perl paradigm I don't find in python

2016-01-15 Thread Wolfgang Maier

On 15.01.2016 10:43, Peter Otten wrote:

Charles T. Smith wrote:


while ($str != $tail) {
 $str ~= s/^(head-pattern)//;
 use ($1);
}


For those whose Perl's a little rusty: what does this do?
A self-contained example might also be useful...



Right, an explanation would certainly get you a lot more responses.

If I'm guessing correctly what the snippet is supposed to do (and, yes, 
my Perl definitely is rusty), isn't the Python equivalent of the regex 
part of your question fairly obvious if you're using the re module:


things = []
while some_str != tail:
m = re.match(pattern_str, some_str)
things.append(some_str[:m.end()])
some_str = some_str[m.end():]

# do something with things

I have no idea why you'd want to *import* all the things parsed out of 
some_str, but for this part you may look at importlib.import_module.


P.S.: the while loop above never ends if tail is not in some_str, but I 
guess your Perl snippet has the same problem?



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


Re: filter a list of strings

2015-12-03 Thread Wolfgang Maier

On 03.12.2015 10:27, c.bu...@posteo.jp wrote:
>
> I often saw constructions like this
>x for x in y if ...
> But I don't understand that combination of the Python keywords (for,
> in, if) I allready know. It is to complex to imagine what there really
> happen.
>
> I understand this
>for x in y:
>  if ...
>
> But what is about the 'x' in front of all that?
>

The leading x states which value you want to put in the new list. This 
may seem obvious in the simple case, but quite often its not the 
original x-ses found in y that you want to store, but some 
transformation of it, e.g.:


[x**2 for x in y]

is equivalent to:

squares = []
for x in y:
squares.append(x**2)


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


Re: static variables

2015-12-01 Thread Wolfgang Maier

On 01.12.2015 09:26, Ulli Horlacher wrote:

Steven D'Aprano  wrote:


A better and more general test is:

if hasattr(a, 'x'): print('attribute of a')


Fine!

I have now:

def a(x=None):
   if not hasattr(a,'x'): a.x = 0
   a.x += 1
   print('%d:' % a.x,x)

This simply counts the calls of a()

But, when I rename the function I have to rename the attribute also.
Is it possible to refer the attribute automatically to its function?
Something like:

def a(x=None):
   if not hasattr(_function_,'x'): _function_.x = 0
   _function_.x += 1
   print('%d:' % _function_.x,x)





I'm wondering whether you have a good reason to stick with a function. 
What you are trying to achieve seems to be easier and cleaner to 
implement as a class:


class Counter (object):
def __init__ (self, start_value=0):
self.x = start_value

def __call__ (self):
self.x += 1

1) solves the renaming problem
2) allows you to have several counters around:

counter1 = Counter()
counter2 = Counter()
counter3 = Counter(35)
counter1()
counter2()
counter1()
print (counter1.x, counter2.x, counter3.x)

Cheers,
Wolfgang


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


Re: Unbuffered stderr in Python 3

2015-11-04 Thread Wolfgang Maier

On 04.11.2015 11:43, Wolfgang Maier wrote:

On 04.11.2015 11:24, Steven D'Aprano wrote:

On Wed, 4 Nov 2015 07:19 pm, Wolfgang Maier wrote:


On 04.11.2015 04:18, Steven D'Aprano wrote:


This is one of the offending line from our code base:

print('<4>Suspicious answer "{}"!'.format(answer), file=sys.stderr)

So that ought to be terminated by a newline. And yet, the stderr output
doesn't show up until the program exits.



For me, that prints immediately. Where is your output going? Console,
file, ...?


Going to stderr, like the whole thread is about :-)



I see :), but seriously, what I meant was: is it going to the console
directly or is your code base redirecting sys.stderr to another buffered
object first?



Standard I/O streams are line-buffered only if interactive (i.e., 
connected to a console), but block-buffered otherwise.

What does sys.stderr.isatty() return?


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


Re: Unbuffered stderr in Python 3

2015-11-04 Thread Wolfgang Maier

On 04.11.2015 11:24, Steven D'Aprano wrote:

On Wed, 4 Nov 2015 07:19 pm, Wolfgang Maier wrote:


On 04.11.2015 04:18, Steven D'Aprano wrote:


This is one of the offending line from our code base:

print('<4>Suspicious answer "{}"!'.format(answer), file=sys.stderr)

So that ought to be terminated by a newline. And yet, the stderr output
doesn't show up until the program exits.



For me, that prints immediately. Where is your output going? Console,
file, ...?


Going to stderr, like the whole thread is about :-)



I see :), but seriously, what I meant was: is it going to the console 
directly or is your code base redirecting sys.stderr to another buffered 
object first?




The output does eventually show up written to the console, but only after
Python exits.





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


Re: Unbuffered stderr in Python 3

2015-11-04 Thread Wolfgang Maier

On 04.11.2015 04:18, Steven D'Aprano wrote:

On Wednesday 04 November 2015 09:25, Terry Reedy wrote:


On 11/3/2015 10:42 AM, Chris Angelico wrote:

On Wed, Nov 4, 2015 at 2:00 AM, Random832  wrote:

Nobody  writes:


It's probably related to the fact that std{in,out,err} are Unicode
streams.


There's no fundamental reason a Unicode stream should have to be line
buffered. If it's "related", it's only in that an oversight was made in
the course of making that change.


The current behavior is not an 'oversight'.  I was considered, decided,
and revisited in https://bugs.python.org/issue13601.  Guido:
"Line-buffering should be good enough since in practice errors messages
are always terminated by a newline."  If not, print(part_line,
file=sys.stderr, flush=True) works for the unusual case.


This is one of the offending line from our code base:

print('<4>Suspicious answer "{}"!'.format(answer), file=sys.stderr)

So that ought to be terminated by a newline. And yet, the stderr output
doesn't show up until the program exits.



For me, that prints immediately. Where is your output going? Console, 
file, ...?


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


Re: venv issues

2015-11-03 Thread Wolfgang Maier

On 03.11.2015 11:32, Nicholas Cole wrote:

I'm using python3.5 (installed from binaries) on the latest OS X.

I have a curious issue with virtual environments on this machine (but
not on my other machine).


$ python3.5 -m venv testenv
$ source testenv/bin/activate
(testenv)$ python -m pip
/private/tmp/testenv/bin/python: No module named pip
$

Logging in as a different user and creating a venv works perfectly, so
it's clearly a config issue somewhere, but I've tried removing
~/.bashrc and ~/.bash_profile and that doesn't help.

The sys.path for that venv is: ['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/private/tmp/testenv/lib/python3.5/site-packages']



Is there something special about your /private/tmp folder? In other 
words, do things work if you create a venv in a different place.
If you go to /private/tmp/testenv/lib/python3.5/site-packages is there a 
pip folder and what are its permission settings?


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


Re: Unbuffered stderr in Python 3

2015-11-02 Thread Wolfgang Maier

On 02.11.2015 11:48, Wolfgang Maier wrote:


Since Python3.3, the print function has a flush keyword argument that
accepts a boolean and lets you do just this. Rewrite your example as:

import sys, time

def test():
# Simulate a slow calculation that prints status and/or error
# messages to stderr.
for i in range(10):
_print(i, file=sys.stderr, end="", flush=True)
time.sleep(2)
print("", file=sys.stderr)

and it should do what you want.


sorry for this mess (copy pasted from the wrong source).
The code should be:

def test():
# Simulate a slow calculation that prints status and/or error
# messages to stderr.
for i in range(10):
print(i, file=sys.stderr, end="", flush=True)
time.sleep(2)
print("", file=sys.stderr)


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


Re: Unbuffered stderr in Python 3

2015-11-02 Thread Wolfgang Maier

On 02.11.2015 08:52, Steven D'Aprano wrote:

In Python 2, stderr is unbuffered.

In most other environments (the shell, C...) stderr is unbuffered.

It is usually considered a bad, bad thing for stderr to be buffered. What
happens if your application is killed before the buffer fills up? The errors
in the buffer will be lost.

So how come Python 3 has line buffered stderr? And more importantly, how can
I turn buffering off?



I cannot comment on your first question, but unbuffered writing to 
sys.stderr is possible just like for any other buffered file object. You 
just call its flush method after writing.


Since Python3.3, the print function has a flush keyword argument that 
accepts a boolean and lets you do just this. Rewrite your example as:


import sys, time

def test():
# Simulate a slow calculation that prints status and/or error
# messages to stderr.
for i in range(10):
_print(i, file=sys.stderr, end="", flush=True)
time.sleep(2)
print("", file=sys.stderr)

and it should do what you want.


Before Python 3.3, if I needed an unbuffered print function, I used a 
wrapper to call flush for me, so instead of:




import sys, time

def test():
 # Simulate a slow calculation that prints status and/or error
 # messages to stderr.
 for i in range(10):
 print(i, file=sys.stderr, end="")
 time.sleep(2)
 print("", file=sys.stderr)



I'd use (and still do this if I need compatibility with 3.2):

import sys, time

def _print (*args, **kwargs):
   file = kwargs.get('file', sys.stdout)
   print(*args, **kwargs)
   file.flush()

def test():
# Simulate a slow calculation that prints status and/or error
# messages to stderr.
for i in range(10):
_print(i, file=sys.stderr, end="")
time.sleep(2)
print("", file=sys.stderr)

Best,
Wolfgang

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


Re: unsupported operand type(s) python v2.7

2015-10-20 Thread Wolfgang Maier

On 20.10.2015 10:44, ngangsia akumbo wrote:

def n():

34 * 2



def g():

4 + 2



Your n and g functions do not have an explicit return so, after doing 
their calculations and throwing the result away, they return None.



def ng():

return n() + g()


ng()


Traceback (most recent call last):
   File "", line 1, in 
 ng()
   File "", line 2, in ng
 return n() + g()
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'



The attempt in ng to add None to None then produce the exception you are 
seeing.



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


Re: python.org bugs

2015-09-28 Thread Wolfgang Maier

On 28.09.2015 09:30, Laura Creighton wrote:

If you just send them to webmas...@python.org they will get dealt with
(probably by me).

Laura



Does that apply to bugs on pypi, too?

You still cannot select Python 3.5 as the Python Version for wheels and 
other files uploaded to pypi over the web interface. I've reported this 
almost a week ago on the pypi issue tracker on bitbucket, but there is 
no answer yet.


Wolfgang

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


Re: PIP does not appear to handle diacritics correctly.

2015-09-09 Thread Wolfgang Maier

On 09.09.2015 21:59, Tim Golden wrote:


Well on my Win8.1 machine I created a local user with the name you give
and did a fresh install of the very latest Python 3.5rc. I installed
from the 32-bit web installer and the only variation from the defaults
was to add Python to the PATH (the last checkbox on the first page of
the wizard).

It all installed without issue and I was able to do "pip --version" from
a command prompt to see that it had installed pip 7.1.something.

Now this is on my standard dev machine, ie not a virgin VM, and it's 8.1
rather than Win7, but it's not clear why either of those would make a
difference.

The standard codepage for console processes appears to be 850.



It's been resolved a minute ago. See 
https://github.com/pypa/pip/issues/3087#issuecomment-139034217 for an 
explanation of why the latest rc does not have the bug.


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


Re: PIP does not appear to handle diacritics correctly.

2015-09-09 Thread Wolfgang Maier

On 09.09.2015 10:23, Chris Angelico wrote:

On Wed, Sep 9, 2015 at 5:59 PM, Laszlo Lebrun via Python-list
 wrote:

Whenever I start PIP, I get:
"Fatal error in launcher: Unable to create process using '"C:\Users
\BürgerGegenFluglärm\AppData\Local\Programs\Python\Python35-32
\python.exe"  "C:\Users\B³rgerGegenFluglõrm\AppData\Local\Programs\Python
\Python35-32\Scripts\pip.exe" '"

Where the correct path is "C:\Users\BürgerGegenFluglärm\AppData..."

The funny thing is that the message mentions the path twice, with
different wrong codings.
:-(




I may be wrong, but isn't the error message suggesting that this is a 
bug in the py launcher instead of in pip?
If I remember a post from a recent thread correctly, then pip.exe is 
just a script using the launcher.

If that's true, shouldn't the recommended:

python -m pip

be a workaround?

I might be wrong, but it's worth a try.
Best,
Wolfgang


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


Re: Setuptools: no module named 'html.entities'

2015-03-16 Thread Wolfgang Maier

On 03/16/2015 12:53 AM, Jason Friedman wrote:

Hello,

This is Python 3.3.2 on Linux.
I downloaded Setuptools
(https://pypi.python.org/packages/source/s/setuptools/setuptools-14.3.tar.gz),
exploded the tarball, and I get:

python setup.py build
Traceback (most recent call last):
   File "", line 1521, in
_find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
   File "setup.py", line 21, in 
 exec(init_file.read(), command_ns)
   File "", line 11, in 
   File "/home/spjsf/setuptools-14.3/setuptools/__init__.py", line 11,
in 
 from setuptools.extension import Extension
   File "/home/spjsf/setuptools-14.3/setuptools/extension.py", line 8,
in 
 from .dist import _get_unpatched
   File "/home/spjsf/setuptools-14.3/setuptools/dist.py", line 16, in

 from setuptools.depends import Require
   File "/home/spjsf/setuptools-14.3/setuptools/depends.py", line 6, in

 from setuptools import compat
   File "/home/spjsf/setuptools-14.3/setuptools/compat.py", line 44, in

 from html.entities import name2codepoint
ImportError: No module named 'html.entities'; html is not a package




Not sure, but maybe you have a html.py somewhere in your module search 
path taking precedence over the stdlib html package ?
Putting a dummy html.py file into the extracted setuptools folder, at 
least, lets me reproduce your exact error.


What does

python -c "import html; print(html)"

tell you ?

Best,
Wolfgang

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


when may sys.executable be empty

2015-03-11 Thread Wolfgang Maier

From the documentation of sys.executable:

A string giving the absolute path of the executable binary for the 
Python interpreter, on systems where this makes sense. If Python is 
unable to retrieve the real path to its executable, sys.executable will 
be an empty string or None.


So on which systems does it not make sense ?

Thanks for any help,
Wolfgang

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


Re: Letter class in re

2015-03-09 Thread Wolfgang Maier

On 03/09/2015 03:04 PM, Wolfgang Maier wrote:

On 03/09/2015 02:33 PM, Albert-Jan Roskam wrote:


On Mon, 3/9/15, Tim Chase  wrote:

"[^\d\W_]+" means something like "one or more (+) of 'not (a digit, a
non-word, an underscore)'.



interesting (using Python3.4 and
U+2188 ROMAN NUMERAL ONE HUNDRED THOUSAND ↈ):

 >>> re.search('[^\d\W_]+', '\u2188', re.I | re.U)
<_sre.SRE_Match object; span=(0, 1), match='ↈ'>

ↈ and at least some other Nl (letter numbers) category characters seem
to be part of \w (not part of \W).

Would that be considered a bug ?



Sorry for the potential confusion: I meant in the pattern search above 
(not in the definition of \w or \W).


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


Re: Letter class in re

2015-03-09 Thread Wolfgang Maier

On 03/09/2015 02:33 PM, Albert-Jan Roskam wrote:


On Mon, 3/9/15, Tim Chase  wrote:

"[^\d\W_]+" means something like "one or more (+) of 'not (a digit, a non-word, 
an underscore)'.



interesting (using Python3.4 and
U+2188  ROMAN NUMERAL ONE HUNDRED THOUSAND  ↈ):

>>> re.search('[^\d\W_]+', '\u2188', re.I | re.U)
<_sre.SRE_Match object; span=(0, 1), match='ↈ'>

ↈ and at least some other Nl (letter numbers) category characters seem 
to be part of \w (not part of \W).


Would that be considered a bug ?

Wolfgang

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


Re: Letter class in re

2015-03-09 Thread Wolfgang Maier

On 03/09/2015 01:26 PM, Antoon Pardon wrote:

Op 09-03-15 om 12:17 schreef Tim Chase:

On 2015-03-09 11:37, Wolfgang Maier wrote:

On 03/09/2015 11:23 AM, Antoon Pardon wrote:

Does anyone know what regular expression to use for a sequence of
letters? There is a class for alphanumerics but I can't find one
for just letters, which I find odd.

how about [a-zA-Z] ?

That breaks if you have Unicode letters.  While ugly, since "\w" is
composed of "letters, numbers, and underscores", you can assert that
the "\w" you find is not a number or underscore by using

   (?:(?!_|\d)\w)


So if I understand correctly the following should be a regular expression for
a python3 identifier.

   (?:(?!_|\d)\w)\w+



No, that is not it. For one thing, a leading underscore is fine in 
identifier names. That is easy to fix in your expression though.
Another thing are the Other_ID_Start and Other_ID_Continue categories 
defined in http://www.unicode.org/Public/6.3.0/ucd/PropList.txt, e.g.,


>>> '\u212E'
'℮'
>>> ℮ = 10
>>> ℮
10

though ℮ is not included in \w.


It seems odd that one should need such an ugly expression for something that is
used rather frequently for parsing computer languages and the like.



There is str.isidentifier, which returns True if something is a valid 
identifier name:


>>> '℮'.isidentifier()
True



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


Re: Letter class in re

2015-03-09 Thread Wolfgang Maier

On 03/09/2015 11:23 AM, Antoon Pardon wrote:

I am using PLY for a parsing task which uses re for the lexical
analysis. Does anyone
know what regular expression to use for a sequence of letters? There is
a class for alphanumerics but I can't find one for just letters, which I
find odd.

I am using python 3.4



how about [a-zA-Z] ?

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


Re: Speeding up permutations generation

2015-03-06 Thread Wolfgang Maier

On 03/06/2015 05:14 PM, Gene Heskett wrote:



On Friday 06 March 2015 06:22:34 Dave Angel wrote:


30414093201713378043612608166064768844377641568960512L


What utility output that as an L ?



One called the python interactive interpreter used by many people on 
this list (though it is a shame they haven't switched to python3 yet) :)


Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> from math import factorial
>>> factorial(50)

30414093201713378043612608166064768844377641568960512L

Wolfgang


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


Re: Speeding up permutations generation

2015-03-06 Thread Wolfgang Maier

On 03/06/2015 09:34 AM, Mark Lawrence wrote:

On 06/03/2015 06:44, Abhiram R wrote:

Hi all,
Is there a way to generate permutations of large arrays of sizes say,in
the hundreds, faster than in the time itertools.permutations() can
return?

​-Abhiram.R
/~Never give up/



If there is I'd guess that you'd use numpy http://www.numpy.org/.  The
more mathematically minded may well be able to give better answers.



Well, numpy would be faster if you could call into it once and retrieve 
all permutations as an array. This would allow you to do all 
calculations in C, while itertools.permutations has to jump back and 
forth between C and Pyhon code.


However, 50! is still ~ 3*10^64. So where would you want to store the 
array of these many permutations ?


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


Re: rst and pypandoc

2015-03-02 Thread Wolfgang Maier

On 03/02/2015 08:59 AM, alb wrote:

Hi everyone,

I'm writing a document in restructured text and I'd like to convert it
to latex for printing. To accomplish this I've used semi-successfully
pandoc and the wrapper pypandoc.

My biggest issue is with figures and references to them. We've our macro
to allocate figures so I'm forced to bypass the rst directive /..
figure/, moreover I haven't happened to find how you can reference to a
figure in the rst docs.

For all the above reasons I'm writing snippets of pure latex in my rst
doc, but I'm having issues with the escape characters:

i = '\ref{fig:abc}'
print pypandoc.convert(i, 'latex', format='rst')
ef\{fig:abc\}

because of the \r that is interpreted by python as special character.

If I try to escape with '\' I don't seem to find a way out...



what exactly do you mean by not finding a way out ? Escaping with a '\' 
should work. Of course, that backslash will print for clarity, but I 
suppose you want to write this to a file ? What happens if you do so ?


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


Re: PyPI, reStructuredText and readthedocs problems

2015-03-02 Thread Wolfgang Maier

On 03/02/2015 11:33 AM, INADA Naoki wrote:

PyPI parses your README strictly.

$ rst2html.py --strict README.rst
README.rst:700: (INFO/1) Duplicate implicit target name: "fingerprint".
Exiting due to level-1 (INFO) system message.

But I don't know how to avoid this error when converting from markdown.



The other occurence of a title Fingerprint is at line 436. I guess you 
will have to change one of the two titles (maybe Fingerprints ?) to make 
things work.



On Mon, Mar 2, 2015 at 6:35 PM Leonardo Giordani
mailto:giordani.leona...@gmail.com>> wrote:

Hi all,

Some time ago I open sourced a package named postage
(https://pypi.python.org/pypi/postage/).

I am experiencing issues with documentation. The project is hosted
on GitHub (https://github.com/lgiordani/postage), where the
README.md is perfectly rendered. My issues are:

1. I use pandoc to convert README.md to README.rst. This latter is
rendered by GitHUb as well, but when I upload the package to PyPI I
get a messy result (look at the package page).

2. When I import the project into readthedocs.org
 the build fails with no output. This is the
only information I get

- 8< -

Build for postage

Built: Feb. 27, 2015. 10:41 a.m.

State: Finished

Outcome: Failed (Status Code: 0)

Version: latest

Type: html

Build Standard Output

- 8< -

May someone help me figuring out what's wrong in my code?
Thanks!

Leo



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


Re: Python path on windows

2015-02-20 Thread Wolfgang Maier

On 20.02.2015 19:25, Ian Kelly wrote:

On Fri, Feb 20, 2015 at 8:16 AM, loial  wrote:

On Friday, February 20, 2015 at 2:54:26 PM UTC, Ian wrote:

On Feb 20, 2015 7:46 AM, "loial"  wrote:






On Linux we use



#!/usr/bin/env python







At the start of scripts to ensure that the python executable used is the one 
defined in the PATH variable, rather than hardcoding a path to the python 
executable.







What is the equivalent functionality in Windows?


https://docs.python.org/3/using/windows.html#launcher

Note that while the launcher can be used with any version of Python, it is only 
packaged with 3.3+.


Vesrion is 2.6


You can install multiple versions of Python on the same system without
conflict. If you install Python 3.4 also, then you'll have the
launcher. I don't know if there's an easy way to install just the
launcher.


https://bitbucket.org/vinay.sajip/pylauncher/overview

has the standalone launcher (msi installers are in the downloads section).


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


Re: pypandoc and restructured text

2015-02-20 Thread Wolfgang Maier

On 20.02.2015 15:59, alb wrote:


My installation is the following:
pandoc 1.5.1.1
python 2.6.6
debian squeeze

Any idea why? Should I upgrade somehow beyond what the debian repository
delivers?



I have pandoc 1.12.2.1 and it recognizes the figure directive just fine 
(tested with html output so I cannot say anything about LaTeX).


I've found an old forum post from 2011:

https://groups.google.com/forum/#!topic/pandoc-discuss/OmGYDycaMjs

confirming that the figure directive was not supported at that time.
So, yes, I think upgrading pandoc could help.

Best,
Wolfgang

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


Re: what would be the regular expression for null byte present in a string

2015-01-14 Thread Wolfgang Maier

On 01/13/2015 02:40 PM, Shambhu Rajak wrote:

I have a string that I get as an output of a command as:

'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00*10232ae8944a*\x02\x00\x00\x00\x00\x00\x00\x00\n'

I want to fetch ‘*10232ae8944a*’ from the above string.

I want to find a re pattern that could replace all the \x01..\x0z to be
replace by empty string ‘’,  so that I can get the desired portion of string

Can anyone help me with a working regex for it.

Thanks,

Shambhu



If the characters you need to keep always form a contiguous stretch, you 
can also use:


exclude = ''.join(chr(n) for n in range(32))
s_in.strip(exclude)

Wolfgang

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


Re: what would be the regular expression for null byte present in a string

2015-01-14 Thread Wolfgang Maier

On 01/13/2015 02:40 PM, Shambhu Rajak wrote:

I have a string that I get as an output of a command as:

'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00\x00\x00\x00\x00\x00\x00\n'

I want to fetch ‘*10232ae8944a*’ from the above string.

I want to find a re pattern that could replace all the \x01..\x0z to be
replace by empty string ‘’,  so that I can get the desired portion of string

Can anyone help me with a working regex for it.



Sorry, no regex either, but depending on what exact behavior you need 
str.isprintable() or even str.isalnum() could be for you:


e.g.

s_in = 
'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00\x00\x00\x00\x00\x00\x00\n'

s_out = ''.join(c for c in s_in if c.isprintable())

Wolfgang

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


Re: Why does argparse return None instead of [] if an append action isn't used?

2015-01-09 Thread Wolfgang Maier

On 01/09/2015 03:44 PM, Adam Funk wrote:

I noticed in use that if an option with the 'append' action isn't
used, argparse assigns None to it rather than an empty list, &
confirmed this interactively:

#v+

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='append')

_AppendAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, 
default=None, type=None, choices=None, help=None, metavar=None)

parser.add_argument('--bar', action='append')

_AppendAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, 
default=None, type=None, choices=None, help=None, metavar=None)

parser.parse_args('--foo 1 --foo 2'.split())

Namespace(bar=None, foo=['1', '2'])
#v-



Isn't that the exact behaviour documented here:

https://docs.python.org/3/library/argparse.html#default

where it says that the default for the default argument is None ?

I think Skip is right: you should be able to just add

default = []

to your arguments in the add_argument call.

Wolfgang

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


Re: Style question: Importing modules from packages - 'from' vs 'as'

2014-12-04 Thread Wolfgang Maier

On 04.12.2014 22:30, Chris Angelico wrote:

On Fri, Dec 5, 2014 at 7:56 AM, Wolfgang Maier
 wrote:

On 04.12.2014 19:05, Chris Angelico wrote:



With os.path it definitely is. With the actual code in question, it's
a Python 2.7 project that mostly uses relative imports - inside
package.module1 is "import module2" etc - and I was writing an
external script that calls on one of the modules.



What ? I'm usually thinking Python 3 not 2 and I'm never sure which Python
2.x has backported which feature of 3, but I thought implicit relative
imports like you seem to describe are not working in 2.7 ?


Hmm, I'm not sure, but certainly it does seem to work that way. Typing
"import foo" from inside a package will import foo.py from the package
directory. I haven't dug into the details of _why_, and if ever the
project shifts to Python 3 (which I would like it to), we might have
to change some of the import lines, but I'd still like to be able to
reference "foo.bar" as meaning the "bar" top-level object in foo.py.



I checked what the docs say about this and it is totally confusing (at 
least me):


https://docs.python.org/3/howto/pyporting.html#from-future-import-absolute-import 
says:


"
from __future__ import absolute_import

Implicit relative imports (e.g., importing spam.bacon from within 
spam.eggs with the statement import bacon) do not work in Python 3. This 
future statement moves away from that and allows the use of explicit 
relative imports (e.g., from . import bacon).


In Python 2.5 you must use the __future__ statement to get to use 
explicit relative imports and prevent implicit ones. In Python 2.6 
explicit relative imports are available without the statement, but you 
still want the __future__ statement to prevent implicit relative 
imports. In Python 2.7 the __future__ statement is not needed. In other 
words, unless you are only supporting Python 2.7 or a version earlier 
than Python 2.5, use this __future__ statement.

"

which I read as there has been a stepwise transition between 2.5 and 2.7 
so that 2.7 now behaves like Python 3 even without the __future__ statement.
OTOH, I believe you, of course, if you're saying implicit relative 
imports are working just fine in 2.7, but then how to interpret the "In 
Python 2.7 the __future__ statement is not needed." above ?


Wolfgang

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


Re: Style question: Importing modules from packages - 'from' vs 'as'

2014-12-04 Thread Wolfgang Maier

On 04.12.2014 19:05, Chris Angelico wrote:


With os.path it definitely is. With the actual code in question, it's
a Python 2.7 project that mostly uses relative imports - inside
package.module1 is "import module2" etc - and I was writing an
external script that calls on one of the modules.


What ? I'm usually thinking Python 3 not 2 and I'm never sure which 
Python 2.x has backported which feature of 3, but I thought implicit 
relative imports like you seem to describe are not working in 2.7 ?


Wolfgang

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


Re: Style question: Importing modules from packages - 'from' vs 'as'

2014-12-04 Thread Wolfgang Maier

On 12/03/2014 12:02 PM, Chris Angelico wrote:

When importing a module from a subpackage, it's sometimes convenient
to refer to it throughout the code with a one-part name rather than
two. I'm going to use 'os.path' for the examples, but my actual
use-case is a custom package where the package name is, in the
application, quite superfluous.

Throughout the code, I want to refer to "path.split()",
"path.isfile()", etc, without the "os." in front of them. I could do
either of these:

import os.path as path
from os import path

Which one would you recommend? Does it depend on context?



One argument not yet brought up by anyone else:

if you ever wanted to make the module part of your own package and turn 
the import into a relative one, only the second, but not the first form 
lets you replace the package name with . :


from . import path (while import .path is a SyntaxError, so you'd need a 
slightly more complicated rewrite).


Wolfgang


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


Re: A syntax question

2014-11-10 Thread Wolfgang Maier

You may want to read:

https://docs.python.org/3/faq/programming.html?highlight=global#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

from the Python docs Programming FAQ section.
It explains your problem pretty well.

As others have hinted at, always provide concrete Python error messages 
and tracebacks instead of vague descriptions.


Best,
Wolfgang


On 11/10/2014 12:07 PM, Mok-Kong Shen wrote:


I don't understand the following phenomenon. Could someone kindly
explain it? Thanks in advance.

M. K. Shen

-

count=5

def test():
   print(count)
   if count==5:
 count+=0  ### Error message if this line is active, otherwise ok.
 print(count)
   return

test()


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


Re: Different behaviour in list comps and generator expressions

2014-11-08 Thread Wolfgang Maier

On 08.11.2014 22:31, Wolfgang Maier wrote:

On 08.11.2014 02:50, Steven D'Aprano wrote:

The following list comprehension and generator expression are almost, but
not quite, the same:

[expr for x in iterable]

list(expr for x in iterable)


The difference is in the handling of StopIteration raised inside the
expr.
Generator expressions consume them and halt, while comprehensions allow
them to leak out.


This is not the right description of what's happening. It is not the
generator expression that consumes it, but the list constructor and, of
course, list can't tell at which level in the inside code StopIteration
got raised.
So, yes this had me confused some times, too, but it is really not
surprising.


A simple example:

iterable = [iter([])]
list(next(x) for x in iterable)
=> returns []

But:

[next(x) for x in iterable]
=> raises StopIteration



Yes, but the equivalent to list(next(x) for x in iterable) is:

l = []
for item in (next(x) for x in iterable):
 l.append(item)

=> returns [] because the for consumes the StopIteration

this, on the other hand raises StopIteration

l = []
for item in [next(x) for x in iterable]:
 l.append(item)

because the error gets raised already when for causes iter() to be
called on the list comprehension.



Has anyone come across this difference in the wild? Was it a problem?
Do you
rely on that difference, or is it a nuisance? Has it caused difficulty in
debugging code?

If you had to keep one behaviour, which would you keep?



The point is: there is no difference in the behavior of comprehensions
and generator expressions, it is just how you access them:
for anything that follows the iterator protocol, a comprehension (since
it is evaluated immediately) raises during the iter() phase, while a
generator expression (which gets evaluated lazily) raises during the
next() phase where it gets swallowed.

So in your example you would have to use the silly

list([next(x) for x in iterable])

if you want the error to get raised.

I agree this is all rather non-intuitive, but how would you change it ?




Ah, I came across the related thread on python-ideas only now and from 
this I can see that, as I expected, you know everything I've written 
above already.


In light of the discussion on the other list:
I did find it annoying occasionally that raising StopIteration inside a 
generator expression conveys a different behavior than elsewhere. It did 
take me quite a while to understand why that is so, but after that it 
did not cause me much of a headache anymore.


I would say that Guido's suggestion of transforming StopIteration raised 
inside a generator into some other error to eliminate ambiguity would 
really help in some situations, but then I'm not sure whether that's 
worth breaking existing code.


Best,
Wolfgang

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


Re: Different behaviour in list comps and generator expressions

2014-11-08 Thread Wolfgang Maier

On 08.11.2014 02:50, Steven D'Aprano wrote:

The following list comprehension and generator expression are almost, but
not quite, the same:

[expr for x in iterable]

list(expr for x in iterable)


The difference is in the handling of StopIteration raised inside the expr.
Generator expressions consume them and halt, while comprehensions allow
them to leak out.


This is not the right description of what's happening. It is not the 
generator expression that consumes it, but the list constructor and, of 
course, list can't tell at which level in the inside code StopIteration 
got raised.
So, yes this had me confused some times, too, but it is really not 
surprising.



A simple example:

iterable = [iter([])]
list(next(x) for x in iterable)
=> returns []

But:

[next(x) for x in iterable]
=> raises StopIteration



Yes, but the equivalent to list(next(x) for x in iterable) is:

l = []
for item in (next(x) for x in iterable):
l.append(item)

=> returns [] because the for consumes the StopIteration

this, on the other hand raises StopIteration

l = []
for item in [next(x) for x in iterable]:
l.append(item)

because the error gets raised already when for causes iter() to be 
called on the list comprehension.




Has anyone come across this difference in the wild? Was it a problem? Do you
rely on that difference, or is it a nuisance? Has it caused difficulty in
debugging code?

If you had to keep one behaviour, which would you keep?



The point is: there is no difference in the behavior of comprehensions 
and generator expressions, it is just how you access them:
for anything that follows the iterator protocol, a comprehension (since 
it is evaluated immediately) raises during the iter() phase, while a 
generator expression (which gets evaluated lazily) raises during the 
next() phase where it gets swallowed.


So in your example you would have to use the silly

list([next(x) for x in iterable])

if you want the error to get raised.

I agree this is all rather non-intuitive, but how would you change it ?


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


Re: A bug?

2014-10-27 Thread Wolfgang Maier

On 10/27/2014 05:01 PM, uma...@gmail.com wrote:

I use python 3.4.0 version. In the course of developing / running a python 
program, I have encountered a problem. I have reproduced below a simple program 
to bring it out.



d = [[0]*3]*4
dd = [1,2,3,4,5,6,7,8,9,10,11,12]
for i in range(4):

...   for j in range(3): d[i][j] = dd[i*3+j]
...

d

[[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]]



d is not transferred to dd as expected?
Of course I can use 'append' & do my job (less elegantly though).



See 
https://docs.python.org/3/library/stdtypes.html?highlight=list#common-sequence-operations 
under Note 2 .


Also asked and answered multiple times at stackoverflow, e.g., 
http://stackoverflow.com/questions/6688223/




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


Re: Status of side-effecting functions in python

2014-10-25 Thread Wolfgang Maier

On 25.10.2014 19:27, Rustom Mody wrote:

Moved from other (Seymore's) thread where this is perhaps not relevant

On Saturday, October 25, 2014 1:15:09 PM UTC+5:30, Steven D'Aprano wrote:

Rustom Mody wrote:


On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote:

On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody  wrote:

Its generally accepted that side-effecting functions are not a good
idea -- typically a function that returns something and changes global
state.


Only in certain circles. Not in Python. There are large numbers of
functions with side effects (mutator methods like list.append,
anything that needs lots of state like random.random, everything with
external effect like I/O, heaps of stuff), and it is most definitely
not frowned upon.

In Python 3 (or Python 2 with the future directive), print is a
function, print() an expression. It's not "semantically a statement".


Ok
So give me a valid (ie useful) use where instead of the usual
l=[1,2,3]
l.append(4)

we have

foo(l.append(4))


Your question seems to be non-sequitor. To me, it doesn't appear to have any
relationship to Chris' comments.


| Languages like Pascal (many others)... distinguish function which return
| results and procedure which do not...
| Extract from https://en.wikipedia.org/wiki/Subroutine#Language_support

So my point: Whether the language supports it strongly (Pascal'
procedures) weakly (C's void functions) more weakly (Python's None
returning functions), the beginning programmer needs this concept as a core
thinking tool.

Pascal makes this easy -- teach the syntax and the concept will get across
Python is harder because the concept does not correlate with any specific syntax
But its not all that hard unless the teacher is stuck in correlating core 
concepts
and language syntax.

A teacher who is so stuck is cheating the student.

My version:
"print may (3) or may not (2) be an expression. Just always consider it as a 
statement"

Chris version: print() is an expression.
Technically Chris is correct. Is it methodologically/pedagogically it is sound?

Consider:

 From my explanation this:


[print(x) for x in [1,2,3]]

1
2
3
[None, None, None]




is in "Dont Do!" category whether python (3) allows it or python 2 doesn't.
And you "Dont do" because print(x) is a statement -- literally in
python 2; morally in python 3

And from here its only a small step to why l.append(4) should never
be used except as a statement. Python may not literally have Pascal's 
procedures;
they are morally there if you choose to 'believe' in them.

How would Chris inculcate avoidance of code-smells like
- foo(l.append(4))
- [print(x) for x in [1,2,3]]



As Chris and Steven have pointed out, picking print() as an example does 
not make too much sense since it returns None.
It may be rare to use an expression both for its side-effects and its 
return value, but, provided you document the intention appropriately, I 
do not see what would generally be wrong with it.


A quick example that's not quite as silly as all your print() ones:

>>> with open('longnumber.txt', 'w') as out:
print(sum(out.write(str(x)) for x in range(100)), 'characters written.')


190 characters written.


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


Re: Truthiness

2014-10-23 Thread Wolfgang Maier

On 10/23/2014 04:47 PM, Alain Ketterlin wrote:

Simon Kennedy  writes:


Just out of academic interest, is there somewhere in the Python docs where the 
following is explained?


3 == True

False

if 3:

print("It's Twue")

It's Twue

i.e. in the if statement 3 is True but not in the first


https://docs.python.org/2/reference/compound_stmts.html#the-if-statement

says: "The if statement [...] selects exactly one of the suites by
evaluating the expressions one by one until one is found to be true (see
section Boolean operations for the definition of true and false)"



Exactly, but in

if 3 == True:

the expression is 3==True , in which 3 and True compare unequal, thus, 
the expression is false.

On the other hand, in

if 3:

the expression to evaluate is just the int object and the rules below apply.


and then:

https://docs.python.org/2/reference/expressions.html#booleans

says: "In the context of Boolean operations, and also when expressions
are used by control flow statements, the following values are
interpreted as false: False, None, numeric zero of all types, and empty
strings and containers (including strings, tuples, lists, dictionaries,
sets and frozensets). All other values are interpreted as true."

(links are to the 2.7 version of the reference manual, I think not much
has changed in 3.* versions.)

-- Alain.



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


Re: Truthiness

2014-10-23 Thread Wolfgang Maier

On 10/23/2014 04:30 PM, Simon Kennedy wrote:

Just out of academic interest, is there somewhere in the Python docs where the 
following is explained?



https://docs.python.org/3/library/stdtypes.html#truth-value-testing


3 == True

False


as opposed to:

https://docs.python.org/3/library/stdtypes.html#comparisons


if 3:

print("It's Twue")

It's Twue

i.e. in the if statement 3 is True but not in the first



Here is the misunderstanding: it is not true that 3 is True in the if 
example, but it's evaluated as True in a boolean context. Illustration:


>>> 3 == True
False

>>> bool(3) == True
True

>>> bool(3) is True
True

If you combine if and a comparison, it behaves like in your first example:

>>>
if 3 == True:
print('True')
else:
print('False')

False


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


Re: stressing problem with Python < 3.3.3 / 2.7.6 and Mac OS 10.9 Mavericks

2014-10-14 Thread Wolfgang Maier

On 14.10.2014 22:30, Ned Deily wrote:

In article ,
  Wolfgang Maier  wrote:

I'm not a regular MacPython user, but today I had to build Mac wheels
for different versions of Python. To test the wheel files I set up a
fresh Mac OS 10.9 Mavericks and and installed Python 3.2, 3.3, 3.4 from
the python.org download page on it. Then I struggled for the rest of the
afternoon to try to figure out why Python 3.2 crashed when I used my
package in interactive mode until I finally realized that it's not the
package but Python that's responsible.

Turns out that I had run into http://bugs.python.org/issue18458 which
probably every MacPython user here is so familiar with that the download
page doesn't even mention it ? ;)

Seriously, I think the official download page for a OS shouldn't offer
me a version that will not work well with the latest version of that OS
without a warning. Why not add such a warning (like: versions below will
crash in interactive mode on Mac OS 10.9) in the list of downloads at
https://www.python.org/downloads/mac-osx/ between Python 2.7.6 (the
first version with the issue fixed) and Python 3.2.5 (the last affected
version).


Sorry you ran into that problem.  Unfortunately, that's a general
problem when using older versions of Python that are in
security-fix-only mode, e.g. those no longer in active maintenance mode.
Currently only 3.2.x and 3.3.x are in that category.

"The only changes made to a security branch are those fixing issues
exploitable by attackers such as crashes, privilege escalation and,
optionally, other issues such as denial of service attacks. Any other
changes are not considered a security risk and thus not backported to a
security branch."

https://docs.python.org/devguide/devcycle.html#security-branches

Fixes for new operating system releases do not fall in this category.
There are certainly other problems that one will run into on platform
releases newer than those supported and tested at the time of the final
maintenance release.  However, we did add a warning about this
particular issue to the release page of the final security release of
2.6.x.  That warning is now copied into the 3.2.6 release page.



Thanks for the fast response, Ned.

I fully understand how the issue arose and why it hasn't been fixed. No 
complaints about that.
I just thought that, if you cannot use the interactive interpreter on a 
standard version of the OS you're downloading for, that deserves a 
prominent mention.


The added warning in the 3.2.6 release page may have saved me a bit of 
searching *after* I figured out what's going on, but I wouldn't have 
discovered it *before* downloading.



In the future, if you encounter problems with the python.org website,
follow the Help link at the bottom of each page to the website issue
tracker.



Thanks for pointing that out. I thought such a link must exist, but 
posting to this list seemed simpler than looking for it. I'll remember 
it for next time.


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


stressing problem with Python < 3.3.3 / 2.7.6 and Mac OS 10.9 Mavericks

2014-10-14 Thread Wolfgang Maier

Hi,

I'm not a regular MacPython user, but today I had to build Mac wheels 
for different versions of Python. To test the wheel files I set up a 
fresh Mac OS 10.9 Mavericks and and installed Python 3.2, 3.3, 3.4 from 
the python.org download page on it. Then I struggled for the rest of the 
afternoon to try to figure out why Python 3.2 crashed when I used my 
package in interactive mode until I finally realized that it's not the 
package but Python that's responsible.


Turns out that I had run into http://bugs.python.org/issue18458 which 
probably every MacPython user here is so familiar with that the download 
page doesn't even mention it ? ;)


Seriously, I think the official download page for a OS shouldn't offer 
me a version that will not work well with the latest version of that OS 
without a warning. Why not add such a warning (like: versions below will 
crash in interactive mode on Mac OS 10.9) in the list of downloads at 
https://www.python.org/downloads/mac-osx/ between Python 2.7.6 (the 
first version with the issue fixed) and Python 3.2.5 (the last affected 
version).


Wolfgang

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


Re: Python code in presentations

2014-10-01 Thread Wolfgang Keller
> Right now the method I'm using is write the code in notepad++, use a
> plugin (NppExport) to copy paste code into powerpoint. After using it
> a little bit, I'm really not satisfied with this method, it's
> expensive and all this copy paste stuff is driving me crazy. Not to
> mention that the syntax highlight from notepads renders like crap in
> powerpoint.
> 
> I wonder if some people in this list who have successfully presented
> python code have some tips about doing the proper way. Ned's
> presentations for pycons are to me one example of successful code
> presentation:
>   - the layout is simple
>   - the code and code output are clearly identified
>   - a line of code can be highlighted while presenting

LyX and Beamer.

Sincerely,

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


Re: Thoughts on python classes to represent an ebook reader

2014-10-01 Thread Wolfgang Maier

On 01.10.2014 10:14, math math wrote:

Hi,

I hope there are people here with strong OOP experience.

Which classes would an object-oriented python programmer create for the design 
of a e-book reader for example? I am not really interested in the code, just 
the OOP classes that would come to one's mind for a task like this.

It should allow users to buy new e-books, view their list of purchased books 
and read the books.

I have made an attempt of class diagram here "http://imgur.com/9TR2Tlm"; but I 
would be really glad to hear other opinions. I have not used any inheritance for example. 
I didn't know exactly where it would be handy and I also dont know if these classes are 
theoretically a good basis at all...

Thanks a lot for comments/feedback.
Felix



As it happens, the very popular Calibre ebook software is written in 
Python. So, I guess, getting (https://github.com/kovidgoyal/calibre) and 
looking at its source code should give you a good start.


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


  1   2   3   4   5   6   >