Re: Guido on python3 for beginners

2016-02-18 Thread INADA Naoki
In Python 3, I don't required to teach followings to newbies.

1. Don't do `class Foo:`, do `class Foo(object):`.
2. Don't do `isinstance(x, int)`, do `isinstance(x, (int, long))`.
3. Don't return non-ASCII string from `__repr__`, otherwise UnicodeError
   happens in logging and you will lost your important log.
4. Use %r instead of %s in logging to avoid UnicodeError when __str__
returns non ASCII strings.

I think there are many pitfalls fixed in Python 3 other than above.
Python 3 is far easier to teach and review code than Python 2.


On Thu, Feb 18, 2016 at 4:27 PM, Chris Angelico  wrote:

> On Thu, Feb 18, 2016 at 5:47 PM, Steven D'Aprano
>  wrote:
> > There are more features in Python 3, so in that trivial sense of "more to
> > learn", I suppose that it is objectively correct that it is harder to
> learn
> > than Python 2. But I don't think the learning curve is any steeper. If
> > anything, the learning curve is ever-so-slightly less steep.
>
> Let's see... changes in Py3.
>
> 1) Division of two integers now yields a float instead of flooring.
> For someone fresh to programming, that's a Py3 advantage, although it
> can cause surprises elsewhere. But since 1.0==1, it's not going to be
> a problem for a new programmer. Advantage: Py3.
>
> 2) Strings are Unicode text, and files etc may need to have their
> encodings declared. Definitely causes some issues in ASCII-only
> situations, where a lot of other languages (notably including PHP, for
> the people building web sites) let you be sloppy. Advantage: Py3 if
> you speak any language other than English; otherwise Py2 in the very
> short term, neither in the medium term, and most definitely Py3 in the
> long term (no more "funny characters break my program" errors long
> after deployment).
>
> 3) Laziness. When you explain to someone what the range() function
> does, Py2 makes a list, but Py3 makes... a range. It doesn't really
> answer the question at all. When you ask Py2 for a dictionary's
> keys/values, you get a list; Py3 gives you a thing that mostly acts
> like a list, only it isn't. If you map a function over a list, you get
> back a lazy thing that will eventually call that function. Py2 often
> has less levels of indirection, ergo less things to try to explain.
> Advantage: Py2; the benefits (lower memory usage, etc) aren't
> significant to new users.
>
> 4) Exception chaining. You get more information when errors cascade.
> Advantage: Py3, easily and without any question.
>
> 5) print statement/function. Py3 forces you to put parentheses on it,
> which is no different from C's printf() or Pike's write() or any
> number of other languages where console I/O needs no language support.
> Maybe a tiny TINY advantage to Py2 in the short term, but as soon as
> you introduce the less basic features, keyword arguments are way
> better than the magic syntax the statement needs. (Also, trying to
> explain the interaction between the print statement's "soft space" and
> other console I/O is not easy.) By the time you've really learned the
> language, the advantage belongs to Py3.
>
> 6) The fact that the name "python" may not invoke the interpreter you
> want. Advantage: Py2, if any; there'll be times when they're on par,
> but Py3 never comes out ahead.
>
> 7) Whether or not the interpreter comes pre-installed on your system.
> As of a few years ago, that was a clear advantage to Py2 (most systems
> would ship with both, or neither, or Py2 only), but that's shifting.
> It's only a small difference, though; on Windows, you generally get
> nothing, and on any system with a decent package manager, you should
> be able to request either version with ease.
>
> It's actually a pretty tough call. Most of the Py3 advantages aren't
> for the absolute beginner; it's not easier to write "Hello, world" in
> Py3, and aside from the change to integer division, most of the
> changes won't benefit small-to-medium scripts either. The biggest
> advantage (Unicode by default) really only shows itself by sparing you
> hassles later on - it's not going to make your life easier in the
> short term, ergo it's not going to make the language easier to learn.
> Py3 isn't so much easier as _better_. There are specific situations
> where it's massively better, but for the most part, they're about on
> par.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>



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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
Thanks to all of you who have responded. One point two of you ask me is why I 
want to shift from Visual Basic. 

Most of my software is in VB6 (and VB3), and converting to VB.net is not very 
pleasant. I have learnt enough VB.net to manage most of the things I will need, 
but it always gives me a feeling that it is not meant for the kind of things I 
am doing. And you never know when Microsoft will kick us out of VB.net also. 
For the sake of keeping software compatible with new versions of Windows, you 
need to keep changing things in the software, which takes too much time. You 
might ask if it is really necessary to move from VB6 to VB.net because 
Microsoft will still not be able to kill VB6 very soon, thanks to VBA used in 
Excel. If my reasoning is wrong, please correct me. I am just an engineer, not 
a good programmer.

Is it easy to create vector graphics files of plots in Python? In VB6, I wrote 
my own code to generate EPS files. Then people who demand jpg and gif files 
could be given those by converting the EPS with the desired resolution.

More points in the text below.

William Ray Wing writes:
> > On Feb 17, 2016, at 2:49 PM, [email protected] wrote:
> > 
> > It seems Python is used more for web based applications. Is it equally fine 
> > for creating stand-alone *.exe's? Can the same code be compiled to run on 
> > Linux or Android or web-based?
> > 
> 
> I'm not sure where you got that idea.  Python has been and is being used for 
> an extremely broad range of applications.  At one extreme, the popular 
> YouTube site is based on Python (and yes, that is a web application), at the 
> other extreme much (most?) of the data analysis of the recent LIGO data 
> leading up to the discovery of gravitational waves was done in Python, and 
> numpy (a python numerical library); with the results displayed in matplotlib 
> (a python library for scientific-engineering graphics).
> 

This is good news, because I need several kinds of plots.

> The basic python language and its libraries are completely cross-platform 
> (Linux, OS-X, Windows, iOS, and Android).  The same source code will run on 
> all of them.  However, because it is an Interpreted language, the step to a 
> bundled, self-contained image is platform dependent. There python compliers 
> (as opposed to interpreters) for some, but not all platforms, and there is a 
> very active JiT compiler project that would fall somewhere in between. 
> 

OK. This is clear to me now. It is like needing different Fortran compilers for 
different operating systems, but Fortran code does not need much modifications 
(except file names/paths, etc.).

> > Is it possible to create GUI elements with a good IDE? Can they be defined 
> > like in Visual Basic with given sizes, fonts, visible/invisible, etc.?
> > 
> 
> There are several GUI libraries for Python.  You might check out TK (which 
> comes built-in), but there are also libraries like wxPython, Kivi (which is 
> completely cross platform), and PyQt.  Note that these are the GUI libraries 
> themselves, not IDE's which tend to be independent.  There are too many IDE's 
> to list here - check with Google.
> 
> > Is it easy to do matrix operations in Python? Or do I need to write 
> > subroutines like in Visual Basic?
> 
> Matrix (and similar operations) can be done in Python directly, but if you 
> need maximum performance you should use the optimized vector routines 
> available 

Speed is usually not an issue.

> in numpy, these are typically pre-compiled with C or FORTRAN and squeeze out 
> the maximum speed your hardware is capable of.  (There is work being done to 
> migrate them to GPUs, but is VERY hardware dependent at this point.) If you 
> need to do scientific/engineering analysis, you should also check out scipy, 
> which is built on top of it and is also vector optimized.
> 
> > 
> > Could someone kindly tell me advantages and disadvantages of Python?
> 
> If you are completely satisfied with VB, there is no reason to change (other 
> than the enjoyable exercise of learning a new and more powerful language).
> 

Will VB6 run on Windows 11? Or can I compile VB6 on Windows 11. We can't know. 
But there will be easy ways to run Python on any Windows version or Linux or 
whatever.

> On the other hand, Python has often been referred to as "executable pseudo 
> code" - in other words, the english-like steps you might sketch out to 
> outline the solution to a programming problem in another language is to all 
> intents and purposes Python itself.  This makes for very fast and productive 
> code generation with typically fewer errors than are made in other languages. 
> In addition, and as has been implied above, it is cross platform.  The same 
> python source code (with the appropriate libraries) will run on all the 
> platforms mentioned above. One of the biggest productive features of Python 
> is the fact that it is interpreted (in its most common instantiation).  Thus, 
> you can hav

Re: Guido on python3 for beginners

2016-02-18 Thread Terry Reedy

On 2/18/2016 2:27 AM, Chris Angelico wrote:

On Thu, Feb 18, 2016 at 5:47 PM, Steven D'Aprano
 wrote:

There are more features in Python 3, so in that trivial sense of "more to
learn", I suppose that it is objectively correct that it is harder to learn
than Python 2. But I don't think the learning curve is any steeper. If
anything, the learning curve is ever-so-slightly less steep.


Let's see... changes in Py3.

1) Division of two integers now yields a float instead of flooring.
For someone fresh to programming, that's a Py3 advantage, although it
can cause surprises elsewhere. But since 1.0==1, it's not going to be
a problem for a new programmer. Advantage: Py3.

2) Strings are Unicode text, and files etc may need to have their
encodings declared. Definitely causes some issues in ASCII-only
situations, where a lot of other languages (notably including PHP, for
the people building web sites) let you be sloppy. Advantage: Py3 if
you speak any language other than English; otherwise Py2 in the very
short term, neither in the medium term, and most definitely Py3 in the
long term (no more "funny characters break my program" errors long
after deployment).

3) Laziness. When you explain to someone what the range() function
does, Py2 makes a list, but Py3 makes... a range. It doesn't really
answer the question at all. When you ask Py2 for a dictionary's
keys/values, you get a list; Py3 gives you a thing that mostly acts
like a list, only it isn't. If you map a function over a list, you get
back a lazy thing that will eventually call that function. Py2 often
has less levels of indirection, ergo less things to try to explain.
Advantage: Py2; the benefits (lower memory usage, etc) aren't
significant to new users.

4) Exception chaining. You get more information when errors cascade.
Advantage: Py3, easily and without any question.

5) print statement/function. Py3 forces you to put parentheses on it,
which is no different from C's printf() or Pike's write() or any
number of other languages where console I/O needs no language support.
Maybe a tiny TINY advantage to Py2 in the short term, but as soon as
you introduce the less basic features, keyword arguments are way
better than the magic syntax the statement needs. (Also, trying to
explain the interaction between the print statement's "soft space" and
other console I/O is not easy.) By the time you've really learned the
language, the advantage belongs to Py3.

6) The fact that the name "python" may not invoke the interpreter you
want. Advantage: Py2, if any; there'll be times when they're on par,
but Py3 never comes out ahead.

7) Whether or not the interpreter comes pre-installed on your system.
As of a few years ago, that was a clear advantage to Py2 (most systems
would ship with both, or neither, or Py2 only), but that's shifting.
It's only a small difference, though; on Windows, you generally get
nothing, and on any system with a decent package manager, you should
be able to request either version with ease.

It's actually a pretty tough call. Most of the Py3 advantages aren't
for the absolute beginner; it's not easier to write "Hello, world" in
Py3, and aside from the change to integer division, most of the
changes won't benefit small-to-medium scripts either. The biggest
advantage (Unicode by default) really only shows itself by sparing you
hassles later on - it's not going to make your life easier in the
short term, ergo it's not going to make the language easier to learn.
Py3 isn't so much easier as _better_. There are specific situations
where it's massively better, but for the most part, they're about on
par.


8. 2.x has two subtlely different types of classes.  The 2.x docs do not 
document the type of builtin and stdlib classes. I discovered that 
tkinter classes are still old-style in 2.7 when I backported a patch 
from 3.x to 2.7 and it mysteriously did not work. Py 3 wins here.  To 
me, this alone makes 2.x a bad choice for most beginners.


9. Two integer classes and the nuisance of 'L' suffix.  Py 3 wins for 
beginners, at least.  (Mentioned by Inaki).


10. Two except-clause syntaxes in 2.7, just one in 3.x.  -1 syntax is 
+1 vote for 3.x


11.  To test is something is text, isinstance s, c), where 'c' is one of 
str, bytes, unicode, basestring, (bytes, unicode), (str, unicode).  +1 
for 3.x.


12. 2.7 has two different open' functions, open and io.open.  In 3.x 
these are the same opjects.  I believe there are other 3.x backports 
like this.


13. 2.7 has two ways to apply arguments to functions: apply and *args. 
3.x only has the latter.


To my mind, the numerous duplications and overlaps in 2.7 that are gone 
in 3.x make 2.7 the worse version ever for beginners.



--
Terry Jan Reedy

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


Testing whether the VPN is running?

2016-02-18 Thread Adam Funk
I'd like to test (inside a python 3 program) whether the VPN is
running or not.  The only thing I can think of so far is to use
subprocess to run the 'ifconfig' command, then check its output for
'tun0'.  Is there a better way?

Thanks.


-- 
Nam Sibbyllam quidem Cumis ego ipse oculis meis vidi in ampulla 
pendere, et cum illi pueri dicerent: beable beable beable; respondebat 
illa: doidy doidy doidy. --- plorkwort
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing whether the VPN is running?

2016-02-18 Thread Ervin Hegedüs
Hi Adam,

On Thu, Feb 18, 2016 at 09:26:58AM +, Adam Funk wrote:
> I'd like to test (inside a python 3 program) whether the VPN is
> running or not.  The only thing I can think of so far is to use
> subprocess to run the 'ifconfig' command, then check its output for
> 'tun0'.  Is there a better way?

you didn't wrote, which system (OS) you want to use - based on
the "ifconfig" and "tun0" keywords, possible that's a Linux.

I think that the psutil modul could be better for you for this
task:

https://pypi.python.org/pypi/psutil/

and see the "Network" section.


Regards,


a.
 
-- 
I � UTF-8
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido on python3 for beginners

2016-02-18 Thread Chris Angelico
On Thu, Feb 18, 2016 at 7:40 PM, Terry Reedy  wrote:
> To my mind, the numerous duplications and overlaps in 2.7 that are gone in
> 3.x make 2.7 the worse version ever for beginners.

Hmm. I was teaching on 2.7 up until last year, and for the most part,
we taught a "compatible with Py3" subset of the language, without any
significant cost. If you'd shown code saying "except ValueError, e:"
to one of my Py2 students then, s/he would have been just as
unfamiliar as one of my Py3 students would be today. That said,
though, it's still that Py3 is no worse than Py2, and potentially
better.

The removal of L suffixes (and, similarly, the removal of u"..."
prefixes on text strings) is a bigger deal to newbies than it is to
experienced programmers, so that one definitely counts. "This is
great, but how can I remove that u from the strings?" was a common
question (eg when they're printing out a list of strings obtained from
a database, or decoded from JSON).

The removal of old-style classes is a definite improvement in Py3, as
is the no-arg form of super(), which I'd consider a related change. So
there's a bunch of tiny little "quality of life" improvements here.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Oscar Benjamin
On 18 February 2016 at 08:17,   wrote:
> Is it easy to create vector graphics files of plots in Python?

Yes

> In VB6, I wrote my own code to generate EPS files. Then people who demand jpg 
> and gif files could be given those by converting the EPS with the desired 
> resolution.

That sounds a lot harder than doing it in Python using matplotlib. To
run the following you need Python, numpy and matplotlib:

-
from matplotlib import pyplot as plt

xdata = [0, 1, 2, 3, 4]
ydata = [0, 1, 0, 1, 0]

fig = plt.figure(figsize=(4, 3))
ax = fig.add_axes([0.15, 0.15, 0.70, 0.70])
ax.plot(xdata, ydata, color='black', linewidth=2)
ax.set_xlabel('$V_x$') # Latex math-mode in text
ax.set_ylabel('$V_y$')

plt.show() # Make the plot window appear on screen
-

The last line can be replaced with a call to fig.savefig if you want
the plot to go straight to a file. The format is inferred from the
filename so:

fig.savefig('plot.eps') # Do you really want eps?
fig.savefig('plot.pdf') # I'd use pdf
fig.savefig('plot.jpg') # etc.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Chris Angelico
On Thu, Feb 18, 2016 at 7:17 PM,   wrote:
> Thanks to all of you who have responded. One point two of you ask me is why I 
> want to shift from Visual Basic.
>
> Most of my software is in VB6 (and VB3), and converting to VB.net is not very 
> pleasant. I have learnt enough VB.net to manage most of the things I will 
> need, but it always gives me a feeling that it is not meant for the kind of 
> things I am doing. And you never know when Microsoft will kick us out of 
> VB.net also. For the sake of keeping software compatible with new versions of 
> Windows, you need to keep changing things in the software, which takes too 
> much time. You might ask if it is really necessary to move from VB6 to VB.net 
> because Microsoft will still not be able to kill VB6 very soon, thanks to VBA 
> used in Excel. If my reasoning is wrong, please correct me. I am just an 
> engineer, not a good programmer.
>

Very fair point. And I fully support your move, here. Just make sure
you start on the latest Python (currently that's 3.5), and you should
have no difficulty moving forward in versions; as someone who started
writing Python 3 code back when 3.3 was the newest and latest thing, I
can attest that it's been easy to migrate 3.2->3.3->3.4->3.5->3.6;
there are very few things that get broken by the upgrade, and they're
mostly things that would have been bad code in the older version
anyway.

>> The basic python language and its libraries are completely cross-platform 
>> (Linux, OS-X, Windows, iOS, and Android).  The same source code will run on 
>> all of them.  However, because it is an Interpreted language, the step to a 
>> bundled, self-contained image is platform dependent. There python compliers 
>> (as opposed to interpreters) for some, but not all platforms, and there is a 
>> very active JiT compiler project that would fall somewhere in between.
>>
>
> OK. This is clear to me now. It is like needing different Fortran compilers 
> for different operating systems, but Fortran code does not need much 
> modifications (except file names/paths, etc.).
>

Something like that. There are a lot of little traps you can fall into
(as you say, file names can be different, especially system ones) that
stop your code from running correctly on all platforms, but porting a
Python script from Linux to Windows or vice versa is a matter of
testing it on the new platform and seeing what breaks, not completely
rewriting it in a new language.

>> > Could someone kindly tell me advantages and disadvantages of Python?
>>
>> If you are completely satisfied with VB, there is no reason to change (other 
>> than the enjoyable exercise of learning a new and more powerful language).
>>
>
> Will VB6 run on Windows 11? Or can I compile VB6 on Windows 11. We can't 
> know. But there will be easy ways to run Python on any Windows version or 
> Linux or whatever.
>

There will indeed. That's the advantage of a fully open system - even
if a nuclear meltdown kills all the Python core devs in one stroke (we
really shouldn't have had PyCon Chernobyl), anyone in the world can
pick up the source code and keep going with it. And Microsoft, despite
having a strongly anti-freedom history, has come far more on board of
recent years; as I understand it, Steve Dower has been spending
company time improving Python (notably in the area of Windows
installers and such). The future of open source software is pretty
secure, and the future of openly-developed languages even more so,
because CPython isn't the only way to run your Python code.

One Python advantage that you may or may not be aware of is its
extensibility. To an extent that I haven't seen since working with
REXX on OS/2, there is a thriving community building Python packages,
many of which (about 75K!) are listed on PyPI [1]. Got this
proprietary database that you need to get info from? Check PyPI -
chances are someone's written a connector for it, so you can perform
queries on it as if it had native support in the language. Once you
install something using "pip" [2], you can import it into your script
the exact same way that you would import something from the standard
library - making PyPI kinda like the "extended library" for the
language. The barrier to entry is low, though, so you do sometimes
have to wade through a bunch of stagnant or expired projects to find
the gems you want. But there's so much good stuff there that it's well
worth the effort.

ChrisA

[1] https://pypi.python.org/pypi
[2] No, not the chipmunk from Enchanted.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Testing whether the VPN is running?

2016-02-18 Thread Adam Funk
On 2016-02-18, Ervin Hegedüs wrote:

> Hi Adam,
>
> On Thu, Feb 18, 2016 at 09:26:58AM +, Adam Funk wrote:
>> I'd like to test (inside a python 3 program) whether the VPN is
>> running or not.  The only thing I can think of so far is to use
>> subprocess to run the 'ifconfig' command, then check its output for
>> 'tun0'.  Is there a better way?
>
> you didn't wrote, which system (OS) you want to use - based on
> the "ifconfig" and "tun0" keywords, possible that's a Linux.

Oops, sorry!  But your educated guess is right.  :-)

> I think that the psutil modul could be better for you for this
> task:
>
> https://pypi.python.org/pypi/psutil/
>
> and see the "Network" section.

if 'tun0' in psutil.net_if_addrs():
   # vpn is running

Brilliant!  I've used psutil for something else, but I didn't know it
did that too.  My excuse is that the version on my system was 2.2.1,
which does not do that, so I installed the newer version with pip3.
Thanks for pointing me to that.


-- 
XML is like violence: if it doesn't solve the problem,
use more.
-- 
https://mail.python.org/mailman/listinfo/python-list


Trying to build Python from Source on HPUX 11.23 IA fails

2016-02-18 Thread bthk55

I am trying to build python from source on HPUX 11.23 IA  I am using the latest 
python version 3.5.1. 


I am getting the following error:

Error 172: "Python/pytime.c", line 627 # Undeclared variable 'CLOCK_MONOTONIC'. 
const clockid_t clk_id = CLOCK_MONOTONIC; ^^^ *** Error exit code 2


I used the following steps to build :


export CC="cc +DD64"
export CXX=aCC

./configure --prefix=/opt/soe/local/Python-3.5.1



Does anyone know what is the issue here.


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


Re: Guido on python3 for beginners

2016-02-18 Thread Cem Karan

On Feb 18, 2016, at 4:57 AM, Chris Angelico  wrote:

> On Thu, Feb 18, 2016 at 7:40 PM, Terry Reedy  wrote:
>> To my mind, the numerous duplications and overlaps in 2.7 that are gone in
>> 3.x make 2.7 the worse version ever for beginners.
> 
> Hmm. I was teaching on 2.7 up until last year, and for the most part,
> we taught a "compatible with Py3" subset of the language, without any
> significant cost. If you'd shown code saying "except ValueError, e:"
> to one of my Py2 students then, s/he would have been just as
> unfamiliar as one of my Py3 students would be today. That said,
> though, it's still that Py3 is no worse than Py2, and potentially
> better.
> 
> The removal of L suffixes (and, similarly, the removal of u"..."
> prefixes on text strings) is a bigger deal to newbies than it is to
> experienced programmers, so that one definitely counts. "This is
> great, but how can I remove that u from the strings?" was a common
> question (eg when they're printing out a list of strings obtained from
> a database, or decoded from JSON).
> 
> The removal of old-style classes is a definite improvement in Py3, as
> is the no-arg form of super(), which I'd consider a related change. So
> there's a bunch of tiny little "quality of life" improvements here.
> 
> ChrisA

I agree with Chris on all his points.  My personal feeling is that Py3 is the 
way to go for teaching in the future; its just that little bit more consistent 
across the board.  And the things that are confusing are not things that 
beginners will need to know about.

About the only thing I've read where Py2 has a slight advantage is for scripts 
where you're suddenly surprised by Py2 starting up when you've been using a Py3 
interactive interpreter.  For me, I'd probably give my students a block of code 
that they are asked to copy at the start of their files to test for Py2 or Py3, 
and to raise an exception on Py2.  After that, I just wouldn't worry about it.

Thanks,
Cem Karan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido on python3 for beginners

2016-02-18 Thread Chris Angelico
On Thu, Feb 18, 2016 at 9:57 PM, Cem Karan  wrote:
> I agree with Chris on all his points.  My personal feeling is that Py3 is the 
> way to go for teaching in the future; its just that little bit more 
> consistent across the board.  And the things that are confusing are not 
> things that beginners will need to know about.
>
> About the only thing I've read where Py2 has a slight advantage is for 
> scripts where you're suddenly surprised by Py2 starting up when you've been 
> using a Py3 interactive interpreter.  For me, I'd probably give my students a 
> block of code that they are asked to copy at the start of their files to test 
> for Py2 or Py3, and to raise an exception on Py2.  After that, I just 
> wouldn't worry about it.
>

Another solution is to have a little bit of boilerplate at the shell first:

python3 -m venv env
source env/bin/activate

Then both "python" and "python3" will run the binary from your virtual
environment, and as a side bonus, you get to use pip without root
privileges.

By the way... For bash users, adding this to .bashrc may make venvs a
bit easier to keep straight:

checkdir() {
[ -n "$VIRTUAL_ENV" ] && ! [[ `pwd` =~ `dirname $VIRTUAL_ENV`* ]]
&& echo Deactivating venv $VIRTUAL_ENV... && deactivate
[ -z "$VIRTUAL_ENV" -a -d env ] && echo Activating venv
`pwd`/env... && source env/bin/activate
}
PROMPT_COMMAND=checkdir

(I'm more fluent in Python than in bash, so this is a bit ugly.)

As soon as you change out of the directory that contains your venv,
it'll be deactivated, so you can't accidentally run stuff in the
"wrong" environment. And as soon as you change into a directory that
contains an 'env' subdir, it'll activate it. (Also applies on first
creation; as soon as "python3 -m venv env" returns, this will activate
the env.)

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1

Almost everything points positively for Python. Thanks to all of you who have 
responded. But please also tell me the disadvantages of Python. If I start 
using Python, I should be aware of the price I am paying. Speed is not a big 
problem for me, so an interpreted language is fine. Is packaging/installing 
very messy? Do I create dozens of files for a simple program calculating the 
sum of two numbers and product of two numbers in text boxes with one command to 
be clicked? Can I learn this much in the first couple of hours?

torstai 18. helmikuuta 2016 12.16.30 UTC+2 Chris Angelico kirjoitti:
> On Thu, Feb 18, 2016 at 7:17 PM,   wrote:
> > Thanks to all of you who have responded. One point two of you ask me is why 
> > I want to shift from Visual Basic.
> >
> > Most of my software is in VB6 (and VB3), and converting to VB.net is not 
> > very pleasant. I have learnt enough VB.net to manage most of the things I 
> > will need, but it always gives me a feeling that it is not meant for the 
> > kind of things I am doing. And you never know when Microsoft will kick us 
> > out of VB.net also. For the sake of keeping software compatible with new 
> > versions of Windows, you need to keep changing things in the software, 
> > which takes too much time. You might ask if it is really necessary to move 
> > from VB6 to VB.net because Microsoft will still not be able to kill VB6 
> > very soon, thanks to VBA used in Excel. If my reasoning is wrong, please 
> > correct me. I am just an engineer, not a good programmer.
> >
> 
> Very fair point. And I fully support your move, here. Just make sure
> you start on the latest Python (currently that's 3.5), and you should
> have no difficulty moving forward in versions; as someone who started
> writing Python 3 code back when 3.3 was the newest and latest thing, I
> can attest that it's been easy to migrate 3.2->3.3->3.4->3.5->3.6;
> there are very few things that get broken by the upgrade, and they're
> mostly things that would have been bad code in the older version
> anyway.
> 
> >> The basic python language and its libraries are completely cross-platform 
> >> (Linux, OS-X, Windows, iOS, and Android).  The same source code will run 
> >> on all of them.  However, because it is an Interpreted language, the step 
> >> to a bundled, self-contained image is platform dependent. There python 
> >> compliers (as opposed to interpreters) for some, but not all platforms, 
> >> and there is a very active JiT compiler project that would fall somewhere 
> >> in between.
> >>
> >
> > OK. This is clear to me now. It is like needing different Fortran compilers 
> > for different operating systems, but Fortran code does not need much 
> > modifications (except file names/paths, etc.).
> >
> 
> Something like that. There are a lot of little traps you can fall into
> (as you say, file names can be different, especially system ones) that
> stop your code from running correctly on all platforms, but porting a
> Python script from Linux to Windows or vice versa is a matter of
> testing it on the new platform and seeing what breaks, not completely
> rewriting it in a new language.
> 
> >> > Could someone kindly tell me advantages and disadvantages of Python?
> >>
> >> If you are completely satisfied with VB, there is no reason to change 
> >> (other than the enjoyable exercise of learning a new and more powerful 
> >> language).
> >>
> >
> > Will VB6 run on Windows 11? Or can I compile VB6 on Windows 11. We can't 
> > know. But there will be easy ways to run Python on any Windows version or 
> > Linux or whatever.
> >
> 
> There will indeed. That's the advantage of a fully open system - even
> if a nuclear meltdown kills all the Python core devs in one stroke (we
> really shouldn't have had PyCon Chernobyl), anyone in the world can
> pick up the source code and keep going with it. And Microsoft, despite
> having a strongly anti-freedom history, has come far more on board of
> recent years; as I understand it, Steve Dower has been spending
> company time improving Python (notably in the area of Windows
> installers and such). The future of open source software is pretty
> secure, and the future of openly-developed languages even more so,
> because CPython isn't the only way to run your Python code.
> 
> One Python advantage that you may or may not be aware of is its
> extensibility. To an extent that I haven't seen since working with
> REXX on OS/2, there is a thriving community building Python packages,
> many of which (about 75K!) are listed on PyPI [1]. Got this
> proprietary database that you need to get info from? Check PyPI -
> chances are someone's written a connector for it, so you can perform
> queries on it as if it had native support in the language. Once you
> install something using "pip" [2], you can import it into your script
> the exact same way that you would import something from the standard
> library - making PyPI kinda like the "extended library" for the
> language. T

Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Chris Angelico
On Thu, Feb 18, 2016 at 10:11 PM,   wrote:
> Almost everything points positively for Python. Thanks to all of you who have 
> responded. But please also tell me the disadvantages of Python. If I start 
> using Python, I should be aware of the price I am paying. Speed is not a big 
> problem for me, so an interpreted language is fine. Is packaging/installing 
> very messy? Do I create dozens of files for a simple program calculating the 
> sum of two numbers and product of two numbers in text boxes with one command 
> to be clicked? Can I learn this much in the first couple of hours?
>

There are a few warts, particularly on Windows, as regards packaging
and third-party modules. Anything that's written in pure Python is
fairly easy; stuff that's written in C is sometimes a bit hairy. But
that's a limitation on the "extended library" of PyPI, not the stuff
that comes with Python itself.

Your simple example could easily be a single file. Python tends to
eschew boilerplate; its motto comes from Baloo - look for the bare
necessities of life.

For a first couple of hours, I would recommend working at the console
or in Idle, rather than creating a GUI; a window takes a bit of extra
effort (plus you have choices in how to do that), so just learn the
language first. But you could easily advance to building a GUI within
your first day of learning Python, if that's the direction you want to
go.

The biggest disadvantage of Python is that, in a number of ways, it
surprises people. Significant whitespace bugs a lot of experienced
programmers (and some tools, too), and there are a few other ways that
you may find a team of people revile against it. But if you can deal
with the social aspects, it's a solid language.

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


pymysql question

2016-02-18 Thread tdsperth
Hi All

I have many mysql tables in a conversion I am doing - the table field names are 
a mixture of lower case and upper case - do I have to covert all to one case to 
over come Python not finding the field.

rows ocur.fetchall()
for row in rows:
print(row['newname']) 
#which fails because it is upper case in the table


Cheers

Colin


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


Re: Guido on python3 for beginners

2016-02-18 Thread Rustom Mody
On Thursday, February 18, 2016 at 12:17:26 PM UTC+5:30, Steven D'Aprano wrote:
> On Wednesday 17 February 2016 19:51, Rustom Mody wrote:
> 
> > I hope someone can help me find this link: There is some record that Guido
> > has said that python3 is probably a bit harder on noobs than python2.
> > 
> > Does anyone know/have that link?
> 
> 
> I can't say that I've seen it. I know that Raymond Hettinger is not too fond 
> of adding new syntactic features that add little in the way of power but 
> make the language harder to learn, but I don't recall anyone saying that it 
> is harder for newbies to get started with Python 3 than Python 2.
> 
> There are more features in Python 3, so in that trivial sense of "more to 
> learn", I suppose that it is objectively correct that it is harder to learn 
> than Python 2. But I don't think the learning curve is any steeper. If 
> anything, the learning curve is ever-so-slightly less steep.
> 
> 
Thanks Steven!
So its Raymond Hettinger... Good enough

So now I find your earlier post:
https://mail.python.org/pipermail/python-list/2015-March/688387.html

Obviously google was not obliging when I searched for Guido :-)

BTW I have no tongs in this 2 vs 3 fire -- I'll leave that to Rick jmf and other
noble gentry.

My beef is somewhat different: viz that post 70s (Pascal) and 80s (scheme) 
programming pedagogy has deteriorated with general purpose languages replacing
'teaching-purpose language' for teaching.

Which is about as intelligent as calling Martha[1] and Rose[2] both pianists

[1] https://www.youtube.com/watch?v=YLZLp6AcAi4
[2] https://www.youtube.com/watch?v=_bjKDJD-CLc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pymysql question

2016-02-18 Thread MRAB

On 2016-02-18 12:08, [email protected] wrote:

Hi All

I have many mysql tables in a conversion I am doing - the table field names are 
a mixture of lower case and upper case - do I have to covert all to one case to 
over come Python not finding the field.

rows ocur.fetchall()
for row in rows:
 print(row['newname'])
 #which fails because it is upper case in the table


According to this:

MySQL query to get column names?
http://stackoverflow.com/questions/4165195/mysql-query-to-get-column-names

it's possible to get the column names.

You could then build a dict to map a lowercase column name to an actual 
column name.


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


Re: extending PATH on Windows?

2016-02-18 Thread eryk sun
On Wed, Feb 17, 2016 at 6:53 PM, Dennis Lee Bieber
 wrote:
> On Wed, 17 Feb 2016 17:49:11 + (UTC), Ulli Horlacher
>  declaimed the following:
>
>>Thorsten Kampe  wrote:
>>
>>> By the way: there is a script called `win_add2path.py` in your Python
>>> distribution
>>
>>I have
>>"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
>>v.1500 32 bit (Intel)] on win32"
>>and there is no "win_add2path.py"
>>
> C:\Python_x64\Python27\Tools\scripts\win_add2path.py
>
> PythonWin 2.7.5 (default, Sep 16 2013, 23:11:01) [MSC v.1500 64 bit
> (AMD64)] on win32.
> Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for
> further copyright information.
>
> But I can't confirm that this is not something added in the ActiveState
> release.

It's here:
https://hg.python.org/cpython/file/v2.7.11/Tools/scripts/win_add2path.py

But there are a few issues with this script.

* A default value of u"%PATH%" is wrong. That causes the system
  PATH to be concatenated with itself.

* For the user scripts directory, replacing appdata with
  "%APPDATA%" causes os.path.isdir to always fail.

* For QueryValueEx, the only error it should handle is
  ERROR_FILE_NOT_FOUND. Other OS errors are unlikely, but they
  shouldn't be masked.

* In Python 2, the value returned by QueryValueEx is a unicode
  string, which this script assumes is ASCII only. So it could
  die on a UnicodeDecodeError.

* REG_EXPAND_SZ should only be used when '%' occurs 2 or more
  times. Otherwise use REG_SZ. This is important for two-pass
  environment variable expansion. Thus an existing REG_SZ type
  should be preserved, if that's reasonable, because the user may be
  reusing PATH in a  REG_EXPAND_SZ variable.

* It doesn't broadcast a WM_SETTINGCHANGE message, so it
  needlessly forces the user to log off and back on in order to
  use the modified PATH.

Here's a new version for Python 2. I generalized the shell-variable
replacement to a list of well-known folders.

import os
import sys
import site
import ctypes
import _winreg
import warnings

user32 = ctypes.WinDLL('user32', use_last_error=True)

HWND_BROADCAST = 0x
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
ERROR_FILE_NOT_FOUND = 0x0002
ERROR_TIMEOUT = 0x05B4
HKCU = _winreg.HKEY_CURRENT_USER

ENVIRONMENT = u"Environment"
PATH = u"PATH"
SCRIPTS = u"Scripts"

dir_vars = [u"%APPDATA%",
u"%LOCALAPPDATA%",
u"%USERPROFILE%",
u"%HOMEDRIVE%%HOMEPATH%",
u"%ProgramFiles%",
u"%ProgramFiles(x86)%"]

dir_vals = [_winreg.ExpandEnvironmentStrings(v) for v in dir_vars]

def broadcast_change(lparam):
if not user32.SendMessageTimeoutW(
HWND_BROADCAST, WM_SETTINGCHANGE,
0, ctypes.c_wchar_p(lparam),
SMTO_ABORTIFHUNG, 1000, None):
err = ctypes.get_last_error()
if err != ERROR_TIMEOUT:
raise ctypes.WinError(err)

def modify():
executable = sys.executable.decode("mbcs")
pythonpath = os.path.dirname(os.path.normpath(executable))
scripts = os.path.join(pythonpath, SCRIPTS)
if hasattr(site, "USER_SITE"):
userpath = site.USER_SITE.decode("mbcs")
userscripts = os.path.join(userpath, SCRIPTS)
else:
userscripts = None
with _winreg.CreateKey(HKCU, ENVIRONMENT) as key:
try:
envpath, dtype = _winreg.QueryValueEx(key, PATH)
except WindowsError as e:
if e.winerror != ERROR_FILE_NOT_FOUND:
raise
envpath, dtype = u"", _winreg.REG_EXPAND_SZ
if dtype not in (_winreg.REG_SZ, _winreg.REG_EXPAND_SZ):
raise TypeError(r"Existing PATH value is not a string.")
if dtype == _winreg.REG_SZ and envpath.count(u"%") > 1:
warnings.warn('Changing type to REG_EXPAND_SZ.')
dtype = _winreg.REG_EXPAND_SZ
paths = [envpath]
for path in (pythonpath, scripts, userscripts):
if path and path not in envpath and os.path.isdir(path):
if dtype == _winreg.REG_EXPAND_SZ:
for var, val in zip(dir_vars, dir_vals):
if val in path:
path = path.replace(val, var)
break
if path in envpath:
continue
paths.append(path)
envpath = os.pathsep.join(paths)
_winreg.SetValueEx(key, PATH, 0, dtype, envpath)
broadcast_change(ENVIRONMENT)
return paths, envpath

def main():
paths, envpath = modify()
if len(paths) > 1:
print "Path(s) added:"
print '\n'.join(paths[1:])
else:
print "No path was ad

EuroPython 2016: Call for Proposals

2016-02-18 Thread M.-A. Lemburg
We’re looking for proposals on every aspect of Python: programming
from novice to advanced levels, applications and frameworks, or how
you have been involved in introducing Python into your organization.
EuroPython is a community conference and we are eager to
hear about your experience.

Please also forward this Call for Proposals to anyone that you feel
may be interested.


 *** https://ep2016.europython.eu/en/call-for-proposals/ ***

   Submissions will be open until
   Sunday, March 6, 23:59:59 CET


For full details, please see the above CFP page. We have many exciting
things waiting for you:

* a PyData satellite event

* new formats (panels, interactive sessions)

* tracks to focus on more specific domains, including a
  revival of the EuroPython Business Track

* speaker discounts for more than just talks and trainings


Please note that we are using a shorter CFP period of just 2.5 weeks
this year, since we want to have the list of talks published sooner
than last year.


With gravitational regards,
--
EuroPython 2016 Team
http://ep2016.europython.eu/
http://www.europython-society.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread William Ray Wing

> On Feb 17, 2016, at 2:49 PM, [email protected] wrote:
> 
> I am mostly getting positive feedback for Python.
> 
> It seems Python is used more for web based applications. Is it equally fine 
> for creating stand-alone *.exe's? Can the same code be compiled to run on 
> Linux or Android or web-based?
> 
> Is it possible to create GUI elements with a good IDE? Can they be defined 
> like in Visual Basic with given sizes, fonts, visible/invisible, etc.?
> 
> Is it easy to do matrix operations in Python? Or do I need to write 
> subroutines like in Visual Basic?
> 
> Could someone kindly tell me advantages and disadvantages of Python? Or any 
> better options? I have like 40-50 VB Forms and may be around 2 lines of 
> code. It will be a task to learn a new language and translate/re-write that 
> code.
> 

At this point you’ve probably heard more than you wanted to *about* Python.  
The next step really ought to be simply to invest a few minutes in looking at 
the language itself.
Start here by downloading a copy of the Python interpreter:

https://www.python.org/downloads/windows/

Then, there is an extensive list of on-line tutorial material here:

https://wiki.python.org/moin/BeginnersGuide/Programmers

I’d recommend simply picking one and diving in. If you have questions (and you 
surely will), come back here or, at least initially, send them to the Python 
Tutor list ([email protected]).

Good luck and have fun,
Bill


> Thanks for your responses. 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


Question on keyword arguments

2016-02-18 Thread grsmith

Would this be the correct way to return
a list as a default result.

Also, would the list be the preferable result (to a python programmer) ?

def test(command, return_type='LIST'):
""" Go to database and return data"""
if return_type == 'LIST':
result = ['ONE', 'TWO', 'THREE']
else:
result = r'0xfeONE\0exfeTWO\0xfeTHREE'
return result

if __name__ == '__main__':
print(test('cmd'))
print(test('cmd', 'LIST'))
print(test('cmd', None))
print(test('cmd', 'string'))


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


Re: Question on keyword arguments

2016-02-18 Thread Peter Otten
[email protected] wrote:

> Would this be the correct way to return
> a list as a default result.

If it does what you want it to do it is "correct" as in "complies with 
specification".
 
> Also, would the list be the preferable result (to a python programmer) ?

A list as a return value is OK as is any other object, however,

> def test(command, return_type='LIST'):

passing the desired result type as an argument is usually not a good idea. 

> """ Go to database and return data"""
> if return_type == 'LIST':
> result = ['ONE', 'TWO', 'THREE']
> else:
> result = r'0xfeONE\0exfeTWO\0xfeTHREE'
> return result
> 
> if __name__ == '__main__':
> print(test('cmd'))
> print(test('cmd', 'LIST'))
> print(test('cmd', None))
> print(test('cmd', 'string'))

Make it separate functions instead:

def test(command):
return ["ONE", "TWO", "THREE"]

def test_as_string(command, sep=","):
return sep.join(test(command))

if __name__ == '__main__':
print(test("cmd"))
print(test_as_string("cmd"))


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


Re: Question on keyword arguments

2016-02-18 Thread Tim Chase
On 2016-02-18 09:00, [email protected] wrote:
> Would this be the correct way to return
> a list as a default result.
> 
> Also, would the list be the preferable result (to a python
> programmer) ?
> 
> def test(command, return_type='LIST'):
> """ Go to database and return data"""
> if return_type == 'LIST':
> result = ['ONE', 'TWO', 'THREE']
> else:
> result = r'0xfeONE\0exfeTWO\0xfeTHREE'

[I presume the "\0exfe" should just be "\0xfe" like the other two]

> return result
> 
> if __name__ == '__main__':
> print(test('cmd'))
> print(test('cmd', 'LIST'))
> print(test('cmd', None))
> print(test('cmd', 'string'))

The function should return "the most obvious way to do it".  In this
case, it appears that you should just always return a list.  If you
want to format it in your crazy-other-result format, create a utility
function to do that:

  def test(command):
return ['ONE', 'TWO', 'THREE']

  def grsmithify(lst):
return ''.join("\0xfe%s" % s for s in lst)

  print(test('cmd'))
  print(grsmithify(test('cmd')))

-tkc



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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Oscar Benjamin
On 18 February 2016 at 11:32, Chris Angelico  wrote:
> On Thu, Feb 18, 2016 at 10:11 PM,   wrote:
>> Almost everything points positively for Python. Thanks to all of you who 
>> have responded. But please also tell me the disadvantages of Python. If I 
>> start using Python, I should be aware of the price I am paying. Speed is not 
>> a big problem for me, so an interpreted language is fine. Is 
>> packaging/installing very messy? Do I create dozens of files for a simple 
>> program calculating the sum of two numbers and product of two numbers in 
>> text boxes with one command to be clicked? Can I learn this much in the 
>> first couple of hours?
>>
>
> There are a few warts, particularly on Windows, as regards packaging
> and third-party modules. Anything that's written in pure Python is
> fairly easy; stuff that's written in C is sometimes a bit hairy. But
> that's a limitation on the "extended library" of PyPI, not the stuff
> that comes with Python itself.

For packaging/installing it really depends on what you're trying to
do. You have to understand that Python is used in many very different
ways in different environments and ecosystems so there just isn't a
single way of doing it.

It sounds to me as if all of your needs can be solved in pure Python
code possibly using some of the popular extension modules from PyPI.
In this case it's actually very easy to package/install. You can
package your code simply by zipping it up with a __main__.py file.
Someone who wants to install it will simply have a two step process:
first install Python (and possibly a few dependencies) and then obtain
the zip file with your code in it.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
torstai 18. helmikuuta 2016 17.21.32 UTC+2 Oscar Benjamin kirjoitti:
> On 18 February 2016 at 11:32, Chris Angelico  wrote:
> > On Thu, Feb 18, 2016 at 10:11 PM,   wrote:
> >> Almost everything points positively for Python. Thanks to all of you who 
> >> have responded. But please also tell me the disadvantages of Python. If I 
> >> start using Python, I should be aware of the price I am paying. Speed is 
> >> not a big problem for me, so an interpreted language is fine. Is 
> >> packaging/installing very messy? Do I create dozens of files for a simple 
> >> program calculating the sum of two numbers and product of two numbers in 
> >> text boxes with one command to be clicked? Can I learn this much in the 
> >> first couple of hours?
> >>
> >
> > There are a few warts, particularly on Windows, as regards packaging
> > and third-party modules. Anything that's written in pure Python is
> > fairly easy; stuff that's written in C is sometimes a bit hairy. But
> > that's a limitation on the "extended library" of PyPI, not the stuff
> > that comes with Python itself.
> 
> For packaging/installing it really depends on what you're trying to
> do. You have to understand that Python is used in many very different
> ways in different environments and ecosystems so there just isn't a
> single way of doing it.
> 
> It sounds to me as if all of your needs can be solved in pure Python
> code possibly using some of the popular extension modules from PyPI.
> In this case it's actually very easy to package/install. You can
> package your code simply by zipping it up with a __main__.py file.
> Someone who wants to install it will simply have a two step process:
> first install Python (and possibly a few dependencies) and then obtain
> the zip file with your code in it.
> 
> --
> Oscar

This form of packing is not desirable. I can't ask other people to install 
Python on their machines, and I also would not want show most of the code doing 
the calculations.

Another question I have is regarding reading numerical data from text files. Is 
it necessary to read one character at a time, or can one read like in Fortran 
and Basic (something like Input #5, X1, X2, X3)?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
torstai 18. helmikuuta 2016 16.08.05 UTC+2 William Ray Wing kirjoitti:
> > On Feb 17, 2016, at 2:49 PM, [email protected] wrote:
> > 
> > I am mostly getting positive feedback for Python.
> > 
> > It seems Python is used more for web based applications. Is it equally fine 
> > for creating stand-alone *.exe's? Can the same code be compiled to run on 
> > Linux or Android or web-based?
> > 
> > Is it possible to create GUI elements with a good IDE? Can they be defined 
> > like in Visual Basic with given sizes, fonts, visible/invisible, etc.?
> > 
> > Is it easy to do matrix operations in Python? Or do I need to write 
> > subroutines like in Visual Basic?
> > 
> > Could someone kindly tell me advantages and disadvantages of Python? Or any 
> > better options? I have like 40-50 VB Forms and may be around 2 lines of 
> > code. It will be a task to learn a new language and translate/re-write that 
> > code.
> > 
> 
> At this point you've probably heard more than you wanted to *about* Python.  
> The next step really ought to be simply to invest a few minutes in looking at 
> the language itself.
> Start here by downloading a copy of the Python interpreter:
> 
>   https://www.python.org/downloads/windows/
> 
> Then, there is an extensive list of on-line tutorial material here:
> 
>   https://wiki.python.org/moin/BeginnersGuide/Programmers
> 
> I'd recommend simply picking one and diving in. If you have questions (and 
> you surely will), come back here or, at least initially, send them to the 
> Python Tutor list ([email protected]).
> 
> Good luck and have fun,
> Bill
> 
> 
> > Thanks for your responses. 
> > -- 
> > https://mail.python.org/mailman/listinfo/python-list

I am almost eager to do this but want to be sure that I know the pitfalls in 
using Python for my purposes. Thanks for your encouraging response.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Question on keyword arguments

2016-02-18 Thread Dan Strohl
I have approached this in a few different ways, depending on the use case.

I have done the "return_type=list" before, though I don't really like it... 
it's too easy to forget or mistype the exact name used for the switch.  If you 
do this, I also recommend setting some class or module variables to the text 
strings and pass those back and forth.

I have also returned a different type depending on what is being requested... 
so, if the function user requests data that has multiple objects, return a 
list, if they request something that has just one object, return that object.  
This also has potential problems if the number of returned objects is not 
consistently predictable, you would have to always test your returned object to 
see how to handle it.

I like the other suggestions thrown out as well, (having multiple methods and 
having one method and a converting function).. They are good, easy to read and 
use methods as long as you know at design time what type of object you want 
(which is probably the norm).

Another approach that I like (where it makes sense) is to return another 
(custom) object that can act like either... that way, you have the content in 
hand and can use it either way.  This approach works well when there is a high 
overhead in creating the data, that you don't want to have to do again, and you 
don't mind having a few more objects hanging around until cleaned up.

So, define a return object like:

from collections import UserList
class TestResponse(UserList):
def __str__(self):
return '\0xfe%s' % '\0xfe'.join(self.data)

...and return that object.

that way, you can iterate over it, treat it as a list, or whatever, or if you 
do print(str(TestResponse)), you get your r'0xfeONE\0exfeTWO\0xfeTHREE'

In the end, your decision should be made based on:
1.  What would the developer using this EXPECT to get back? (if the user 
normally expects one or the other, do that, if this is for a "public module", I 
would expect the list is more likely the common response.  This list is 
probably not the right place for that question though, unless this is a very 
general utility, you want to ask the people coding in the domain that would 
mostly be using your function.)

2.  What is the most likely response type? (if it is common to get it back 
different ways, or use it multiple times, this is probably mostly the same as 
#1, but can be different)

3.  What will be the easiest to read and document?  Returning a list is easy to 
read and expectable, but not if you have to then jump through some loops to 
convert it to something else immediately.

4.  Is there a large enough benefit in processing that you want to be able to 
use it multiple ways without having to regenerate the list.  (note that this is 
the last criteria, unless performance is really critical, readability and 
predictability is normally much more important than what is probably minor 
performance tuning.)

Dan Strohl


> -Original Message-
> From: Python-list [mailto:[email protected]] On
> Behalf Of Peter Otten
> Sent: Thursday, February 18, 2016 6:37 AM
> To: [email protected]
> Subject: Re: Question on keyword arguments
> 
> [email protected] wrote:
> 
> > Would this be the correct way to return a list as a default result.
> 
> If it does what you want it to do it is "correct" as in "complies with
> specification".
> 
> > Also, would the list be the preferable result (to a python programmer) ?
> 
> A list as a return value is OK as is any other object, however,
> 
> > def test(command, return_type='LIST'):
> 
> passing the desired result type as an argument is usually not a good idea.
> 
> > """ Go to database and return data"""
> > if return_type == 'LIST':
> > result = ['ONE', 'TWO', 'THREE']
> > else:
> > result = r'0xfeONE\0exfeTWO\0xfeTHREE'
> > return result
> >
> > if __name__ == '__main__':
> > print(test('cmd'))
> > print(test('cmd', 'LIST'))
> > print(test('cmd', None))
> > print(test('cmd', 'string'))
> 
> Make it separate functions instead:
> 
> def test(command):
> return ["ONE", "TWO", "THREE"]
> 
> def test_as_string(command, sep=","):
> return sep.join(test(command))
> 
> if __name__ == '__main__':
> print(test("cmd"))
> print(test_as_string("cmd"))
> 
> 
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: not all arguments converted during string formatting

2016-02-18 Thread Ganesh Pal
On Wed, Feb 17, 2016 at 7:32 PM, Chris Angelico  wrote:

> The print statement/function happily accepts multiple arguments, and
> will join them according to a set of predefined rules. The logging
> functions don't have those rules, so they take one message and some
> optional parameters. Try this, instead:
>
> logging.info("%r %r %r", out, err, ret)
>

Thanks this solved my issue :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question on keyword arguments

2016-02-18 Thread Chris Angelico
On Fri, Feb 19, 2016 at 2:39 AM, Dan Strohl  wrote:
> So, define a return object like:
>
> from collections import UserList
> class TestResponse(UserList):
> def __str__(self):
> return '\0xfe%s' % '\0xfe'.join(self.data)
>
> ...and return that object.

Out of interest, why UserList rather than simply subclassing list?

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Oscar Benjamin
On 18 February 2016 at 15:33,   wrote:
>> It sounds to me as if all of your needs can be solved in pure Python
>> code possibly using some of the popular extension modules from PyPI.
>> In this case it's actually very easy to package/install. You can
>> package your code simply by zipping it up with a __main__.py file.
>> Someone who wants to install it will simply have a two step process:
>> first install Python (and possibly a few dependencies) and then obtain
>> the zip file with your code in it.
>
> This form of packing is not desirable. I can't ask other people to install 
> Python on their machines, and I also would not want show most of the code 
> doing the calculations.

This is what sometimes makes packaging Python apps difficult.
Distributing code as a zip file is easy and works out of the box.
However a lot of people are very insistent that asking the end user to
first install Python is unacceptable. That's why I said it depends
what you're trying to do. I guess from your description that you want
other people to be able to install and use your proprietary
applications on whatever OS they're using.

You would probably want to use something like pyinstaller then as this
bundles a Python interpreter with your code. For Windows there's also
the embedded Python distribution which you can ship as part of an
installer for your program. For OSX/Linux Python is most likely
already installed so this may be unnecessary.

In terms of hiding the code doing the calculations: it doesn't work
like that in Python. The code is not compiled so if the end user has
your app then they have your code. You could probably use something
like Cython to obfuscate it but then this means that your compiled
code is architecture/platform dependent so you need to compile it
separately for each platform and there are other problems.

> Another question I have is regarding reading numerical data from text files. 
> Is it necessary to read one character at a time, or can one read like in 
> Fortran and Basic (something like Input #5, X1, X2, X3)?

There are loads of ways to read your data in from text files. I don't
know how it works in Fortran and Basic but I'm sure there will be
something that does what you want.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
On Thursday, 18 February 2016 13:32:58 UTC+2, Chris Angelico  wrote:
> On Thu, Feb 18, 2016 at 10:11 PM,   wrote:
> > Almost everything points positively for Python. Thanks to all of you who 
> > have responded. But please also tell me the disadvantages of Python. If I 
> > start using Python, I should be aware of the price I am paying. Speed is 
> > not a big problem for me, so an interpreted language is fine. Is 
> > packaging/installing very messy? Do I create dozens of files for a simple 
> > program calculating the sum of two numbers and product of two numbers in 
> > text boxes with one command to be clicked? Can I learn this much in the 
> > first couple of hours?
> >
> 
> There are a few warts, particularly on Windows, as regards packaging
> and third-party modules. Anything that's written in pure Python is
> fairly easy; stuff that's written in C is sometimes a bit hairy. But
> that's a limitation on the "extended library" of PyPI, not the stuff
> that comes with Python itself.
> 
> Your simple example could easily be a single file. Python tends to
> eschew boilerplate; its motto comes from Baloo - look for the bare
> necessities of life.
> 
> For a first couple of hours, I would recommend working at the console
> or in Idle, rather than creating a GUI; a window takes a bit of extra
> effort (plus you have choices in how to do that), so just learn the
> language first. But you could easily advance to building a GUI within
> your first day of learning Python, if that's the direction you want to
> go.
> 
> The biggest disadvantage of Python is that, in a number of ways, it
> surprises people. Significant whitespace bugs a lot of experienced
> programmers (and some tools, too), and there are a few other ways that
> you may find a team of people revile against it. But if you can deal
> with the social aspects, it's a solid language.
> 
> ChrisA

Thanks. You have guided me quite well, and I am almost ready to declare that I 
will use Python for the next few decades.

Imagine I want to read in two (or a few) numbers from a text file, display them 
in two (or more) text boxes, calculate their sums and products, may be take 
logarithms of them, and display them in other two text boxes or labels, and 
make some bar charts, scatter plots, and later draw curves and surfaces on a 
computer screen. Do I really need PyPi or other external stuff for this? Is 
Python well equipped for this?

I will have to learn GUI creating quickly after I know the basics of reading 
and writing text files, and doing simple mathematical calculations.

Later I can imagine using things like sending an SMS from a phone running this 
on Android, or placing a graph in a WhatsApp message, make a call to someone 
and tell him the temperature is now too high, etc. These things might need 
external libraries, but I can learn this later on.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido on python3 for beginners

2016-02-18 Thread Random832
On Thu, Feb 18, 2016, at 07:25, Rustom Mody wrote:
> My beef is somewhat different: viz that post 70s (Pascal) and 80s
> (scheme) 
> programming pedagogy has deteriorated with general purpose languages
> replacing
> 'teaching-purpose language' for teaching.

The flaw in this idea is right there in your post. Both languages you
named are strongly tied to a single paradigm (procedural for Pascal, and
functional for Scheme) which don't match the paradigm that real-world
work is done in. Is there a new "teaching-purpose language"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question on keyword arguments

2016-02-18 Thread grsmith
Thanks to all who responded, it is a big help. 


Tim, the 'crazy-other-result format' is the
result returned by the database, nothing
I can do about that :)

Thanks again
George

-Original Message- 
From: Chris Angelico 
Sent: Thursday, February 18, 2016 10:45 AM 
Cc: [email protected] 
Subject: Re: Question on keyword arguments 


On Fri, Feb 19, 2016 at 2:39 AM, Dan Strohl  wrote:

So, define a return object like:

from collections import UserList
class TestResponse(UserList):
def __str__(self):
return '\0xfe%s' % '\0xfe'.join(self.data)

...and return that object.


Out of interest, why UserList rather than simply subclassing list?

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread William Ray Wing

> On Feb 18, 2016, at 10:33 AM, [email protected] wrote:
> 
> torstai 18. helmikuuta 2016 17.21.32 UTC+2 Oscar Benjamin kirjoitti:
>> On 18 February 2016 at 11:32, Chris Angelico  wrote:
>> 

[byte]

>> It sounds to me as if all of your needs can be solved in pure Python
>> code possibly using some of the popular extension modules from PyPI.
>> In this case it's actually very easy to package/install. You can
>> package your code simply by zipping it up with a __main__.py file.
>> Someone who wants to install it will simply have a two step process:
>> first install Python (and possibly a few dependencies) and then obtain
>> the zip file with your code in it.
>> 
>> --
>> Oscar
> 
> This form of packing is not desirable. I can't ask other people to install 
> Python on their machines, and I also would not want show most of the code 
> doing the calculations.
> 

Now things get tricky.  I can understand you not wanting to force people to 
pre-install Python in order for your code to run, but just how deeply do you 
want to hide or obfuscate it?  Is this potentially a commercial application to 
be sold, or are you simply trying to keep things clean and tidy within various 
divisions of your company.  I’d hope not the former, because even VB can get 
you into tricky licensing issues (and in any case - even fully compiled code in 
any language these days can be de-compiled into logically correct source code, 
although with less than obvious variable names).  At the other extreme, there 
are packaging programs (py2exe comes to mind, although I have no experience 
with it).  These wrap the whole python interpreter, your code, and any needed 
libraries into an executable (clickable) package.  Their only downside is that 
the output packages they produce tend to be large.  However, any sophisticated 
user who digs into them WILL be able to find your source code, possibly only 
slightly obfuscated by being zipped.

> Another question I have is regarding reading numerical data from text files. 
> Is it necessary to read one character at a time, or can one read like in 
> Fortran and Basic (something like Input #5, X1, X2, X3)?

Python can read lines of text or whole blocks of text from source files.  If 
those files are in more or less well-understood form (csv for example) it has 
libraries specifically designed for reading and extracting data from them 
(including VERY nice facilities for doing arithmetic and otherwise manipulating 
time and date data).

Bill

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

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


RE: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Dan Strohl
Disadvantages of python... (compared to VB)

That's a hard one, but here are my thoughts:  (keep in mind that these kinds of 
discussions are subjective and much is based on the background and experience 
of the coder, these are also assuming that 100% of your audience is on windows, 
as soon as you start talking about cross platform support, VB gets much harder 
to use (yes, you could use it on Linus, via a web based app, or an emulator if 
you HAD to).

- I find that VB is much easier at making quick GUI apps (for windows).

- VB is easier to integrate with office apps and other windows specific things 
(there are some python modules that will access office files etc, but if you 
want to have an engineering app that directly integrates / interacts with 
excel, VB is probably better.

- I find VB is easier to package and distribute.  (there are some good 
utilities that will take Python and package it into an exe, along with all of 
the needed pieces, interpreter, etc, but those all require some level of work 
to setup and make work... not a lot sometimes, but certainly more than "click 
compile" and copy the .exe file.

- VB is often, for simple apps, often simpler to learn for non-programmers.  (I 
know I will get slammed for that one).  For complex apps, I find VB harder to 
do things than Python, but for example, if I wanted to make a quick windows 
calculator, I would probably go to VB first.)

My approach is generally:

I use Python for:
- server apps, web based apps, plugins, modules, library development, or apps 
that I want to be able to expand later with plugins, console apps and utilities 
(things that I am only going to run from the CLI anyway),  performance focused 
apps (unless I need to go all the way to C for performance), anything that 
might ever need to be cross platform, apps that interact with other 
(non-Microsoft) apps.

I use VB for:
Quick user focused, non-web apps, apps that are used in or directly with 
Microsoft Office apps, apps that I am developing for someone else that is a VB 
programmer (or non-programmer but might poke at them).. apps that I need to 
distribute to lots of less controlled workstations that don't have python on 
them already.

These days, I find that I am using VB much less than Python, most of the 
reasons that I would pick VB can be overcome by developing a cloud app instead 
of a local app, but there are still times that VB is the right tool (for me at 
least).





> -Original Message-
> From: Python-list [mailto:[email protected]] On
> Behalf Of [email protected]
> Sent: Thursday, February 18, 2016 7:33 AM
> To: [email protected]
> Subject: Re: Considering migrating to Python from Visual Basic 6 for 
> engineering
> applications
> 
> torstai 18. helmikuuta 2016 17.21.32 UTC+2 Oscar Benjamin kirjoitti:
> > On 18 February 2016 at 11:32, Chris Angelico  wrote:
> > > On Thu, Feb 18, 2016 at 10:11 PM,   wrote:
> > >> Almost everything points positively for Python. Thanks to all of you who
> have responded. But please also tell me the disadvantages of Python. If I 
> start
> using Python, I should be aware of the price I am paying. Speed is not a big
> problem for me, so an interpreted language is fine. Is packaging/installing 
> very
> messy? Do I create dozens of files for a simple program calculating the sum of
> two numbers and product of two numbers in text boxes with one command to
> be clicked? Can I learn this much in the first couple of hours?
> > >>
> > >
> > > There are a few warts, particularly on Windows, as regards packaging
> > > and third-party modules. Anything that's written in pure Python is
> > > fairly easy; stuff that's written in C is sometimes a bit hairy. But
> > > that's a limitation on the "extended library" of PyPI, not the stuff
> > > that comes with Python itself.
> >
> > For packaging/installing it really depends on what you're trying to
> > do. You have to understand that Python is used in many very different
> > ways in different environments and ecosystems so there just isn't a
> > single way of doing it.
> >
> > It sounds to me as if all of your needs can be solved in pure Python
> > code possibly using some of the popular extension modules from PyPI.
> > In this case it's actually very easy to package/install. You can
> > package your code simply by zipping it up with a __main__.py file.
> > Someone who wants to install it will simply have a two step process:
> > first install Python (and possibly a few dependencies) and then obtain
> > the zip file with your code in it.
> >
> > --
> > Oscar
> 
> This form of packing is not desirable. I can't ask other people to install 
> Python on
> their machines, and I also would not want show most of the code doing the
> calculations.
> 
> Another question I have is regarding reading numerical data from text files. 
> Is it
> necessary to read one character at a time, or can one read like in Fortran and
> Basic (something like Input #5

Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Chris Angelico
On Fri, Feb 19, 2016 at 2:49 AM,   wrote:
> Thanks. You have guided me quite well, and I am almost ready to declare that 
> I will use Python for the next few decades.
>

Don't declare like that - just start using it, and see what you think
:) But I would be very much surprised if Python doesn't get added to
your toolbelt. A good programmer should always keep a selection of
tools handy - seldom is one tool the right one for every job.

> Imagine I want to read in two (or a few) numbers from a text file, display 
> them in two (or more) text boxes, calculate their sums and products, may be 
> take logarithms of them, and display them in other two text boxes or labels, 
> and make some bar charts, scatter plots, and later draw curves and surfaces 
> on a computer screen. Do I really need PyPi or other external stuff for this? 
> Is Python well equipped for this?
>

You could do all of that with just the standard library, but then your
only choice of GUI library is Tkinter, which is derived from Tcl/Tk.
If you don't like how that looks (either in your code, or in the
resulting GUI), you'll need to turn to PyPI for an alternative (eg
something derived from GTK or wxWindows or Qt). I'm not sure how the
graphing capabilities of Tkinter are, so you might want to grab
matplotlib too - again, it'll give you a lot more flexibility than you
would have if you restrict yourself to *just* the standard library.
But I think you could do all of that - certainly most of it - with
just the language and standard library.

> I will have to learn GUI creating quickly after I know the basics of reading 
> and writing text files, and doing simple mathematical calculations.
>

Reading and writing text files is easy, as is basic mathematics.
You'll have that down in an hour or two, most likely, and then you'll
have time to play GUIs.

> Later I can imagine using things like sending an SMS from a phone running 
> this on Android, or placing a graph in a WhatsApp message, make a call to 
> someone and tell him the temperature is now too high, etc. These things might 
> need external libraries, but I can learn this later on.
>

Those things will most likely require external libraries. But most of
them are probably possible.

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


RE: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Dan Strohl
I totally agree with Chris here, try it out, do some simpler things to get your 
feet wet before committing to redoing hundreds of thousands of lines of code in 
it.  Find a few of the "deal breakers" and try to solve them in Python (create 
a hello world app in python, then package it in an exe and distribute it to 
some friends).. VB is a fine language, and is likely to suit your needs as 
well... even if we all believe that Python is better, the effort to convert 
from one to the other may not make sense.

I would also suggest taking a few steps back and seeing if there is a different 
overall architectural approach that makes sense.  If you are using a heavy 
weight local app, what about a web app?  What about doing a combination 
approach?  Have a back end running on a server with Python, that feeds a VB app 
on a client for displaying and manipulating data? (then a Java app for mobile 
clients or Linux ones?)

Also, looking at existing frameworks and expandable apps out there that you 
might be able to do less work but still meet your goals with because 80% of the 
work was done for you... things like django, splunk, tableau, etc...

Dan


> -Original Message-
> From: Python-list [mailto:[email protected]] On
> Behalf Of Chris Angelico
> Sent: Thursday, February 18, 2016 8:06 AM
> Cc: [email protected]
> Subject: Re: Considering migrating to Python from Visual Basic 6 for 
> engineering
> applications
> 
> On Fri, Feb 19, 2016 at 2:49 AM,   wrote:
> > Thanks. You have guided me quite well, and I am almost ready to declare 
> > that I
> will use Python for the next few decades.
> >
> 
> Don't declare like that - just start using it, and see what you think
> :) But I would be very much surprised if Python doesn't get added to your
> toolbelt. A good programmer should always keep a selection of tools handy -
> seldom is one tool the right one for every job.
> 
> > Imagine I want to read in two (or a few) numbers from a text file, display 
> > them
> in two (or more) text boxes, calculate their sums and products, may be take
> logarithms of them, and display them in other two text boxes or labels, and
> make some bar charts, scatter plots, and later draw curves and surfaces on a
> computer screen. Do I really need PyPi or other external stuff for this? Is 
> Python
> well equipped for this?
> >
> 
> You could do all of that with just the standard library, but then your only 
> choice
> of GUI library is Tkinter, which is derived from Tcl/Tk.
> If you don't like how that looks (either in your code, or in the resulting 
> GUI),
> you'll need to turn to PyPI for an alternative (eg something derived from GTK 
> or
> wxWindows or Qt). I'm not sure how the graphing capabilities of Tkinter are, 
> so
> you might want to grab matplotlib too - again, it'll give you a lot more 
> flexibility
> than you would have if you restrict yourself to *just* the standard library.
> But I think you could do all of that - certainly most of it - with just the 
> language
> and standard library.
> 
> > I will have to learn GUI creating quickly after I know the basics of 
> > reading and
> writing text files, and doing simple mathematical calculations.
> >
> 
> Reading and writing text files is easy, as is basic mathematics.
> You'll have that down in an hour or two, most likely, and then you'll have 
> time to
> play GUIs.
> 
> > Later I can imagine using things like sending an SMS from a phone running 
> > this
> on Android, or placing a graph in a WhatsApp message, make a call to someone
> and tell him the temperature is now too high, etc. These things might need
> external libraries, but I can learn this later on.
> >
> 
> Those things will most likely require external libraries. But most of them are
> probably possible.
> 
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
Dennis Lee Bieber  wrote:

> >I have 
> >"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
> >v.1500 32 bit (Intel)] on win32"
> >and there is no "win_add2path.py"
> >
> C:\Python_x64\Python27\Tools\scripts\win_add2path.py

Ok, It is here in C:\Python27\Tools\scripts\win_add2path.py
but windows "Search programs and files" was not able to find it.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: [email protected]
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido on python3 for beginners

2016-02-18 Thread Matt Wheeler
On Thu, 18 Feb 2016 11:07 Chris Angelico  wrote:

> By the way... For bash users, adding this to .bashrc may make venvs a
> bit easier to keep straight:
>
> checkdir() {
> [ -n "$VIRTUAL_ENV" ] && ! [[ `pwd` =~ `dirname $VIRTUAL_ENV`* ]]
> && echo Deactivating venv $VIRTUAL_ENV... && deactivate
> [ -z "$VIRTUAL_ENV" -a -d env ] && echo Activating venv
> `pwd`/env... && source env/bin/activate
> }
> PROMPT_COMMAND=checkdir
>
> (I'm more fluent in Python than in bash, so this is a bit ugly.)
>
> As soon as you change out of the directory that contains your venv,
> it'll be deactivated, so you can't accidentally run stuff in the
> "wrong" environment. And as soon as you change into a directory that
> contains an 'env' subdir, it'll activate it. (Also applies on first
> creation; as soon as "python3 -m venv env" returns, this will activate
> the env.)
>

This is a bad idea for the same reason enabling all magic comments in your
editor is a bad idea.
(rvm does this but confirms that the rvmrc it's about to activate is one
that you've previously approved, I wouldn't want to try to write a shell
function that did that though :)).

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


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
eryk sun  wrote:


> https://hg.python.org/cpython/file/v2.7.11/Tools/scripts/win_add2path.py
> 
> But there are a few issues with this script.

(... lot of flaws ...)

> Here's a new version for Python 2. I generalized the shell-variable
> replacement to a list of well-known folders.

Great script, I will save it for later usage!

But in the meantime I came to another solution:
Instead of modifying PATH systemwide, I modify it only for cmd.exe.

To achieve this, I set the registry key
"HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun"
to "%USERPROFILE%\autorun.cmd" and write in this file:
set PATH=%PATH%;%USERPROFILE%\Desktop

If there was already an old value in
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
it will be saved to %USERPROFILE%\autorun.cmd, too

This autorun.cmd is like .bashrc on UNIX.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: [email protected]
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
Ulli Horlacher  wrote:

> > but simpler still and more reliable to just call QueryValueEx.
> 
> I find it more complicated.

I have now (after long studying docs and examples)::

def get_winreg(key,subkey):
  try:
rkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,key,0,winreg.KEY_READ)
rvalue,rtype = winreg.QueryValueEx(rkey,subkey)
winreg.CloseKey(rkey)
  except WindowsError:
rvalue,rtype = None,None
  return rvalue


def set_winreg(key,subkey,value):
  winreg.CreateKey(winreg.HKEY_CURRENT_USER,key)
  rkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,key,0,winreg.KEY_WRITE)
  winreg.SetValueEx(rkey,subkey,0,winreg.REG_SZ,value)
  winreg.CloseKey(rkey)

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: [email protected]
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
On Thursday, 18 February 2016 17:59:59 UTC+2, William Ray Wing  wrote:
> > On Feb 18, 2016, at 10:33 AM, [email protected] wrote:
> > 
> > torstai 18. helmikuuta 2016 17.21.32 UTC+2 Oscar Benjamin kirjoitti:
> >> On 18 February 2016 at 11:32, Chris Angelico  wrote:
> >> 
> 
> [byte]
> 
> >> It sounds to me as if all of your needs can be solved in pure Python
> >> code possibly using some of the popular extension modules from PyPI.
> >> In this case it's actually very easy to package/install. You can
> >> package your code simply by zipping it up with a __main__.py file.
> >> Someone who wants to install it will simply have a two step process:
> >> first install Python (and possibly a few dependencies) and then obtain
> >> the zip file with your code in it.
> >> 
> >> --
> >> Oscar
> > 
> > This form of packing is not desirable. I can't ask other people to install 
> > Python on their machines, and I also would not want show most of the code 
> > doing the calculations.
> > 
> 
> Now things get tricky.  I can understand you not wanting to force people to 
> pre-install Python in order for your code to run, but just how deeply do you 
> want to hide or obfuscate it? 

I don't have to hide it very carefully. If it creates machine code which can be 
decompiled, I am not very bothered, but I do not want to show many of the 
equations I will embed in the code, very openly. These will be different for 
different people, so nobody will have much motivation to break open the code. 
One *.exe is likely to be used by 2 or 3 people, and then for someone else, I 
would create another very similar *.exe with somewhat different equations. This 
is just one of the things I intend to do. Then there are several calculation 
and plotting routines for my work, which won't be given to anyone, where the 
issue of secrecy does not arise.

> Is this potentially a commercial application to be sold, or are you simply 
> trying to keep things clean and tidy within various divisions of your 
> company.  I'd hope not the former, because even VB can get you into tricky 
> licensing issues (and in any case - even fully compiled code in any language 
> these days can be de-compiled into logically correct source code, although 
> with less than obvious variable names). 

Decompiling machine code I am not at all worried about. The decompiled code 
will be too messy for people to study. (I won't be writing simple algebraic 
equations in one or two lines.)

> At the other extreme, there are packaging programs (py2exe comes to mind, 
> although I have no experience with it).  These wrap the whole python 
> interpreter, your code, and any needed libraries into an executable 
> (clickable) package.  Their only downside is that the output packages they 
> produce tend to be large.  However, any sophisticated user who digs into them 
> WILL be able to find your source code, possibly only slightly obfuscated by 
> being zipped.
> 

This is not good if the source code with actual variable names becomes visible. 
Then I would have to use misleading variable names, and call temperature a flow 
rate, and pressure a magnetic field; stuff a lot of matrix equations which do 
nothing but get the decoders to waste a huge amount of time.

> > Another question I have is regarding reading numerical data from text 
> > files. Is it necessary to read one character at a time, or can one read 
> > like in Fortran and Basic (something like Input #5, X1, X2, X3)?
> 
> Python can read lines of text or whole blocks of text from source files.  If 
> those files are in more or less well-understood form (csv for example) it has 
> libraries specifically designed for reading and extracting data from them 
> (including VERY nice facilities for doing arithmetic and otherwise 
> manipulating time and date data).
> 

That is good. VB.net also has, but in the beginning I got the impression that 
you could read only one character as a time in a stream.

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

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


Re: How to properly override the default factory of defaultdict?

2016-02-18 Thread Herman
d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
self.assertEqual("apple", d['apple'])

From: Ben Finney 
>
> you are using the inheritance hierarchy but thwarting it by not using
> ‘super’. Instead::
>
> super().__init__(self, default_factory, *a, **kw)
>
> and::
>
> super().__getitem__(self, key)
> --
>  \   "Those who will not reason, are bigots, those who cannot, are |
>   `\fools, and those who dare not, are slaves." —“Lord” George |
> _o__)Gordon Noel Byron |
> Ben Finney

super does not work for defaultdict. I am using python 2.7. If I use
super(defaultdict, self).__init__(default_factory, *a, **kw), I get the
error:

super(defaultdict, self).__init__(default_factory, *a, **kw)
TypeError: 'function' object is not iterable

My use case is:
d = dictutil.DefaultDictWithEnhancedFactory(lambda k: k)
self.assertEqual("apple", d['apple'])


> From: Chris Angelico 
>
> Save yourself a lot of trouble, and just override __missing__:
>
> class DefaultDictWithEnhancedFactory(collections.defaultdict):
> def __missing__(self, key):
> return self.default_factory(key)
>
> ChrisA
>
This works! Thanks.

From: "Steven D'Aprano" 
> > I want to pass in the key to the default_factory of defaultdict
>
> Just use a regular dict and define __missing__:
>
> class MyDefaultDict(dict):
> def __missing__(self, key):
> return "We gotcha key %r right here!" % key
>
>
> If you want a per-instance __missing__, do something like this:
>
>
> class MyDefaultDict(dict):
> def __init__(self, factory):
> self._factory = factory
> def __missing__(self, key):
> return self._factory(self, key)
>
>
> d = MyDefaultDict(lambda self, key: ...)
>
>
> --
> Steve
>
Look like inheriting from defaultdict is easier. I don't even  have to
override the constructor as suggested by Chris Angelico above. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
On Thursday, 18 February 2016 18:01:17 UTC+2, Dan Strohl  wrote:
> Disadvantages of python... (compared to VB)
> 
> That's a hard one, but here are my thoughts:  (keep in mind that these kinds 
> of discussions are subjective and much is based on the background and 
> experience of the coder, these are also assuming that 100% of your audience 
> is on windows, as soon as you start talking about cross platform support, VB 
> gets much harder to use (yes, you could use it on Linus, via a web based app, 
> or an emulator if you HAD to).
> 
> - I find that VB is much easier at making quick GUI apps (for windows).

Yes, and I have used it for about 20 years. VB2 was wonderful for my work. VB3 
was fine. VB6 is also OK, but VB.net is too bloated. But can I count on using 
VB6 for the next five years? Or more?

> 
> - VB is easier to integrate with office apps and other windows specific 
> things (there are some python modules that will access office files etc, but 
> if you want to have an engineering app that directly integrates / interacts 
> with excel, VB is probably better.
> 

Python will read *.csv, and that will be enough. I guess writing *.csv will 
also be easy.

> - I find VB is easier to package and distribute.  (there are some good 
> utilities that will take Python and package it into an exe, along with all of 
> the needed pieces, interpreter, etc, but those all require some level of work 
> to setup and make work... not a lot sometimes, but certainly more than "click 
> compile" and copy the .exe file.
> 

Is Python packaging a lot more complicated than VB.net?

> - VB is often, for simple apps, often simpler to learn for non-programmers.  
> (I know I will get slammed for that one).  For complex apps, I find VB harder 
> to do things than Python, but for example, if I wanted to make a quick 
> windows calculator, I would probably go to VB first.)
> 
> My approach is generally:
> 
> I use Python for:
> - server apps, web based apps, plugins, modules, library development, or apps 
> that I want to be able to expand later with plugins, console apps and 
> utilities (things that I am only going to run from the CLI anyway),  
> performance focused apps (unless I need to go all the way to C for 
> performance), anything that might ever need to be cross platform, apps that 
> interact with other (non-Microsoft) apps.
> 

For me, none of these things are very interesting.

> I use VB for:
> Quick user focused, non-web apps, apps that are used in or directly with 
> Microsoft Office apps, apps that I am developing for someone else that is a 
> VB programmer (or non-programmer but might poke at them).. apps that I need 
> to distribute to lots of less controlled workstations that don't have python 
> on them already.
> 
> These days, I find that I am using VB much less than Python, most of the 
> reasons that I would pick VB can be overcome by developing a cloud app 
> instead of a local app, but there are still times that VB is the right tool 
> (for me at least).
> 

But how long can I continue to use VB6?

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
On Thursday, 18 February 2016 18:06:29 UTC+2, Chris Angelico  wrote:
> On Fri, Feb 19, 2016 at 2:49 AM,   wrote:
> > Thanks. You have guided me quite well, and I am almost ready to declare 
> > that I will use Python for the next few decades.
> >
> 
> Don't declare like that - just start using it, and see what you think
> :) But I would be very much surprised if Python doesn't get added to
> your toolbelt. A good programmer should always keep a selection of
> tools handy - seldom is one tool the right one for every job.
> 
> > Imagine I want to read in two (or a few) numbers from a text file, display 
> > them in two (or more) text boxes, calculate their sums and products, may be 
> > take logarithms of them, and display them in other two text boxes or 
> > labels, and make some bar charts, scatter plots, and later draw curves and 
> > surfaces on a computer screen. Do I really need PyPi or other external 
> > stuff for this? Is Python well equipped for this?
> >
> 
> You could do all of that with just the standard library, but then your
> only choice of GUI library is Tkinter, which is derived from Tcl/Tk.
> If you don't like how that looks (either in your code, or in the
> resulting GUI), you'll need to turn to PyPI for an alternative (eg
> something derived from GTK or wxWindows or Qt). I'm not sure how the
> graphing capabilities of Tkinter are, so you might want to grab
> matplotlib too - again, it'll give you a lot more flexibility than you
> would have if you restrict yourself to *just* the standard library.
> But I think you could do all of that - certainly most of it - with
> just the language and standard library.
> 

What do I lose by using an external library? Bigger size of the *.exe is not a 
problem, neither is speed an issue. It might even be easier to learn with these 
external libraries, and produce more readable code.

> > I will have to learn GUI creating quickly after I know the basics of 
> > reading and writing text files, and doing simple mathematical calculations.
> >
> 
> Reading and writing text files is easy, as is basic mathematics.
> You'll have that down in an hour or two, most likely, and then you'll
> have time to play GUIs.

That is good.

> 
> > Later I can imagine using things like sending an SMS from a phone running 
> > this on Android, or placing a graph in a WhatsApp message, make a call to 
> > someone and tell him the temperature is now too high, etc. These things 
> > might need external libraries, but I can learn this later on.
> >
> 
> Those things will most likely require external libraries. But most of
> them are probably possible.
> 
> ChrisA

Thanks again for your input.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread wrong . address . 1
On Thursday, 18 February 2016 18:24:55 UTC+2, Dan Strohl  wrote:
> I totally agree with Chris here, try it out, do some simpler things to get 
> your feet wet before committing to redoing hundreds of thousands of lines of 
> code in it.  Find a few of the "deal breakers" and try to solve them in 
> Python (create a hello world app in python, then package it in an exe and 
> distribute it to some friends).. VB is a fine language, and is likely to suit 
> your needs as well... even if we all believe that Python is better, the 
> effort to convert from one to the other may not make sense.
> 

How long can I depend on VB? I don't really mind learning one more language if 
there is sufficient utility of it. Besides, I hear that Python is relatively 
easy to learn compared to C++ or Java.

I have some smaller VB programs (single form, little math) for my own use. I 
could convert those first and get a feel of how it is going to be with larger 
programs with thousands of lines.

> I would also suggest taking a few steps back and seeing if there is a 
> different overall architectural approach that makes sense.  If you are using 
> a heavy weight local app, what about a web app? 

Some things I do can be done in a web app, but the important stuff has to be 
put into *.exe files for myself and others to use.

> What about doing a combination approach?  Have a back end running on a server 
> with Python, that feeds a VB app on a client for displaying and manipulating 
> data? (then a Java app for mobile clients or Linux ones?)
> 

I do not know Java, and don't feel inclined to learn that. If I could use VB 
for years, I need not consider moving over to Python. The trouble is that I 
don't think we can trust VB (VB6 particularly, but even VB.net) for too long.

> Also, looking at existing frameworks and expandable apps out there that you 
> might be able to do less work but still meet your goals with because 80% of 
> the work was done for you... things like django, splunk, tableau, etc...
> 
> Dan
> 

Thanks.

> 
> > -Original Message-
> > From: Python-list [mailto:[email protected]] On
> > Behalf Of Chris Angelico
> > Sent: Thursday, February 18, 2016 8:06 AM
> > Cc: [email protected]
> > Subject: Re: Considering migrating to Python from Visual Basic 6 for 
> > engineering
> > applications
> > 
> > On Fri, Feb 19, 2016 at 2:49 AM,   wrote:
> > > Thanks. You have guided me quite well, and I am almost ready to declare 
> > > that I
> > will use Python for the next few decades.
> > >
> > 
> > Don't declare like that - just start using it, and see what you think
> > :) But I would be very much surprised if Python doesn't get added to your
> > toolbelt. A good programmer should always keep a selection of tools handy -
> > seldom is one tool the right one for every job.
> > 
> > > Imagine I want to read in two (or a few) numbers from a text file, 
> > > display them
> > in two (or more) text boxes, calculate their sums and products, may be take
> > logarithms of them, and display them in other two text boxes or labels, and
> > make some bar charts, scatter plots, and later draw curves and surfaces on a
> > computer screen. Do I really need PyPi or other external stuff for this? Is 
> > Python
> > well equipped for this?
> > >
> > 
> > You could do all of that with just the standard library, but then your only 
> > choice
> > of GUI library is Tkinter, which is derived from Tcl/Tk.
> > If you don't like how that looks (either in your code, or in the resulting 
> > GUI),
> > you'll need to turn to PyPI for an alternative (eg something derived from 
> > GTK or
> > wxWindows or Qt). I'm not sure how the graphing capabilities of Tkinter 
> > are, so
> > you might want to grab matplotlib too - again, it'll give you a lot more 
> > flexibility
> > than you would have if you restrict yourself to *just* the standard library.
> > But I think you could do all of that - certainly most of it - with just the 
> > language
> > and standard library.
> > 
> > > I will have to learn GUI creating quickly after I know the basics of 
> > > reading and
> > writing text files, and doing simple mathematical calculations.
> > >
> > 
> > Reading and writing text files is easy, as is basic mathematics.
> > You'll have that down in an hour or two, most likely, and then you'll have 
> > time to
> > play GUIs.
> > 
> > > Later I can imagine using things like sending an SMS from a phone running 
> > > this
> > on Android, or placing a graph in a WhatsApp message, make a call to someone
> > and tell him the temperature is now too high, etc. These things might need
> > external libraries, but I can learn this later on.
> > >
> > 
> > Those things will most likely require external libraries. But most of them 
> > are
> > probably possible.
> > 
> > ChrisA
> > --
> > https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Will file be closed automatically in a "for ... in open..." statement?

2016-02-18 Thread Jeremy Leonard
On Tuesday, February 16, 2016 at 3:39:34 AM UTC-5, [email protected] wrote:
> I know
> 
> with open('foo.txt') as f:
> ...do something...
> 
> will close the file automatically when the "with" block ends. 
> 
> I also saw codes in a book:
> 
> for line in open('foo.txt'):
>   ...do something...
> 
> but it didn't mention if the file will be closed automatically or not when 
> the "for" block ends. Is there any document talking about this? and how to 
> know if a file is in "open" or not?
> 
> --Jach Fong

One way of having a file automatically closed is to have something like:

with open("file_name") as foo:
for x in foo:
   # process line x

Once the with block has completed, the file will be automatically closed. Sorry 
if this has already been posted, but I wasn't able to see it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Passing data across callbacks in ThreadPoolExecutor

2016-02-18 Thread Joseph L. Casale
On Thur, Feb 17, 2016 at 9:24 AM, Ian Kelly  wrote:
>> What is the pattern for chaining execution of tasks with ThreadPoolExecutor?
>> Callbacks is not an adequate facility as each task I have will generate new 
>> output.
>
> Can you specify in more detail what your use case is?
>
> If you don't mind having threads sitting around waiting, you can just
> submit each chained task at the start and have each task wait on the
> futures of its dependencies. The advantage of this is that it's easy
> to conceptualize the dependency graph of the tasks. The disadvantage
> is that it eats up extra threads. You'll probably want to increase the
> size of the thread pool to handle the waiting tasks (or use a separate
> ThreadPoolExecutor for each chained task).

The thing with callbacks is each one gets the original tasks result. So the
callback can't pass a new task result up and/or cancel the task "set".

> Otherwise, is there some reason you can't use multiple callbacks, one
> to handle the task's output and one to submit the chained task?
> 
> E.g.:
> 
> def chain_task2(input, f2):
> f2 = executor.submit(task2, input, f2.result())
> f2.add_done_callback(handle_task2_done)
> 
> f1 = executor.submit(task1, input)
> f1.add_done_callback(handle_task1_done)
> f1.add_done_callback(functools.partial(chain_task2, input))

Closing over the executer instance seems potentially race'y. What happens when
the last task finishes and the executer checks (locking the queue) and the task 
also
wants to add more work. I'll check the source, but I had hoped for a more 
succinct way.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Tim Chase
On 2016-02-18 09:58, [email protected] wrote:
> How long can I depend on VB?

Are you talking the VB6-and-before, or VB.Net?  Given that MS dropped
support for the VB6 line a decade ago (2005-2008 depending on whether
you had extended support) with little to no help in transitioning to
VB.Net which (pejoratively called "Visual Fred" because it's so
different), I wouldn't want to depend on it at all.  Especially since
VB.Net is so radically different from VB6.  As it seems you've found.

> I don't really mind learning one more language if there is
> sufficient utility of it. Besides, I hear that Python is relatively
> easy to learn compared to C++ or Java.

I find that Python is much more readable than the C-flavored
languages.  Also, while there are language gotchas in all of them,
Python's make a lot more sense to me compared to those in the
C-flavored languages.

> I have some smaller VB programs (single form, little math) for my
> own use. I could convert those first and get a feel of how it is
> going to be with larger programs with thousands of lines.

Excellent plan.

-tkc




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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Tim Chase
On 2016-02-18 07:33, [email protected] wrote:
> Another question I have is regarding reading numerical data from
> text files. Is it necessary to read one character at a time, or can
> one read like in Fortran and Basic (something like Input #5, X1,
> X2, X3)?

A lot of my work is extracting data from text files.  If it's
CSV-format data, Python's "csv" module in the standard library offers
some nice tools for doing this.

If the numbers are in plain-text, but at fixed column-offsets, I
usually create a mapping of slices to make it easier to work with.
If this is the case and you want some example code, I can dig some up.

Finally, if the data is actually binary, Python's "struct" module
(also in the standard library) makes it a lot easier to work with such
data.

-tkc



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


Re: Question on keyword arguments

2016-02-18 Thread Tim Chase
On 2016-02-18 10:57, [email protected] wrote:
> Tim, the 'crazy-other-result format' is the
> result returned by the database, nothing
> I can do about that :)

then, much like converting byte-strings to unicode strings as early
as possible and converting them back to byte-strings as late as
possible, I'd do the same with your DB results:  change them into
real Python lists as soon as they come out of the DB, operate on them
throughout your code as real lists, and only convert them back to
crazy-other-format at the time you write them back to the DB.

My condolences on having to deal with ugly data.  Been there, done
that, still stuck with it. :-)

-tkc


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


Re: Guido on python3 for beginners

2016-02-18 Thread John Ladasky
On Wednesday, February 17, 2016 at 11:28:17 PM UTC-8, Chris Angelico wrote:

> 5) print statement/function. Py3 forces you to put parentheses on it,
> which is no different from C's printf() or Pike's write() or any
> number of other languages where console I/O needs no language support.
> Maybe a tiny TINY advantage to Py2 in the short term, but as soon as
> you introduce the less basic features, keyword arguments are way
> better than the magic syntax the statement needs. (Also, trying to
> explain the interaction between the print statement's "soft space" and
> other console I/O is not easy.) By the time you've really learned the
> language, the advantage belongs to Py3.

Another advantage to the Py3 print function over the Py2 print statement is 
that it makes redirecting output SO much easier.  If I write a function that 
might sometimes print output to the console, and might at some other time print 
to a GUI window, or to a log file, I can just pass in the relevant output 
function name as an argument to my own function.  

This is very helpful, and I use it often.  I teach my new Python students to 
write their application's core logic, without regards to any GUI.  Later, when 
I teach them to use a GUI, building it is easier because the process is modular.
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2016-02-18 Thread Christian Gollwitzer

Am 16.02.16 um 03:02 schrieb Rick Johnson:

On Friday, February 12, 2016 at 1:51:35 AM UTC-6, John Ladasky wrote:

I like lazy evaluation.


Well, it is a "Pythonic feature" no doubt.



?? I'm confused. Does Python have lazy evaluation? I thought that Python 
does eager evaluation. At least this snippet seems to confirm:


def arg():
print("Evaluating arg")
return None

def func(x):
print("Evluating func")
print(x)

func(arg())

If I run it, the output is:

Evaluating arg
Evluating func

and I think that with side effects, only eager evaluation is really 
predictable.


Christian

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


Re: PythonTidy

2016-02-18 Thread cjcollier
Hello Sir!

First, thank you for creating this tool.

next, I would recommend perltidy as a program to emulate.  I'll paste the 
output of perltidy --help below.

http://perltidy.sourceforge.net/

I could probably write a wrapper script to do this if you'd like.

Cheers,

C.J.



$ perltidy --help
This is perltidy version 20140328, a perl script indenter.  Usage:

perltidy [ options ] file1 file2 file3 ...
(output goes to file1.tdy, file2.tdy, file3.tdy, ...)
perltidy [ options ] file1 -o outfile
perltidy [ options ] file1 -st >outfile
perltidy [ options ] outfile

Options have short and long forms. Short forms are shown; see
man pages for long forms.  Note: '=s' indicates a required string,
and '=n' indicates a required integer.

I/O control
 -h  show this help
 -o=file name of the output file (only if single input file)
 -oext=s change output extension from 'tdy' to s
 -opath=path  change path to be 'path' for output files
 -b  backup original to .bak and modify file in-place
 -bext=s change default backup extension from 'bak' to s
 -q  deactivate error messages (for running under editor)
 -w  include non-critical warning messages in the .ERR error output
 -synrun perl -c to check syntax (default under unix systems)
 -logsave .LOG file, which has useful diagnostics
 -f  force perltidy to read a binary file
 -g  like -log but writes more detailed .LOG file, for debugging scripts
 -optwrite the set of options actually used to a .LOG file
 -npro   ignore .perltidyrc configuration command file 
 -pro=file   read configuration commands from file instead of .perltidyrc 
 -st send output to standard output, STDOUT
 -se send all error output to standard error output, STDERR
 -v  display version number to standard output and quit

Basic Options:
 -i=nuse n columns per indentation level (default n=4)
 -t  tabs: use one tab character per indentation level, not recommeded
 -nt no tabs: use n spaces per indentation level (default)
 -et=n   entab leading whitespace n spaces per tab; not recommended
 -io "indent only": just do indentation, no other formatting.
 -sil=n  set starting indentation level to n;  use if auto detection fails
 -ole=s  specify output line ending (s=dos or win, mac, unix)
 -plekeep output line endings same as input (input must be filename)

Whitespace Control
 -fwsfreeze whitespace; this disables all whitespace changes
   and disables the following switches:
 -bt=n   sets brace tightness,  n= (0 = loose, 1=default, 2 = tight)
 -bbtsame as -bt but for code block braces; same as -bt if not given
 -bbvt   block braces vertically tight; use with -bl or -bli
 -bbvtl=s  make -bbvt to apply to selected list of block types
 -pt=n   paren tightness (n=0, 1 or 2)
 -sbt=n  square bracket tightness (n=0, 1, or 2)
 -bvt=n  brace vertical tightness, 
 n=(0=open, 1=close unless multiple steps on a line, 2=always close)
 -pvt=n  paren vertical tightness (see -bvt for n)
 -sbvt=n square bracket vertical tightness (see -bvt for n)
 -bvtc=n closing brace vertical tightness: 
 n=(0=open, 1=sometimes close, 2=always close)
 -pvtc=n closing paren vertical tightness, see -bvtc for n.
 -sbvtc=n closing square bracket vertical tightness, see -bvtc for n.
 -ci=n   sets continuation indentation=n,  default is n=2 spaces
 -lp line up parentheses, brackets, and non-BLOCK braces
 -sfsadd space before semicolon in for( ; ; )
 -awsallow perltidy to add whitespace (default)
 -dwsdelete all old non-essential whitespace 
 -icbindent closing brace of a code block
 -cti=n  closing indentation of paren, square bracket, or non-block brace: 
 n=0 none, =1 align with opening, =2 one full indentation level
 -icpequivalent to -cti=2
 -wls=s  want space left of tokens in string; i.e. -nwls='+ - * /'
 -wrs=s  want space right of tokens in string;
 -stsput space before terminal semicolon of a statement
 -sak=s  put space between keywords given in s and '(';
 -nsak=s no space between keywords in s and '('; i.e. -nsak='my our local'

Line Break Control
 -fnlfreeze newlines; this disables all line break changes
and disables the following switches:
 -anladd newlines;  ok to introduce new line breaks
 -bbsadd blank line before subs and packages
 -bbcadd blank line before block comments
 -bbbadd blank line between major blocks
 -kbl=n  keep old blank lines? 0=no, 1=some, 2=all
 -mbl=n  maximum consecutive blank lines to output (default=1)
 -ce cuddled else; use this style: '} else {'
 -dnldelete old newlines (default)
 -l=nmaximum line length;  default n=80
 -bl opening brace on new line 
 -sblopening sub brace on new line.  value of -bl is used if not given.
 -bliopening brace on new line and indented
 -baropening brace always on right, even for long clauses
 -vt=n   vertical tightness (requires -lp); n controls break after op

Re: Guido on python3 for beginners

2016-02-18 Thread Sven R. Kunze

On 18.02.2016 07:59, Paul Rubin wrote:

Steven D'Aprano  writes:

I suppose that it is objectively correct that it is harder to learn
than Python 2. But I don't think the learning curve is any steeper. If
anything, the learning curve is ever-so-slightly less steep.

I think py3 has more learning curve because it uses iterators in places
where py2 uses lists.  That's a significant new concept and it can be
bug-prone even for programmers who are experienced with it.



That is indeed very true.


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


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

2016-02-18 Thread Chris Angelico
On Fri, Feb 19, 2016 at 8:14 AM, Christian Gollwitzer  wrote:
> Am 16.02.16 um 03:02 schrieb Rick Johnson:
>>
>> On Friday, February 12, 2016 at 1:51:35 AM UTC-6, John Ladasky wrote:
>>>
>>> I like lazy evaluation.
>>
>>
>> Well, it is a "Pythonic feature" no doubt.
>
>
>
> ?? I'm confused. Does Python have lazy evaluation? I thought that Python
> does eager evaluation. At least this snippet seems to confirm:
>
> def arg():
> print("Evaluating arg")
> return None
>
> def func(x):
> print("Evluating func")
> print(x)
>
> func(arg())
>
> If I run it, the output is:
>
> Evaluating arg
> Evluating func
>
> and I think that with side effects, only eager evaluation is really
> predictable.

Python's form of lazy evaluation comes in the form of functions that
return iterables, rather than concrete lists:

>>> def square(x):
... print("Squaring %d..." % x)
... return x*x
...
>>> squares = map(square, range(10))
>>> next(squares)
Squaring 0...
0
>>> next(squares)
Squaring 1...
1
>>> next(squares)
Squaring 2...
4

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Dietmar Schwertberger

On 18.02.2016 18:49, [email protected] wrote:

What do I lose by using an external library?
With using matplotlib for your plots, you can easily create many kinds 
of plots.
On the other hand, if integration with MS Office is a concern, other 
options may be more suitable for you as matplotlib can not export 
EMF/WMF files any more. (Using svg or pdf as intermediate format is 
possible, but no fun.)
With the drawing function of e.g. wxPython or PyQt you can either draw 
on the screen or into a Metafile context using the same code. So you can 
easily export high quality vector graphics via clipboard or file.


Regards,

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


testfixtures 4.8.0 Released!

2016-02-18 Thread Chris Withers

Hi All,

I'm pleased to announce the release of testfixtures 4.9.0 featuring the 
following:


- Suffixes and well as prefixes for compare() assertion errors.

- Appropriate metadata to indicate official support for Python 3.5.

Thanks for Felix Yan for the metadata patch.

Thanks to Wim Glenn for the suffix patch.

The package is on PyPI and a full list of all the links to docs, issue 
trackers and the like can be found here:


https://github.com/Simplistix/testfixtures

Any questions, please do ask on the Testing in Python list or on the 
Simplistix open source mailing list...


cheers,

Chris

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


Re: testfixtures 4.8.0 Released!

2016-02-18 Thread Mark Lawrence

On 18/02/2016 22:27, Chris Withers wrote:

Hi All,

I'm pleased to announce the release of testfixtures 4.9.0 featuring the
following:



4.8.0 or 4.9.0, that is the question, or should it be just how good is 
your version control? :)


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

Mark Lawrence

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


Re: Python keyword args can be any string

2016-02-18 Thread Steven D'Aprano
On Thu, 18 Feb 2016 06:55 pm, Mark Lawrence wrote:

> On 18/02/2016 05:42, Steven D'Aprano wrote:
>> Today I learned that **kwargs style keyword arguments can be any string:
>>
>> py> def test(**kw):
>> ... print(kw)
>> ...
>> py> kwargs = {'abc-def': 42, '': 23, '---': 999, '123': 17}
>> py> test(**kwargs)
>> {'': 23, '123': 17, '---': 999, 'abc-def': 42}
>>
>> Bug or feature?
>>
> 
> I'm not sure, but what on earth got you to this in the first place?


A work colleague wanted to pass an argument starting with "-" to a function.

Apparently he didn't have a specific argument in mind. He just wanted to
test the function to breaking point by passing invalid argument names.


-- 
Steven

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Steven D'Aprano
On Thu, 18 Feb 2016 10:32 pm, Chris Angelico wrote:

> The biggest disadvantage of Python is that, in a number of ways, it
> surprises people. Significant whitespace bugs a lot of experienced
> programmers

This is why we cannot have nice things.

"But what if we pass the source code through a system that strips out
leading whitespace?"

"Then don't do that. What if you pass the source code through a system that
strips out braces?"



-- 
Steven

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Chris Angelico
On Fri, Feb 19, 2016 at 11:30 AM, Steven D'Aprano  wrote:
> On Thu, 18 Feb 2016 10:32 pm, Chris Angelico wrote:
>
>> The biggest disadvantage of Python is that, in a number of ways, it
>> surprises people. Significant whitespace bugs a lot of experienced
>> programmers
>
> This is why we cannot have nice things.
>
> "But what if we pass the source code through a system that strips out
> leading whitespace?"
>
> "Then don't do that. What if you pass the source code through a system that
> strips out braces?"

You may note that I didn't say that this was a flaw in Python. And
it's not a tooling issue either (that was mentioned as a parenthesis,
but wasn't my main point). I'm talking about how people, those bags of
flesh and thoughts, are bugged out by the notion that *whitespace*
should matter (other than the mere presence/absence of it). It's the
price you pay for being different - people will have trouble
comprehending you.

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


Re: Python keyword args can be any string

2016-02-18 Thread Ben Finney
Steven D'Aprano  writes:

> A work colleague wanted to pass an argument starting with "-" to a
> function.
>
> Apparently he didn't have a specific argument in mind. He just wanted
> to test the function to breaking point by passing invalid argument
> names.

That seems a reasonable test.

>>> kwargs = {
... 'spam': 13,
... 'eggs': 17,
... '-beans': 11,
... }
>>> foo(**kwargs)# Should this fail?

It exposes a design smell; by capturing ‘**kwargs’, a function has
deiberately not specified which keyword arguments it will accept.

>>> def foo_captures_kwargs(*args, **kwargs):
... for (name, value) in kwargs.items():
... print("Got argument {name}={value!r}".format(
... name=name, value=value))
... 
>>> foo_captures_kwargs(**kwargs)
Got argument eggs=17
Got argument spam=13
Got argument -beans=11

Still not a bug in Python IMO. It may be a bug in the program; the
design of the function doesn't provide any way to know.

Perhaps the design can be improved by not using ‘**kwargs’ at all, and
instead using a specific set of keyword-only arguments.

>>> def foo_names_every_argument(*, spam="Lorem", eggs="ipsum"):
... print("Got argument {name}={value!r}".format(
... name='spam', value=spam))
... print("Got argument {name}={value!r}".format(
... name='eggs', value=eggs))
... 
>>> foo_names_every_argument(**kwargs)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: foo_names_every_argument() got an unexpected keyword argument 
'-beans'

This is IMO another good reason to migrate ASAP to Python 3; better
design is easier that before.

-- 
 \  “Judge: A law student who marks his own papers.” —Henry L. |
  `\   Mencken |
_o__)  |
Ben Finney

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


Ohnoes significant whitespace (was: Considering migrating to Python from Visual Basic 6 for engineering applications)

2016-02-18 Thread Ben Finney
Chris Angelico  writes:

> I'm talking about how people, those bags of flesh and thoughts, are
> bugged out by the notion that *whitespace* should matter (other than
> the mere presence/absence of it). It's the price you pay for being
> different - people will have trouble comprehending you.

To be fair, there is good reason for the programming (and broader IT)
community to have a heuristic of “significant whitespace is probably
bad”.

The few languages that did this badly (Makefile syntax, some Unix shell
syntax) leave a legacy of countless headaches and you can't fix the
language retroactively without breaking backward compatibility.

So I am sympathetic to Python newcomers recoiling in horror from
significant whitespace, *before* they try it. And because of that, we
are burdened with forever needing to deal with that reaction and
soothing it.

Those people who claim to have tried Python and *still* complain about
“significant whitespace”, I have no sympathy for. Python clearly does it
right, and it's a huge boon to readability and reducing simple errors.

-- 
 \   “He was the mildest-mannered man / That ever scuttled ship or |
  `\   cut a throat.” —“Lord” George Gordon Noel Byron, _Don Juan_ |
_o__)  |
Ben Finney

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Mark Lawrence

On 18/02/2016 11:32, Chris Angelico wrote:

On Thu, Feb 18, 2016 at 10:11 PM,   wrote:

Almost everything points positively for Python. Thanks to all of you who have 
responded. But please also tell me the disadvantages of Python. If I start 
using Python, I should be aware of the price I am paying. Speed is not a big 
problem for me, so an interpreted language is fine. Is packaging/installing 
very messy? Do I create dozens of files for a simple program calculating the 
sum of two numbers and product of two numbers in text boxes with one command to 
be clicked? Can I learn this much in the first couple of hours?



There are a few warts, particularly on Windows, as regards packaging
and third-party modules. Anything that's written in pure Python is
fairly easy; stuff that's written in C is sometimes a bit hairy. But
that's a limitation on the "extended library" of PyPI, not the stuff
that comes with Python itself.



The vast majority of C code that you're ever likely to need can be 
obtained here http://www.lfd.uci.edu/~gohlke/pythonlibs/ if there isn't 
a whl file on pypi.  The site might be headed "Unofficial Windows 
Binaries for Python Extension Packages" but it's as safe as houses, I've 
been using it for years without any problems at all.


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

Mark Lawrence

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread Steven D'Aprano
On Fri, 19 Feb 2016 02:35 am, [email protected] wrote:

> I am almost eager to do this but want to be sure that I know the pitfalls
> in using Python for my purposes. Thanks for your encouraging response.

Honestly "wrong.address.1", the ONLY pitfall you need to be aware of is to
beware of trying to write VB code using Python's interpreter. Python has
it's own way of doing things, and if you insist on doing them "just like
VB" you will end up with horrible, slow, inefficient, unusable code. That's
not to say that VB is worse, or Python is worse, just that they are
different. You don't use a hammer the same was a screwdriver.

Python is a 20+ year old language used by millions of professionals all over
the world for everything from quick scripting, scientific computing, web
applications, long-running server applications, and everything in between.
The answer to every one of your questions "Can Python do X?" will be one
of:

(1) Yes it can.

(2) No, but instead it will do Y which gives you the same result.


I'll be frank, to come here and ask a bunch of questions like:

"Is it necessary to read one character at a time...?"

is a little bit rude. I don't want to discourage you from asking questions,
but think about *how* you ask them. What you're doing is a little bit like
going to a car dealer, looking at the cars, then asking a bunch of
questions:

"So... does this car have a reverse gear or can it only go forward? Do the
doors open for entry, or do I have to squeeze through the windows? Can I
use the radio while driving, or is there only enough power for one at a
time?"

In most programming communities, if you start asking questions like that,
you can expect to be ignored or abused. Good thing we're a friendly
bunch :-)


Instead, a good question is:

"How do I read a bunch of numbers from a text file?"


I'll show you, not only how to read a bunch of numbers, but how to write
them first.

Of course there are a million different ways you can do this, and for
serious use you will probably want to use something like a CSV (Comma
Separated Values) file like Excel produces, but for a quick idea of how
Python works, let's write some numbers to a file, one per line. Comments
start with # and have no effect. Remember that indentation is meaningful:
you must use the same number of spaces as shown in my code.

Copy and paste this code into the Python interpreter:



# = cut =

# Define some numbers.
numbers = [1, 45, 38, 99, 1002, 83025, 234, 55, 273, 2]
# Open a file for writing.
with open("myfile.txt", "w") as f:
# Write each number to the file, one per line.
for number in numbers:
print("Writing %d to the file." % number)
f.write(str(number) + "\n")

# = cut =



And that's done. Five lines of code, ignoring comments. Now let's read them
back and see if they're the same:


# = cut =

# Prepare a list to hold the numbers.
data = []
# Open a file for reading.
with open("myfile.txt", "r") as f:
# Read each line.
for line in f:
value = line.strip()  # Get rid of trailing newline.
print("Read %s from the file." % value)
data.append(int(value))

# Confirm the numbers read in are the same as those written out.
if data != numbers:
print("mismatch in values")

# Print the sorted values.
print(sorted(data))

# = cut =



Does this help?



-- 
Steven

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


Re: Guido on python3 for beginners

2016-02-18 Thread Steven D'Aprano
On Fri, 19 Feb 2016 02:51 am, Random832 wrote:

> On Thu, Feb 18, 2016, at 07:25, Rustom Mody wrote:
>> My beef is somewhat different: viz that post 70s (Pascal) and 80s
>> (scheme)
>> programming pedagogy has deteriorated with general purpose languages
>> replacing
>> 'teaching-purpose language' for teaching.
> 
> The flaw in this idea is right there in your post. Both languages you
> named are strongly tied to a single paradigm (procedural for Pascal, and
> functional for Scheme) which don't match the paradigm that real-world
> work is done in. Is there a new "teaching-purpose language"?


Scratch seems very popular for teaching young children. If I were 10, I
would definitely check it out. The emphasis is on writing re-usable code
snippets, collaboration, and graphics and animation.

https://scratch.mit.edu/


But apart from that, I think that "teaching" versus "doing" language is a
false dichotomy. Teaching languages should have a shallow learning curve
(easy to get started and learn the language, easy discoverability).
Production languages should have deep functionality and power. Those two
are not *necessarily* opposed[1]. Good languages should have both: a
shallow learning curve leading to deep functionality.

Pascal was easy to learn and powerful, but it made the mistake of not
standardising on a few critical functions that production languages need,
like strings. Nevertheless, for the first 10 or 15 years, Apple used a mix
of Pascal and assembly to write not just the operating system but a whole
lot of applications for the Macintosh. Anyone who says that Pascal is a toy
language is just ignorant.




[1] Except in the trivial sense that the more you have to learn, the longer
it will take.


-- 
Steven

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


Weird python 2.7 import thing

2016-02-18 Thread Dan Stromberg
OK, I'd rather be on 3.x, but that's not going to happen today.

So 2.7.

I have added directories to my sys.path hundreds of times before
importing from them, and know what to expect from that.  I confess, I
don't have a lot of package or egg experience.

However, I have a somewhat special (apparently) directory that isn't working.

The traceback, when I try to import it, looks like:
Traceback (most recent call last):
  File "t", line 17, in 
from InfinityUnixHost.activities.ICWrap import ICWrap
  File 
"/home/dstromberg/PycharmProjects/infinity_PY/src/InfinityUnixHost/activities/ICWrap.py",
line 8, in 
from InfinityUnixHost.IPGlobal import DB_POOL
  File 
"/home/dstromberg/PycharmProjects/infinity_PY/src/InfinityUnixHost/IPGlobal.py",
line 12, in 
INTERNAL_VERSION = pkg_resources.require("InfinityUnixHost")[0].version
  File 
"/home/dstromberg/virtualenvs/dev/local/lib/python2.7/site-packages/pkg_resources/__init__.py",
line 941, in require
needed = self.resolve(parse_requirements(requirements))
  File 
"/home/dstromberg/virtualenvs/dev/local/lib/python2.7/site-packages/pkg_resources/__init__.py",
line 828, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'InfinityUnixHost'
distribution was not found and is required by the application


And a tiny test program that produces this error is:
#!/usr/bin/env python

import sys
import os.path

sys.path.insert(0, os.path.abspath('src'))
sys.path.insert(0, os.path.abspath('eggs/InfinityCore-6-py2.7.egg'))
#for directory in sys.path:
#   # print(directory)
#   if \
#   os.path.exists(os.path.join(directory,
'InfinityUnixHost')) and \
#   os.path.exists(os.path.join(directory,
'InfinityUnixHost/activities')) and \
#   os.path.exists(os.path.join(directory,
'InfinityUnixHost/activities/ICWrap.py')):
#   print('found in %s' % directory)

# from InfinityUnixHost.activities.ICWrap import ICWrap
from InfinityUnixHost.activities.ICWrap import ICWrap
dummy = ICWrap


BTW, the commented-out for loop can see the file I am trying to import
(when uncommented), but still, the import machinery doesn't load the
module.

I can't share much detail about the InfinityUnixHost internals
unfortunately, but we can probably discuss it as needed.

Does anyone know why import is failing in this odd way?  It's not even
an ImportError!

BTW, this is not a package I pip installed from pypi - it's an
internal-only project.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-18 Thread BartC

On 19/02/2016 00:30, Steven D'Aprano wrote:

On Thu, 18 Feb 2016 10:32 pm, Chris Angelico wrote:


The biggest disadvantage of Python is that, in a number of ways, it
surprises people. Significant whitespace bugs a lot of experienced
programmers


This is why we cannot have nice things.

"But what if we pass the source code through a system that strips out
leading whitespace?"

"Then don't do that. What if you pass the source code through a system that
strips out braces?"


Python doesn't use braces, so that's not a problem!

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


Re: Guido on python3 for beginners

2016-02-18 Thread Rustom Mody
On Thursday, February 18, 2016 at 9:22:10 PM UTC+5:30, Random832 wrote:
> On Thu, Feb 18, 2016, at 07:25, Rustom Mody wrote:
> > My beef is somewhat different: viz that post 70s (Pascal) and 80s
> > (scheme) 
> > programming pedagogy has deteriorated with general purpose languages
> > replacing
> > 'teaching-purpose language' for teaching.
> 
> The flaw in this idea is right there in your post. Both languages you
> named are strongly tied to a single paradigm (procedural for Pascal, and
> functional for Scheme) which don't match the paradigm that real-world
> work is done in. 

Factually incorrect.
Scheme is as multi-paradigm as you can get -- SICP spends considerable time
building OO systems, machine architectures etc
Culturally is another matter -- scheme tends to draw FP aficionados as python 
seems to draw OO ones.  The languages do not mandate this

> Is there a new "teaching-purpose language"?

No And that's the deterioration in the programming edu-world

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


Re: Passing data across callbacks in ThreadPoolExecutor

2016-02-18 Thread Ian Kelly
On Thu, Feb 18, 2016 at 12:06 PM, Joseph L. Casale
 wrote:
> On Thur, Feb 17, 2016 at 9:24 AM, Ian Kelly  wrote:
>>> What is the pattern for chaining execution of tasks with ThreadPoolExecutor?
>>> Callbacks is not an adequate facility as each task I have will generate new 
>>> output.
>>
>> Can you specify in more detail what your use case is?

It's still not clear to me specifically what you're trying to do. It
would really help if you would describe the problem in more detail.
Here's what I think you're trying to do:

1) Submit a task to a ThreadPoolExecutor and get back a future.

2) When the task is complete, submit another task that needs the
result of the first task to do its work.

3) When the chained task is complete, return the final result of the
chained task back to whoever submitted the original task via the
original task's future.

The problem arises in that the original task's future already
completed when the original task did. The chained task sets its result
in a different future that the submitter didn't know about.

>> If you don't mind having threads sitting around waiting, you can just
>> submit each chained task at the start and have each task wait on the
>> futures of its dependencies. The advantage of this is that it's easy
>> to conceptualize the dependency graph of the tasks. The disadvantage
>> is that it eats up extra threads. You'll probably want to increase the
>> size of the thread pool to handle the waiting tasks (or use a separate
>> ThreadPoolExecutor for each chained task).
>
> The thing with callbacks is each one gets the original tasks result. So the
> callback can't pass a new task result up and/or cancel the task "set".

If you start each individual task at time of submission, then you'll
get separate futures for them, and you can add callbacks to each of
the futures individually. Each callback will get the result of the
task it was added to, not the original task. If you only care about
the final result, then you would only add a callback to the future for
the final task.

>> Otherwise, is there some reason you can't use multiple callbacks, one
>> to handle the task's output and one to submit the chained task?
>>
>> E.g.:
>>
>> def chain_task2(input, f2):
>> f2 = executor.submit(task2, input, f2.result())
>> f2.add_done_callback(handle_task2_done)
>>
>> f1 = executor.submit(task1, input)
>> f1.add_done_callback(handle_task1_done)
>> f1.add_done_callback(functools.partial(chain_task2, input))
>
> Closing over the executer instance seems potentially race'y. What happens when
> the last task finishes and the executer checks (locking the queue) and the 
> task also
> wants to add more work. I'll check the source, but I had hoped for a more 
> succinct way.

Again, it's not clear to me what scenario you're talking about here.
The executor never "checks" the queue; it's only used to submit tasks.
The only things pulling from the queue are the worker threads
themselves.

Besides, if something is waiting on a queue, it's not going to hold
the lock on the queue while it's waiting; that would make it
impossible to put anything on the queue and it would just end up
waiting forever.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread pyotr filipivich
Dennis Lee Bieber  on Thu, 18 Feb 2016 21:57:13
-0500 typed in comp.lang.python  the following:
>On Thu, 18 Feb 2016 16:24:00 + (UTC), Ulli Horlacher
> declaimed the following:
>
>>Dennis Lee Bieber  wrote:
>>
>>> >I have 
>>> >"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
>>> >v.1500 32 bit (Intel)] on win32"
>>> >and there is no "win_add2path.py"
>>> >
>>> C:\Python_x64\Python27\Tools\scripts\win_add2path.py
>>
>>Ok, It is here in C:\Python27\Tools\scripts\win_add2path.py
>>but windows "Search programs and files" was not able to find it.
>
>   Windows (especially 7) search function is highly crippled. There is
>some command sequence that will open it up to looking at other file types
>and locations.
>
>http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1


Thanks.  I've found it "simpler" to just open a command prompt, and
use DOS.
-- 
pyotr filipivich
Next month's Panel: Graft - Boon or blessing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guido on python3 for beginners

2016-02-18 Thread Rustom Mody
On Friday, February 19, 2016 at 6:48:12 AM UTC+5:30, Steven D'Aprano wrote:

> 
> 
> But apart from that, I think that "teaching" versus "doing" language is a
> false dichotomy. Teaching languages should have a shallow learning curve
> (easy to get started and learn the language, easy discoverability).
> Production languages should have deep functionality and power. Those two
> are not *necessarily* opposed[1]. Good languages should have both: a
> shallow learning curve leading to deep functionality.
> 
> [1] Except in the trivial sense that the more you have to learn, the longer
> it will take.

Consider as hypothesis
L1: Needs 4 weeks to master
L2: Needs 4 years to manage (if you want to make it less hypothetical think C++)

Which would be more satisfying to a student?
[Not a hypothetical question: Some people like to go 
mountaineering/bungee-jumping etc
and breaks their necks.
Likewise Ive seen students who were so C++-happy they failed other courses!

I'd hazard you have forgotten what it feels like to be a student by some 
decades :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2016-02-18 Thread Ian Kelly
On Mon, Feb 15, 2016 at 7:02 PM, Rick Johnson
 wrote:
> WxPython is not ported either, much to my chagrin.

If wxPython "Classic" had just been ported to Python 3, I'm sure it
would be all done by now. But it was decided to rebuild wxPython from
the ground up instead.

Last I've heard, people generally seem to consider Phoenix beta-ready.
I understand that it's slow-going though because there's basically
only one maintainer and he has a day job.
-- 
https://mail.python.org/mailman/listinfo/python-list


Weird and sparese cgi:error

2016-02-18 Thread Φώντας Λαδοπρακόπουλος
Hello,

I recentely changed VPS server and when i try to load my webiste iam receiving 
500 error which i wasnt receiving in my old VPS server with the same exact cgi 
scripts.

After looking at Apacher's error_log iam seeing the following output when i try 
to load scripts from cgi-bin directory.


[Tue Feb 16 21:28:55.970302 2016] [cgi:error] [pid 17478] [client 
180.76.15.28:21311] End of script output before headers: metrites.py
[Tue Feb 16 21:29:31.193281 2016] [cgi:error] [pid 18802] [client 
180.76.15.29:34155] End of script output before headers: metrites.py
[Tue Feb 16 21:32:21.306627 2016] [cgi:error] [pid 17478] [client 
188.138.124.110:40212] End of script output before headers: metrites.py
[Tue Feb 16 21:37:21.128472 2016] [cgi:error] [pid 19731] [client 
204.152.200.42:54376] End of script output before headers: metrites.py
[Tue Feb 16 21:42:21.198207 2016] [cgi:error] [pid 17478] [client 
184.75.210.226:57252] End of script output before headers: metrites.py
[Tue Feb 16 21:47:21.228361 2016] [cgi:error] [pid 19731] [client 
76.72.172.208:34730] End of script output before headers: metrites.py
[Tue Feb 16 21:52:21.422066 2016] [cgi:error] [pid 18802] [client 
85.17.156.11:52071] End of script output before headers: metrites.py


Please i need your assistance to this.
thank you.Prob



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


Re: Ohnoes significant whitespace

2016-02-18 Thread Marko Rauhamaa
Ben Finney :

> So I am sympathetic to Python newcomers recoiling in horror from
> significant whitespace, *before* they try it. And because of that, we
> are burdened with forever needing to deal with that reaction and
> soothing it.

I remember being *very* doubtful how the whitespace would work in
practice. I was won over by a colleague who had sloppy indentation
habbits in C++ but produced tidy, readable code in Python.

> Those people who claim to have tried Python and *still* complain about
> “significant whitespace”,

I am bitten by it occasionally. The editor doesn't know from the context
how a line or block should be (re)indented. In Emacs, TAB, BS and C-M-\,
which keep source code properly indented in other programming languages,
have been known to lead to accidental bugs in Python code. (The proper
way in Emacs is to use C-> and C-< to manipulate blocks of Python code.)

> I have no sympathy for. Python clearly does it right, and it's a huge
> boon to readability and reducing simple errors.

I don't mind Python's syntax. It's the implicit semicolons of JavaScript
and Go that I dislike.


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