Re: Daemon strategy

2016-02-06 Thread Ben Finney
Ian Kelly <ian.g.ke...@gmail.com> writes:

> Depends on the version: 
> https://en.wikipedia.org/wiki/Windows_Services_for_UNIX
> https://en.wikipedia.org/wiki/POSIX#POSIX_for_Windows
>
> Linux and FreeBSD are also not POSIX-certified, even though they
> mostly comply. Should pip warn about those also?

You're implying that the PyPI trove category “Operating System :: POSIX”
includes MS Windows? Or that it excludes Linux and FreeBSD? Or that it's
meaningless?

-- 
 \   “Drop your trousers here for best results.” —dry cleaner, |
  `\   Bangkok |
_o__)      |
Ben Finney

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


Re: Daemon strategy

2016-02-05 Thread Ben Finney
paul.hermeneu...@gmail.com writes:

> It appears that python-deamon would be exactly what I need. Alas,
> appears not to run on Windows. If I am wrong about that, please tell
> me.

You're correct that ‘python-daemon’ uses Unix facilities to create a
well-behaved Unix daemon process.

Since MS Windows lacks those facilities, ‘python-daemon’ can't use them.

> To what tools should I turn?

If what you need – the support to create a Unix daemon process – is
available only on Unix by definition, it seems you'll need to deploy to
Unix.

> I am not eager to produce a "service" on Windows unless it cannot be
> avoided.

Agreed :-)

-- 
 \ “Wrinkles should merely indicate where smiles have been.” —Mark |
  `\Twain, _Following the Equator_ |
_o__)      |
Ben Finney

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


Re: Question about official API

2016-02-05 Thread Ben Finney
"Frank Millman" <fr...@chagford.com> writes:

> What is the rule for knowing if something is part of the official API?

Part of what official API?

Different libraries will have different rules about what is the official
API. Some may not have official rules.

For Python standard library modules, the official API is in the user
documentation for each module.

> However, it is not mentioned in the [standard library] documentation.

Then it's not part of the official API (or the documentation has a bug
which needs to be reported).

-- 
 \   “The long-term solution to mountains of waste is not more |
  `\  landfill sites but fewer shopping centres.” —Clive Hamilton, |
_o__)    _Affluenza_, 2005 |
Ben Finney

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


Re: Daemon strategy

2016-02-05 Thread Ben Finney
paul.hermeneu...@gmail.com writes:

> On Fri, Feb 5, 2016 at 11:52 AM, Ben Finney <ben+pyt...@benfinney.id.au> 
> wrote:
> > Since MS Windows lacks those facilities, ‘python-daemon’ can't use
> > them.
>
> As you might imagine, I am not always able to specify which OS is
> deployed. That does not mean that I am not responsible for getting the
> work done. Perhaps you will tell me that what I want is not a daemon.

I'm telling you none of those. What I'm telling you is MS Windows does
not support what is needed to make a Unix daemon.

You may need to re-visit the requirements and negotiate something
different — a different deployment platform, or something which MS
Windows can do which is less than a proper Unix daemon.

> BTW, I thought that pip would know that python-daemon would not run on
> my machine, but it had no complaints installing it. That gave me
> unmerited hope.

Sorry to learn that. The PyPI metadata for ‘python-daemon’
<URL:https://pypi.python.org/pypi/python-daemon/> explicitly declares
the supported OS limited to “Operating System :: POSIX”, which MS
Windows is not compatible with.

If ‘pip’ does not honour that field and inform you of the
incompatibility, you may want to report a bug to the ‘pip’ developers.

-- 
 \   “My business is to teach my aspirations to conform themselves |
  `\  to fact, not to try and make facts harmonise with my |
_o__)   aspirations.“ —Thomas Henry Huxley, 1860-09-23 |
Ben Finney

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


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

2016-02-04 Thread Ben Finney
"ast" <nom...@invalid.com> writes:

> Let's invoke an obj method
>
> obj.funct()
>
> funct is first looked in ClassC, then if not found
> on ClassB, then ClassA then object

If it helps: What you describe is attribute lookup, and it happens
whether or not you're going to call the attribute.

In other words, you need only invoke ‘foo.attr’ to have Python look for
attribute ‘attr’ among the class hierarchy as you describe. Calling that
attribute is a distinct operation once the attribute is found.

> But is there a command to know where funct is found ?

That's been answered, but I'm curious to know what your program will do
with that information?

-- 
 \   “But Marge, what if we chose the wrong religion? Each week we |
  `\  just make God madder and madder.” —Homer, _The Simpsons_ |
_o__)          |
Ben Finney

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


Reply to whom? (was: Efficient Wrappers for Instance Methods)

2016-02-03 Thread Ben Finney
Bernardo Sulzbach <mafagafogiga...@gmail.com> writes:

> Thanks for quoting, for some reason my client always replies to the
> person and not the list (on this list only).

You have a “reply to sender” command in your mail client; every client
has that. It seems that is what you used (it might just be named
“reply”). Such replies should not go to anyone else by default.

You *should* also have a “reply to list” command; if you don't, speak
sternly to whomever makes the mail client you're using (“reply to list”
has been around for decades), and until then switch to a better email
client.

When you reply, decide who should receive the response, and choose
“reply to sender” or “reply to list” accordingly.

(You will also have a “reply to all” command. That's almost never
appropriate in a forum like this.)

-- 
 \ “The double standard that exempts religious activities from |
  `\   almost all standards of accountability should be dismantled |
_o__)   once and for all.” —Daniel Dennett, 2010-01-12 |
Ben Finney

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


Re: Reply to whom?

2016-02-03 Thread Ben Finney
Bernardo Sulzbach <mafagafogiga...@gmail.com> writes:

> Then you two started going on about mail clients buttons

Right. Thereby changing the subject of the evolving discussion. You're
welcome :-)

-- 
 \   “… one of the main causes of the fall of the Roman Empire was |
  `\that, lacking zero, they had no way to indicate successful |
_o__)  termination of their C programs.” —Robert Firth |
Ben Finney

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


Re: Reply to whom?

2016-02-03 Thread Ben Finney
Bernardo Sulzbach <mafagafogiga...@gmail.com> writes:

> For this list, and this list only (I likely could identify the issue
> by comparing raw messages, but I won't bother), when I hit 'r' I get
> the sender of the latest message.

This list is correctly configured; a “reply to sender” goes to the
sender address.

Some mailing lists are mis-configured to pretend that the list is the
sender; this is an abuse of the mail system and it thwarts the correct
behaviour of “reply to sender”.

> In this case, "ros...@gmail.com". So I have to start typing "pyt" to
> change it to the list, double tab to body, type, then Ctrl + Enter to
> send it after 30 seconds.

This is something to describe to the vendor of whichever mail program
you are using. Until they correct their software, there are many other
email clients you can use that do not misbehave this way, and correctly
interact with mailing list technology.

-- 
 \ “In economics, hope and faith coexist with great scientific |
  `\  pretension and also a deep desire for respectability.” —John |
_o__)        Kenneth Galbraith, 1970-06-07 |
Ben Finney

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


Re: Reply to whom?

2016-02-03 Thread Ben Finney
Bernardo Sulzbach <mafagafogiga...@gmail.com> writes:

> Mr. Finney, that would be Google itself.

Yep. You're the one who needs to interact with them because as a user of
the program, it's you they're trying to please (more than me, at least).

Can't work out how to interact with a corporation and get into
correspondence about a bug in their software? That's probably a good
sign you shouldn't be using their software :-)

> I have never bothered setting up a client such as Mutt and can't even
> name more than Outlook and Mutt.

You'll know your needs more than me. Maybe you could start with
Thunderbird (available in Debian as “Icedove” because of trademark
issues); that's a good all-round client that behaves well.

> I must say that the way you put it makes sense. A "reply" to the last
> message targeting its sender (the person that wrote it) is very
> reasonable indeed.

Thanks. This is a contentious issue, and some people want to mangle your
messages;but that doesn't mean it's still open for debate — one side is
right :-)

-- 
 \ “I cannot conceive that anybody will require multiplications at |
  `\   the rate of 40,000 or even 4,000 per hour …” —F. H. Wales, 1936 |
_o__)          |
Ben Finney

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


Re: Reply to whom?

2016-02-03 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> On Wed, Feb 3, 2016, at 16:50, Ben Finney wrote:
> > (You will also have a “reply to all” command. That's almost never
> > appropriate in a forum like this.)
>
> Why not? People reply all to messages I write all the time, and I find
> it somewhat useful since it separates replies to things I have said
> from discussions I'm not part of.

That's nice for you that it coincides with what you find useful. For
those who don't want messages to the forum duplicated in their inbox,
the behaviour is obnoxious.

In other words: Using “reply to all” on a forum like this is
inappropriate because you can't know what every participant wants, so
your set of recipients should be conservative and err on the side of not
sending a duplicate message to people who didn't ask for it.

-- 
 \“Don't worry about people stealing your ideas. If your ideas |
  `\ are any good, you'll have to ram them down people's throats.” |
_o__)            —Howard Aiken |
Ben Finney

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


[RELEASE] ‘python-daemon’ version 2.1.1 released

2016-01-30 Thread Ben Finney
Howdy all,

I am pleased to announce the release of version 2.1.1 of the
‘python-daemon’ library.

The current release is always available at
<URL:https://pypi.python.org/pypi/python-daemon/>.


Significant changes since the previous version
==

Version 2.1.0
-

I omitted sending a release announcement for version 2.1.0.

* Add a DaemonContext option, ‘initgroups’, which specifies whether to
  set the daemon process's supplementary groups.

* Set the process groups using ‘os.initgroups’.
  Thanks to Malcolm Purvis for contributing an implementation of this
  feature.

Version 2.1.1
-

This is a bug fix release, addressing this bug:

* Default ‘initgroups’ option to False. Using ‘os.initgroups’ requires
  permission to set process GID, so this now needs to be explicitly
  requested.


What is the ‘python-daemon’ library?


‘python-daemon’ is a Python library to implement a well-behaved Unix
daemon process.

-- 
 \“There are no significant bugs in our released software that |
  `\ any significant number of users want fixed.” —Bill Gates, |
_o__)   1995-10-23 |
Ben Finney <b...@benfinney.id.au>
-- 
https://mail.python.org/mailman/listinfo/python-list


[ANN] Gajja 0.1: Fake objects for real tests

2016-01-29 Thread Ben Finney
Howdy all,

I am pleased to announce the first release of the testing library I've
named Gajja <URL:https://pypi.python.org/pypi/gajja/>.

Its purpose is to allow fine-grained control of not only file content,
but metadata and system access behaviour, for in-memory test doubles.

Currently it provides classes of test doubles for filesystem entries and
subprocesses; and a framework for hooking them into individual test
cases or test case classes.

Each wrapped system interface will respond specifically for the
identifier (filesystem path, or subprocess command line) of that
specific double. Any other call to the same system interface will be
passed through to the real function; only access to the test double
should behave differently.

At the moment the documentation consists of a ‘doc/tutorial.txt’ giving
a worked example of doubling a filesystem entry to report the test
double's file size from `os.stat` (and not affect `os.stat` for any
other file).

Please contact me at <ben+pyt...@benfinney.id.au> if you have feedback
on this, or report an issue at the project's homepage
<URL:https://notabug.org/bignose/python-gajja>.

Discussion here in the Python forum is also welcome.

-- 
 \ “Facts are stubborn things; and whatever may be our wishes, our |
  `\   inclinations, or the dictates of our passion, they cannot alter |
_o__)the state of facts and evidence.” —John Adams, 1770-12-04 |
Ben Finney

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


Re: psss...I want to move from Perl to Python

2016-01-29 Thread Ben Finney
"Sven R. Kunze" <srku...@mail.de> writes:

> On 29.01.2016 01:01, Fillmore wrote:
> > How was the Python 2.7 vs Python 3.X solved? which version should I
> > go for?
>
> Python 3 is the new and better one.

More importantly: Python 2 will never improve; Python 3 is the only one
that is actively developed.

-- 
 \   “We spend the first twelve months of our children's lives |
  `\  teaching them to walk and talk and the next twelve years |
_o__)   telling them to sit down and shut up.” —Phyllis Diller |
Ben Finney

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


Re: psss...I want to move from Perl to Python

2016-01-29 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> You should have started with the official tutorial:
>
> https://docs.python.org/2/tutorial/

And these days the default recommendation should be to start with the
official tutorial for the current stable version of the Python language,
Python 3 <URL:https://docs.python.org/3/tutorial/>.

-- 
 \   “We jealously reserve the right to be mistaken in our view of |
  `\  what exists, given that theories often change under pressure |
_o__)  from further investigation.” —Thomas W. Clark, 2009 |
Ben Finney

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


Re: psss...I want to move from Perl to Python

2016-01-29 Thread Ben Finney
Fillmore <fillmore_rem...@hotmail.com> writes:

> On 1/29/2016 4:30 PM, Rick Johnson wrote:
> >  People who are unwilling to "expanding their
> > intellectual horizons" make me sick!!!
>
> did I miss something or is this aggressiveness unjustified?

Indeed it is unjustified. The person to whom you respond is best ignored
(automatically, via a kill-file in your program). No matter how amusing
some trainwreck-chasers may find his outbursts, his unreasoning
hostility is disruptive.

-- 
 \ “What is it that makes a complete stranger dive into an icy |
  `\   river to save a solid gold baby? Maybe we'll never know.” —Jack |
_o__)           Handey |
Ben Finney

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


Re: how to get python version ?

2016-01-27 Thread Ben Finney
namenobodywa...@gmail.com writes:

> is there something analogous to sys.platform that lets you get the
> version of python you're using? sorry if the question is too
> see-spot-run. thanks if you can help

The same ‘sys’ module provides many other ways to interrogate the
running Python system <URL:https://docs.python.org/3/library/sys.html>.

For the running version of Python, you want ‘sys.version_info’::

>>> import sys
>>> sys.version
'2.7.11 (default, Jan 11 2016, 21:04:40) \n[GCC 5.3.1 20160101]'
>>> type(sys.version)


>>> sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)
>>> type(sys.version_info)

>>> sys.version_info > (3, 1)
False
>>> sys.version_info > (2, 5)
True

The ‘sys.version’ object is a human-readable string. If you actually
want to do comparisons, use ‘sys.version_info’ for its much more
fine-grained structure.

-- 
 \ “If you can't annoy somebody there is little point in writing.” |
  `\—Kingsley Amis |
_o__)  |
Ben Finney

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


Re: python-2.7.3 vs python-3.2.3

2016-01-26 Thread Ben Finney
Gene Heskett <ghesk...@wdtv.com> writes:

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

Correction: the default Python 2 is 2.7.3. The default Python 3 is
3.2.3.

Since Python 2 and Python 3 are distinct run-time systems, there's no
single “default Python” in Debian Wheezy.

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

Correct. If you have a program needing Python 3, you should ignore the
Python 2 system and only look at Python 3.

> Can/will they co-exist peacefully?

Yes.

-- 
 \ “Broken promises don't upset me. I just think, why did they |
  `\ believe me?” —Jack Handey |
_o__)          |
Ben Finney

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


Re: How do I add 18 seconds to an ISO-8601 String in Python?

2016-01-23 Thread Ben Finney
Robert James Liguori <gliesia...@gmail.com> writes:

(I've corrected the Subject field. The standard you're referring to is
ISO 8601, I believe.)

> How do I add 18 seconds to this string in Python?
>
> 2000-01-01T16:36:25.000Z

Two separate parts:

* How do I get a timestamp object from a text representation in ISO 8601
  format?

* How do I add 18 seconds to a timestamp object?

Parsing a text representation of a timestamp to get a timestamp object
is done with ‘datetime.strptime’ from the Python standard library
<URL:https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime>::

>>> import datetime
>>> foo_timestamp_text = "2000-01-01T16:36:25.000Z"
>>> iso8601_format = "%Y-%m-%dT%H:%M:%S.%fZ"
>>> foo_timestamp = datetime.datetime.strptime(foo_timestamp_text, 
iso8601_format)
>>> foo_timestamp
datetime.datetime(2000, 1, 1, 16, 36, 25)

Arithmetic on timestamps is done using the ‘datetime.timedelta’ type
<URL:https://docs.python.org/3/library/datetime.html#timedelta-objects>::

>>> increment = datetime.timedelta(seconds=18)
>>> increment
datetime.timedelta(0, 18)
>>> foo_timestamp + increment
datetime.datetime(2000, 1, 1, 16, 36, 43)

-- 
 \“You don't change the world by placidly finding your bliss — |
  `\you do it by focusing your discontent in productive ways.” |
_o__)   —Paul Z. Myers, 2011-08-31 |
Ben Finney

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


Re: How do I add 18 seconds to an ISO-8601 String in Python?

2016-01-23 Thread Ben Finney
Robert James Liguori <gliesia...@gmail.com> writes:

> Thank you so much!  Btw, how do I convert back to ISO-8301?

You are consistently referring to “ISO 8301”, but I am confident that
you are not intending to talk about:

ISO 8301: Thermal insulation -- Determination of steady-state
thermal resistance and related properties -- Heat flow meter
apparatus
<URL:http://www.iso.org/iso/catalogue_detail.htm?csnumber=15421>

Please take care to refer to the correct standard code for the standard
you're referencing :-)

-- 
 \ “You say I took the name in vain / I don't even know the name / |
  `\But if I did, well, really, what's it to you?” —Leonard Cohen, |
_o__) _Hallelujah_ |
Ben Finney

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


Re: How to simulate C style integer division?

2016-01-21 Thread Ben Finney
Shiyao Ma <i...@introo.me> writes:

> I wanna simulate C style integer division in Python3.

I'm not sure I know exactly what behaviour you want (“C style” may mean
different things to each of us).

I'll point out that Python's ‘//’ operator specifies floor division
<URL:https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations>.

-- 
 \   “Timid men prefer the calm of despotism to the boisterous sea |
  `\of liberty.” —Thomas Jefferson |
_o__)          |
Ben Finney

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


Refactoring in a large code base (was: importing: what does "from" do?)

2016-01-21 Thread Ben Finney
Rustom Mody <rustompm...@gmail.com> writes:

> You may find this strategy useful:
> https://pchiusano.github.io/2015-04-23/unison-update7.html
>
> particularly the section "Limitations of refactoring via modifying
> text files in place, and what to do instead"

A direct link to that section is
<URL:https://pchiusano.github.io/2015-04-23/unison-update7.html#refactoring-lessons>.

The author points out there are times when a code base is large and
complex enough that refactoring puts the programmer in a state of not
knowing whether they're making progress, because until the whole
refactoring is complete the errors just cascade and it's hard to tell
which ones are relevant.

That’s bad for two reasons. Without this feedback, you may be
writing code that is making things worse, not better, building
further on faulty assumptions. But more than the technical
difficulties, working in this state is demoralizing, and it kills
focus and productivity.

All right, so what do we do instead? Should we just avoid even
considering any codebase transformations that are intractable with
the “edit and fix errors” approach? No, that’s too conservative.
Instead, we just have to *avoid modifying our program in place*.
This lets us make absolutely any codebase transformation while
keeping the codebase compiling at all times. Here’s a procedure,
it’s quite simple […]


<URL:https://pchiusano.github.io/2015-04-23/unison-update7.html#refactoring-lessons>

The technique is not presented as flawless, and interesting trade-offs
are discussed. Quite an interesting article.

-- 
 \   “Science and religion are incompatible in the same sense that |
  `\   the serious pursuit of knowledge of reality is incompatible |
_o__)   with bullshit.” —Paul Z. Myers, 2010-03-14 |
Ben Finney

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


Re: Single format descriptor for list

2016-01-20 Thread Ben Finney
Paul Appleby <pap@nowhere.invalid> writes:

> In BASH, I can have a single format descriptor for a list:
> […]
> Is this not possible in Python?

Not as such; you'll need to treat items differently from sequences of
items.

> Using "join" rather than "format" still doesn't quite do the job:

Right, ‘str.join’ is meant for making a new string by joining
substrings.

What you want is to take each item and *append* some text. You can do
that by constructing a sequence dynamically::

>>> values = range(4, 8)
>>> print("\n".join(
... "{:d}th".format(item) for item in values))
4th
5th
6th
7th

> Is there an elegant way to print-format an arbitrary length list?

In general, if you can figure out an operation you'd like to perform on
each item of a sequence, you may try a generator expression to express
the transformed sequence.

In the above example:

* Express the transformation of the sequence: format each number with
  "{:d}th". This can be done with a generator expression, producing an
  iterable.

* Figure out what to do to the transformed sequence: join them all
  together with "\n" between each item. This can be done by passing the
  transformed iterable as the argument to ‘str.join’.

The built-in collection types – dict, list, set, generator, etc. – are
very powerful in Python because of the built-in syntax for expressing
and interrogating and consuming them. Learning to use them is an
important tool in avoiding more complex and error-prone code.

-- 
 \ “[F]reedom of speech does not entail freedom to have your ideas |
  `\accepted by governments and incorporated into law and policy.” |
_o__)   —Russell Blackford, 2010-03-06 |
Ben Finney

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


Re: "x == None" vs "x is None"

2016-01-17 Thread Ben Finney
<paul.hermeneu...@gmail.com> writes:

> I prefer (x is None) and (x is not None).

There are good reasons to prefer this.

But this is not a good reason:

> This matches the SQL concept of NULL.

That's not really helpful, because it *doesn't* match.

> (X = NULL) is not valid since NULL is not a value and cannot be
> compared with anything.

SQL Null fails comparison with any value. Python ``None`` is a value and
can be compared like any other value.

SQL Null is neither truthy nor falsy; three-value logic is required when
Null can occur. Python ``None`` is falsy by definition, and two-value
(Boolean) logic continues to obtain.

SQL Null is not a value and has no data type. Python ``None`` is an
object and, like any other object, has a type defining the operations
that it can perform.

And so on. While some libraries do conflate SQL Null with Python
``None``, the two concepts really behave quite differently. It is
needlessly misleading to say they “match” in any sense.

I'm in the camp that says, while SQL is quite useful, its NULL is a wart
<URL:https://dba.stackexchange.com/questions/5222/why-shouldnt-we-allow-nulls/6049>.

-- 
 \“… it's best to confuse only one issue at a time.” —Brian W. |
  `\Kernighan and Dennis M. Ritchie, _The C programming language_, |
_o__)         1988 |
Ben Finney

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


Re: licenses

2016-01-09 Thread Ben Finney
"Martinez, Jorge Alberto (GE Aviation)" <jorgealberto.marti...@ge.com>
writes:

> We develop applications here with Python and I want to know if there's
> issues by using. We use NumPy, PyDaqMx, Py Visa

Those are all free software: meaning, every recipient has freedom to
execute, modify, and/or redistribute the work. So long as the code base
you derive from them is also free software, you will not need to take
special care.

If you intend to make a proprietary work (restricting the freedom of
recipients further), you should consult your lawyer about how to go
about that legally.

> How can we cover this licensing?

The simplest way – no need to get lawyers involved – to comply is to
grant a free-software license (e.g. GNU GPL) to all recipients of your
work.

When you want to derive from an existing work but restrict freedom of
your recipients, that's when you need to pay a lawyer for advice. So I
advise you don't make such a restrictive work.

-- 
 \  “The way to build large Python applications is to componentize |
  `\ and loosely-couple the hell out of everything.” —Aahz |
_o__)          |
Ben Finney

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


Re: Is '*args' useful in this example code?

2016-01-04 Thread Ben Finney
Robert <rxjw...@gmail.com> writes:

> I understand now, but I feel the args usage is weird. I don't see any way 
> to use *args and **kwargs in above code. What is your opinion on it?

Can you show example code that you would expect, and specifically what about
the actual code doesn't match what you expect?

-- 
 \“Of course, everybody says they're for peace. Hitler was for |
  `\  peace. Everybody is for peace. The question is: what kind of |
_o__)peace?” —Noam Chomsky, 1984-05-14 |
Ben Finney

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


Re: Is '*args' useful in this example code?

2016-01-04 Thread Ben Finney
Robert <rxjw...@gmail.com> writes:

> On Monday, January 4, 2016 at 9:26:47 PM UTC-5, Ben Finney wrote:
> > Can you show example code that you would expect, and specifically what about
> > the actual code doesn't match what you expect?
>
> Excuse me for the incomplete info previously. 
> If I call it with 
> a = f(3) 
> the result is 12.

Can you show a *very* simple example of the ‘f’ you're talking about?
Contrive a new one, make it behave the same way while keeping it very
short, and once you have that, put that code in your message.

With an actual function to examine it will be much easier to know where
the confusion lies.

-- 
 \   “When a well-packaged web of lies has been sold to the masses |
  `\over generations, the truth will seem utterly preposterous and |
_o__)its speaker a raving lunatic.” —Dresden James |
Ben Finney

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


Re: Is there a way importing a string object?

2016-01-04 Thread Ben Finney
jf...@ms4.hinet.net writes:

> For example,

(Please make the body of your message complete. The “Subject” field
should be a summary of your message's subject, and may not be read as
the first line of your message.)

> name = "test"  # test.py is a module's file
> import name

The standard library ‘importlib’ module exports an API for the import
machinery <URL:https://docs.python.org/3/library/importlib.html>.

You will likely want to use ‘importlib.import_module’
<URL:https://docs.python.org/3/library/importlib.html#importlib.import_module>.

-- 
 \  “The difference between a moral man and a man of honor is that |
  `\   the latter regrets a discreditable act, even when it has worked |
_o__)   and he has not been caught.” —Henry L. Mencken |
Ben Finney

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


Re: GitHub's ³pull request² is proprietary lock-in

2016-01-03 Thread Ben Finney
Christian Gollwitzer <aurio...@gmx.de> writes:

> There are layers. Below your Python code there is CPython, below that
> the C compiler, the OS, and finally the hardware.

Yes. There are continual motivations to take the technology at any of
those levels and make it less free, make it more locked to single
vendors, make it more difficult to migrate our valuable data to a system
under our control.

Asserting that one level is currently less free, is in no measure an
argument to allow a different level to be moved further from the
community's control.

> At some point, nobody cares.

You clearly do care, since you are participating in this discussion and
attempting to argue that people *should not* care.

> In former times, people sent emails with patches attached. Nobody
> complains that those emails are lost to the community.

You make my point for me: Nothing about that method of transferring code
changes was actively controlled by a single vendor, nor gratuitously
centralised, nor handed to an unexaminable, unaccountable system.

> Then somebody invented VCS and all became better. Pull requests are
> nothing but elaborated emails.

Email is decentralised; it has no gratuitous barriers between diverse
implementations of the standards; it has standards that are
energetically guarded against vendor lock-in.

Anyone can take email data from the email server, migrate it to a
different implementation of the same email system, keep it running with
the same data and allow the same people to continue interacting with it
as before.

Those are traits I think a community should require of any system that
controls vital discussions like pull requests.

If GitHub pull requests could be verified to work that way, I would have
no complaint here. Until they do, it is foolish for a community to
willingly put their correspondence data into it.

-- 
 \   “Come on Milhouse, there’s no such thing as a soul! It’s just |
  `\  something they made up to scare kids, like the Boogie Man or |
_o__)  Michael Jackson.” —Bart, _The Simpsons_ |
Ben Finney

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


Re: GitHub's ³pull request² is proprietary lock-in

2016-01-03 Thread Ben Finney
Christian Gollwitzer <aurio...@gmx.de> writes:

> Arguably, the most valuable outcome of the pull request in the end is
> the patch, which is of course contained in the git repository.

Arguably, the most valuable outcome of a database system is the query
result, which is of course contained in the result set of tuples
contained in the response data.

Arguably, the most valuable outcome of a version control system is the
source code tree, which is of course contained in a filesystem directory.

Arguably, the most valuable outcome of a programming language is the
programs we write with it, which is of course contained in the compiled
binary.

By your reasoning, that means we should not care about handing the
control over our database system, our version control system, or our
programming language to a vendor-locked, proprietary, gratuitously
centralised technology.

I hope the analogy makes it clear why that's not an argument I think
anyone would accept as sound.

> I doubt that many people want to go back to see the arguments for a
> certain merge

I doubt many people want to go into the source code for my operating
system and tell me exactly what it's doing, where my data is stored, how
to get it from this operating system to a different one.

My freedom to migrate from that system to a different one when I choose,
is entirely dependent on *anyone* being able to do that, no matter how
few people express an interest where you might see it.

-- 
 \   “There's no excuse to be bored. Sad, yes. Angry, yes. |
  `\Depressed, yes. Crazy, yes. But there's no excuse for boredom, |
_o__)  ever.” —Viggo Mortensen |
Ben Finney

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


Re: GitHub's ³pull request² is proprietary lock-in

2016-01-03 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> On Sun, Jan 3, 2016 at 7:45 PM, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> > Anyone can take email data from the email server, migrate it to a
> > different implementation of the same email system, keep it running
> > with the same data and allow the same people to continue interacting
> > with it as before.
> >
> > Those are traits I think a community should require of any system
> > that controls vital discussions like pull requests.
>
> They are. Ultimately, a GitHub pull request is backed by a git pull
> request. Here's an example:
>
> https://github.com/MikeiLL/appension/pull/187

Yes, of course the VCS data is in Git and therefore can be accessed with
Git. Please stop raising that when *I'm not talking about* the VCS data
alone, I'm talking also about the data of the pull request feature.


The discussion data, code review data, etc. is all part of “GitHub pull
request”. How do we export, along with the VCS data, the data and system
that control the code review discussino and other useful features
entailed by “GitHub pull request”?

How do we get that data and confidently and quickly set up a system
hosted on a different provider that allows everyone involved to continue
the same code reviews and discussions etc. without GitHub?

To my knowledge we can't, short of re-implementing an expressly
proprietary non-standard system against the wishes of the vendor.

That's valuable community data being locked into a single-vendor system,
who explicitly rejects community access to the system and the data
needed to continue on a different provider.

It boggles my mind that so many people – even when the conversation has
directly raised the notion of different layers of technology that
control different layers of valuable data – blithely ignore the fact
that *the discussion itself* is dependent on a software system and data.

Control over that software system and data is important to control over
the valuable discussions, just as control over the VCS system and data
is important to control over the valuable source code.


Conversely, as Ned Batchelder points out, without all the proprietary
vendor lock-in centralised features, GitHub is a fairly unimpressive Git
hosting provider. The “but Git is free software, no one is locked in!”
is trivially true, and has an obvious response in “then there's no good
reason to move anything there”.

Please, those who are going to advocate for GitHub especially over other
Git hosting providers because it has specially valuable features, be
honest that you're advocating moving control of valuable information
away from the community that values them.

-- 
 \   “First things first, but not necessarily in that order.” —The |
  `\  Doctor, _Doctor Who_ |
_o__)  |
Ben Finney

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


Re: Trailing zeros of 100!

2016-01-02 Thread Ben Finney
Robin Koch <robin.k...@t-online.de> writes:

> Am 02.01.2016 um 22:57 schrieb Chris Angelico:
> >>> But did you actually test it?
> >>
> >> Yes, should work for n >= 1.

By “test it”, Chris of course means test it *by implementing it in a
program and running that program in Python*.

> >> Why do you ask?
> >
> > Your "should work" does not sound good as a response to "actually
> > test". Normally I would expect the response to be "Yes, and it
> > worked for me" (maybe with a log of an interactive session).
>
> Well, honestly, I trusted my math and didn't thought much about the
> technical limitations.

That's why it's good to actually test the hypothesis in a real computer
program, run on the actual computer system you're going to use.

Computers are physical systems, with technical compromises to the
physical constraints under which they were built.

They are not perfect implementations of our ideal mathematics, and
testing the mathematics is no guarantee the mathematical assumptions
will survive your program unscathed.

So, a request “Did you actually test it?” is both a polite reminder to
do that, and an attempt to get you to do so if you didn't.

If you didn't, then answering “yes” is wasting everyone's time.

-- 
 \   “As the most participatory form of mass speech yet developed, |
  `\the Internet deserves the highest protection from governmental |
_o__)   intrusion.” —U.S. District Court Judge Dalzell |
Ben Finney

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


GitHub's “pull request” is proprietary lock-in (was: We will be moving to GitHub)

2016-01-02 Thread Ben Finney
Michael Torrie <torr...@gmail.com> writes:

> On 01/02/2016 12:02 AM, Ben Finney wrote:
> > GitHub's “pull request” workflow is entirely proprietary and can
> > only be done within GitHub.
>
> Really?  This seems like an entirely artificial github requirement.

Yes, it is.

> There's absolutely no reason why github couldn't do a pull request from
> any arbitrary, valid git url.

Right. The proprietary GitHub “pull request” has many more features
(including a code review tool and discussion thread that are
automatically tied to the pull request) which make it attractive.

The fact these features (unlike Git) are wholly proprietary, and the
valuable processes and data they generate cannot be exported and
continued easily in another instance when a community chooses, are what
makes GitHub's “pull request” an attractive nuisance.

That and other vendor-locked workflow aspects of GitHub makes it a poor
choice for communities that want to retain the option of control over
their processes and data.

-- 
 \ “Try adding “as long as you don't breach the terms of service – |
  `\  according to our sole judgement” to the end of any cloud |
_o__)  computing pitch.” —Simon Phipps, 2010-12-11 |
Ben Finney

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


Re: We will be moving to GitHub

2016-01-01 Thread Ben Finney
Zachary Ware <zachary.ware+pyl...@gmail.com> writes:

> On Jan 1, 2016 2:35 PM, "Paul Rubin" <no.email@nospam.invalid> wrote:
> > Will everyone wanting to submit patches be required to use a Github
> > account? Or will it be enough to put the patch in an outside repo
> > and link to it in the Python issue tracker? I'm glad that (it sounds
> > like) no Github account will be needed to submit bug reports.
>
> Correct, no GitHub account will be required for interactions on the
> bugs.python.org tracker, and a patch can move all the way through to
> commit entirely on the b.p.o tracker (just as currently).

My experience with contributing to repositories hosted on GitHub, from
repositories hosted elsewhere, necessitates the question:

What is being done to stave off the common response, addressed by GitHub
users to people submitting a change as a link to their Git repository,
of “can you please submit that as a GitHub pull request”?

That common response makes for an unnecessary and IMO unacceptable
pressure toward centralisation. GitHub's “pull request” workflow is
entirely proprietary and can only be done within GitHub.

What will be done to ensure other Git repositories remain on a level
playing field not only technically, but socially?

-- 
 \ “Ours is a world where people don't know what they want and are |
  `\   willing to go through hell to get it.” —Donald Robert Perry |
_o__)          Marquis |
Ben Finney

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


Re: We will be moving to GitHub

2016-01-01 Thread Ben Finney
Terry Reedy <tjre...@udel.edu> writes:

> On 1/1/2016 4:08 PM, Zachary Ware wrote:
> > There were three reasons given in Brett's decision message:
> >
> > 1. No major distinguishing features between GitHub or GitLab

It seems “complete source code available and freely licensed, allowing
the community to implement the entire tool set elsewhere, without any
need to consult the existing service provider” – i.e. community control
over their own tools – is not considered a major distinguishing feature.

> In particular, some inactive contributors who use git and github
> apparently emailed Brett to say that they might re-activate if they
> could use the process they otherwise use all the time instead of
> Python's idiosyncratic workflow.

This is a grave concern. A strong implication of “use the process they
otherwise use all the time” is that these people expect to use GitHub's
proprietary, centralised, single-vendor workflow tools. This implication
necessarily entails rejecting contributions from other community members
who don't use those single-vendor tools.

The decision to take tools that were expressly designed to escape
single-vendor centralisation, and then willingly build single-vendor
workflows around them which divide the free software community along
vendor lines, is a foolish and worrying trend. I am alarmed to see the
Python core team go further down that path.

-- 
 \   “… whoever claims any right that he is unwilling to accord to |
  `\ his fellow-men is dishonest and infamous.” —Robert G. |
_o__)   Ingersoll, _The Liberty of Man, Woman and Child_, 1877 |
Ben Finney

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


Re: using __getitem()__ correctly

2015-12-31 Thread Ben Finney
"Charles T. Smith" <cts.private.ya...@gmail.com> writes:

> On Thu, 31 Dec 2015 11:21:59 +1100, Ben Finney wrote:
>
> > Tersely: the relationship between an object and its attributes, is
> > not the same as the relationship between a dictionary and its items.
>
> I understand this to mean that the relationship between a dictionary
> and its items is less complex than the relationship between an object
> and its attributes.

That's not implied by the above, nor is it what I meant.

I meant that the relationship is not the same.

* The attributes of an object ‘foo’ are what you access via ‘foo.bar’
  syntax. You don't access those attributes via ‘foo[bar]’.

* The items of a dictionary ‘foo’ are what you access via ‘foo[bar]’
  syntax. You don't access those items via ‘foo.bar’.

That's an important, and real, difference. And it's much better learned
as part of a comprehensive course on Python, not in a deep dive into the
magic methods.

I really don't know why it's been so difficult to talk about this, but I
hope my meaning is clear now.

Have a wonderful end of year, folks.

-- 
 \  “There are no chaplains in foxholes.” —Sergeant Justin |
  `\  Griffith, 2011-07-27 |
_o__)          |
Ben Finney

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


Re: raise None

2015-12-31 Thread Ben Finney
Oscar Benjamin <oscar.j.benja...@gmail.com> writes:

> Exactly. The critical technique is looking at the traceback and
> splitting it between what's your code and what's someone else's.
> Hopefully you don't need to look at steves_library.py to figure out
> what you did wrong. However if you do need to look at Steve's code
> you're now stumped because he's hidden the actual line that raises.

+1.

As best I can tell, Steven is advocating a way to obscure information
from the traceback, on the assumption the writer of a library knows that
I don't want to see it.

Given how very often such decisions make my debugging tasks needlessly
difficult, I'm not seeing how that's a desirable feature.

-- 
 \   “Firmness in decision is often merely a form of stupidity. It |
  `\indicates an inability to think the same thing out twice.” |
_o__)    —Henry L. Mencken |
Ben Finney

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


Re: raise None

2015-12-31 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> On Fri, Jan 1, 2016 at 7:18 AM, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> > Given how very often such decisions make my debugging tasks
> > needlessly difficult, I'm not seeing how that's a desirable feature.
>
> What Steven's actually advocating is removing a difference between
> Python code and native code.

Sure, but his proposal is to move in the direction of *less* debugging
information.

If I could have the traceback continue into the C code and tell me the
line of C code that raised the exception, *that's* what I'd choose.

The debugging information barrier of the C–Python boundary is a
practical limitation, not a desirable one. I think those barriers should
be as few as possible, and don't agree with enabling more of them.

-- 
 \ “Welchen Teil von ‘Gestalt’ verstehen Sie nicht?  [What part of |
  `\‘gestalt’ don't you understand?]” —Karsten M. Self |
_o__)      |
Ben Finney

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


Re: Where are we in the Python 3 transition?

2015-12-31 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> On Fri, 1 Jan 2016 03:12 am, Mark Lawrence wrote:
>
> > http://www.snarky.ca/the-stages-of-the-python-3-transition
>
> Nice link Mark, thanks.

People sometimes ask me how much Python 2 code I'll be maintaining by
the time official Python 2 support ends.

I tell them I can't say, because I don't have 2020 vision.

-- 
 \   “Science shows that belief in God is not only obsolete. It is |
  `\also incoherent.” —Victor J. Stenger, 2001 |
_o__)      |
Ben Finney

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


Re: using __getitem()__ correctly

2015-12-30 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> On Thu, 31 Dec 2015 10:13 am, Ben Finney wrote:
>
> > You may be familiar with other languages where the distinction
> > between “attribute of an object” is not distinct from “item in a
> > dictionary”. Python is not one of those languages; the distinction
> > is real and important.
>
> I'm not sure what distinction you're referring to, can you explain?

Tersely: the relationship between an object and its attributes, is not
the same as the relationship between a dictionary and its items.

> Obviously there is a syntax difference between x.attr and x['key']

Not merely syntax; the attributes of an object are not generally
available as items of the container.

> but attributes *are* items in a dictionary

That's like saying everything in Python is a number: it conflates the
implementation with the semantics.

The distinction between a Python integer and a Python boolean value is
real and important, despite the incidental fact of their both being
implemented as numbers.

> Either the instance __dict__, the class __dict__, or a superclass
> __dict__.

No, I'm not referring to the ‘__dict__’ attribute of an object; I'm
referring to the object itself.

To talk about the attributes of an object ‘foo’ is distinct from talking
about the items in a dictionary ‘foo’. That distinction is real, and
important.

-- 
 \   “… correct code is great, code that crashes could use |
  `\   improvement, but incorrect code that doesn’t crash is a |
_o__)        horrible nightmare.” —Chris Smith, 2008-08-22 |
Ben Finney

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


Validation in Python (was: raise None)

2015-12-30 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> I have a lot of functions that perform the same argument checking each
> time:

Not an answer to the question you ask, but: Have you tried the data
validation library “voluptuous”?

Voluptuous, despite the name, is a Python data validation library.
It is primarily intended for validating data coming into Python as
JSON, YAML, etc.

It has three goals:

Simplicity.
Support for complex data structures.
Provide useful error messages.

<URL:https://pypi.python.org/pypi/voluptuous/>

Seems like a good way to follow Don't Repeat Yourself in code that needs
a lot of validation of inputs.

-- 
 \ “It's my belief we developed language because of our deep inner |
  `\  need to complain.” —Jane Wagner, via Lily Tomlin |
_o__)          |
Ben Finney

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


Re: Newbie: How to convert a tuple of strings into a tuple of ints

2015-12-30 Thread Ben Finney
otaksoftspamt...@gmail.com writes:

> How do I get from here
>
> t = ('1024', '1280')
>
> to 
>
> t = (1024, 1280)

Both of those are assignment statements, so I'm not sure what you mean
by “get from … to”. To translate one assignment statement to a different
assignment statement, re-write the statement.


But I think you want to produce a new sequence from an existing sequence.

The ‘map’ built-in function is useful for that::

sequence_of_numbers_as_text = ['1024', '1280']
sequence_of_integers = map(int, sequence_of_numbers_as_text)

That sequence can then be iterated.

Another (more broadly useful) way is to use a generator expression::

sequence_of_integers = (int(item) for item in sequence_of_numbers_as_text)


If you really want a tuple, just pass that sequence to the ‘tuple’
callable::

tuple_of_integers = tuple(
int(item) for item in sequence_of_numbers_as_text)

or::

tuple_of_integers = tuple(map(int, sequence_of_numbers_as_text))

-- 
 \  “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\   of Faith_, 2004 |
_o__)          |
Ben Finney

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


Re: using __getitem()__ correctly

2015-12-30 Thread Ben Finney
"Charles T. Smith" <cts.private.ya...@gmail.com> writes:

> I don't understand this distinction between an "attribute" and a "dict
> item".

When did you most recently work through the Python tutorial
<URL:https://docs.python.org/3/tutorial/>> You may want to work through
it again, from start to finish and exercising each example, to be sure
you have a solid understanding of basic concepts like these.

In brief: Objects have attributes; looking up an attribute on an object
has specific syntax. Dictionaries are collections of items; the items
are looked up by key, using a quite different syntax. Those two
different syntaxes translate to distinct special methods.

You may be familiar with other languages where the distinction between
“attribute of an object” is not distinct from “item in a dictionary”.
Python is not one of those languages; the distinction is real and
important. You'll need to do some remedial learning of Python, and I
recommend working through the Python tutorial.

-- 
 \“But it is permissible to make a judgment after you have |
  `\examined the evidence. In some circles it is even encouraged.” |
_o__)    —Carl Sagan, _The Burden of Skepticism_, 1987 |
Ben Finney

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


Re: raise None

2015-12-30 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> Traceback (most recent call last):
>   File "spam", line 19, in this
>   File "spam", line 29, in that
>   File "spam", line 39, in other
>   File "spam", line 5, in _validate
> ThingyError: ...
>
> and the reader has to understand the internal workings of _validate
> sufficiently to infer that this exception is not a bug in _validate
> but an expected failure mode of other when you pass a bad argument.

This point seems to advocate for suppressing *any* code that
deliberately raises an exception. Is that your intent?

-- 
 \  “I don't want to live peacefully with difficult realities, and |
  `\ I see no virtue in savoring excuses for avoiding a search for |
_o__)    real answers.” —Paul Z. Myers, 2009-09-12 |
Ben Finney

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


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

2015-12-28 Thread Ben Finney
lee <malitic...@gmail.com> writes:

> I'm still stuck on this, any Rescuer?

You appear to be yet another different person asking about this homework
assignment.

Please:

* This forum is not suitable for the kind of close attention to very
  basic learning. Take this discussion to the ‘tutor’ forum
  <URL:https://mail.python.org/mailman/listinfo/tutor>, which is much
  better focussed on close collaborative mentoring of beginners.

* Choose a single spokesperson, and have that person provide continuity
  in the discussion by responding consistently from the same email
  address.

* Learn proper email etiquette (plain text messages, quoted material,
  give sufficient context, etc.) to help the community understand what
  each message is about.

-- 
 \“Holy uncanny photographic mental processes, Batman!” —Robin |
  `\   |
_o__)          |
Ben Finney

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


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

2015-12-28 Thread Ben Finney
Prince Udoka <princeud...@gmail.com> writes:

> pls 4give my use of language

Your messages are becoming quite disruptive and inconsiderate of your
readers.

Please take more care with each message, don't bombard us with a series
of poorly-thought-out, hyper-abbreviated messages.

Please take extreme-beginner discussions to the ‘tutor’
<URL:https://mail.python.org/mailman/listinfo/tutor> forum.

-- 
 \   “All progress has resulted from people who took unpopular |
  `\  positions.” —Adlai Stevenson |
_o__)          |
Ben Finney

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


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread Ben Finney
jf...@ms4.hinet.net writes:

> Thank you, Ben. It's amazing that you seem to know every piece of
> Python information hiding in the web:-)

You're welcome, I'm glad to help. As for the “hiding”, the answer is in
the Python documentation itself.

> see this question listed in python core language's Q makes me feel
> better for I am not the only one who commit this kind of crime.

Never feel embarrassed of not knowing something; we should all be active
on the edge of our own ignorance. The embarrassment would be in not
seeking to improve our understanding.

> I should read this Q throughly before going any further.

Searching in the official documentation, and in archives of community
forums, is an essential skill to learn for a programmer. I wish you good
fortune in improving that skill :-)

-- 
 \  “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\   of Faith_, 2004 |
_o__)          |
Ben Finney

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


Re: please can i get help on this problem

2015-12-26 Thread Ben Finney
Please help us by choosing a descriptive Subject field. The one you've
chosen tells us *nothing* useful.

As it turns out, I can't get anything useful from your message either:

Prince Udoka <princeud...@gmail.com> writes:

> here is my work, but i dont know what i ave done wrong:

Neither do I. What is confusing you, in particular? Describe what you're
confused by (for example, what behaviour are you seeing, and how is that
different from what you expect?). Summarise that behaviour in a short
phrase and put it in the Subject field.

-- 
 \“Please to bathe inside the tub.” —hotel room, Japan |
  `\   |
_o__)          |
Ben Finney

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


Re: please can i get help on this problem

2015-12-26 Thread Ben Finney
Prince Udoka <princeud...@gmail.com> writes:

> sir does this make sense:

Referring to the whole of a community as “sir” is not only too formal,
it also betrays a different error: you seem to think you're in a
one-on-one dialogue devoted to your issues.

Please, instead of trying to make your messages more polite (your
phrasing is already plenty polite enough), do us the respect of spending
time on the *content* of your message.

As has been asked of you many times now: When you have a question,
please make it specific and answerable.

Describe what *specifically* is confusing or concerning you; describe
*specifically* what you did, what you expected to happen, and what
happened instead.

Putting effort into making your messages easiler to comprehend will be
far more polite than merely calling us collectively “sir”. It will have
the added benefit of getting you more useful answers.

-- 
 \  “When cryptography is outlawed, bayl bhgynjf jvyy unir |
  `\  cevinpl.” —Anonymous |
_o__)          |
Ben Finney

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


Re: Importing constantly changing variables

2015-12-26 Thread Ben Finney
ariklapid.s...@gmail.com writes:

> Hello everyone !
> First of all, excuse me for my horrible English.

As is often the case with people who make this apology, your English is
far better than most native English speakers can use any other language
:-)

> A file named "sensors.py" imports varying values from physical
> sensors. These values are constantly changing. 

Such values, then, should not be obtained from a Python ‘import’.

Instead, you need to come up with a data transfer protocol, or (more
likely) make use of an existing one. Your running program will make
function calls that get the data from “the outside world” – a file, or a
network interface, or some other input to the program.

So to solve this you will need to know the specifics of how the device
connects to the computer, what interfaces it presents for obtaining the
data at run time, and what Python libraries you can use for accessing
that interface.

-- 
 \   “If you do not trust the source do not use this program.” |
  `\—Microsoft Vista security dialogue |
_o__)          |
Ben Finney

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


Re: A newbie quesiton: local variable in a nested funciton

2015-12-25 Thread Ben Finney
jf...@ms4.hinet.net writes:

> In the first situation, the local variable 'counter' can be referenced
> correctly. But in the second, why a statement added after the print()
> statement can makes this variable "disappear", even the print() won't
> do the right thing. Isn't it wired? please help!

The Python FAQ answers this, even using an example the same as yours
<URL:https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value>.

-- 
 \  “… a Microsoft Certified System Engineer is to information |
  `\ technology as a McDonalds Certified Food Specialist is to the |
_o__)   culinary arts.” —Michael Bacarella |
Ben Finney

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


Re: Idiom for this case?

2015-12-24 Thread Ben Finney
KP <kai.pet...@gmail.com> writes:

> Given:
>
> cfg =  {'c': ('3840', '1024'),
>'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, 
>'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')},
>'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}}
>
> for config in cfg:
> if config != 'canvas':
> print config

Given the above data, none of the keys equal 'canvas', so the comparison
is redundant if that's the data set.

The chosen names are also confusing. It implies that each item of ‘cfg’
is a ‘config’. Can you choose names that better communicate the
semantics of that data structure?

> Is there an idiom that combines the 'for...' & the 'if..' lines into one?

This is an opportunity to learn generator expressions::

for item in (x for x in cfg if x != canvas):
print item

<URL:https://docs.python.org/3/reference/expressions.html#generator-expressions>

You will learn about these by working through the Python tutorial, from
beginning to end <URL:https://docs.python.org/3/tutorial/>. Don't skip
anything, and experiment with each example to understand it before
continuing.

-- 
 \  “Anyone who believes exponential growth can go on forever in a |
  `\finite world is either a madman or an economist.” —Kenneth |
_o__)         Boulding |
Ben Finney

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


Re: Unable to use python 3.5

2015-12-23 Thread Ben Finney
Chris Warrick <kwpol...@gmail.com> writes:

> On 23 December 2015 at 07:38, Ankit Deshmukh <ankit7a...@gmail.com> wrote:
> > I am maters student in India,
>
> We don’t care (expect that you made a typo there).
>
> > […] When in use “pip install numpy” is shows unable to find
> > *‘vcvarsall.bat’* I don’t know how to fix it. I tried several things
> > nothing works.
>
> You clearly haven’t tried enough, as this question is answered by a
> simple Google search. […]
>
> A student who wants to work in programming should be able to find
> answers to their questions online. And know better than putting a
> phone number in their e-mail signature for the whole world to see.

Chris, I found your response to be needlessly condescending and hostile
to a newcomer. The original request was well-formed, and did not warrant
such a slap-down.

Please work to keep our community welcoming, and assume good faith in
newcomers.

-- 
 \ “Do unto others twenty-five percent better than you expect them |
  `\  to do unto you. (The twenty-five percent is [to correct] for |
_o__)        error.)” —Linus Pauling's Golden Rule |
Ben Finney

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


Re: What interface is a ‘Popen.stdout’ presenting?

2015-12-23 Thread Ben Finney
eryk sun <eryk...@gmail.com> writes:

> On Wed, Dec 23, 2015 at 7:36 PM, Ben Finney <ben+pyt...@benfinney.id.au> 
> wrote:
> > So how do I get from a Python 2 ‘file’ object, to whatever
> > ‘io.TextIOWrapper’ wants?
>
> I would dup the file descriptor and close the original file. Then open
> the file descriptor using io.open

Thanks. Okay, now I reveal (I apologise for not making this clear
initially) that I need the *same* code to work with pseudo files created
by the unit test suite: files with no underlying file handle.

That is, I need the same code to accept:

* A Python 2 ‘file’ instance as emitted by many stdlib functions.
* A Python 3 ‘io.*’ file object as emitted by many stdlib functions.
* A pseudo-file (e.g. ‘io.BytesIO’) test double.

With any of those, I need the code to wrap a stream already open in
“binary” mode, and give me a wrapper (e.g. ‘io.TextIOWrapper’) to read
and/or write text on that stream.

-- 
 \ “It is hard to believe that a man is telling the truth when you |
  `\  know that you would lie if you were in his place.” —Henry L. |
_o__)          Mencken |
Ben Finney

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


What interface is a ‘Popen.stdout’ presenting?

2015-12-23 Thread Ben Finney
Howdy all,

When I want to wrap a binary stream to provide a text stream, such as
the ‘Popen.stdout’ attribute from a subprocess, I can use
‘io.TextIOWrapper’.

That works on Python 3::

$ python3
Python 3.4.4rc1 (default, Dec  7 2015, 11:09:54)
[GCC 5.3.1 20151205] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import io
>>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], 
stdout=subprocess.PIPE)
>>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout)
>>> type(gnupg_stdout)


but not Python 2::

$ python2
Python 2.7.11 (default, Dec  9 2015, 00:29:25)
[GCC 5.3.1 20151205] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import io
>>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], 
stdout=subprocess.PIPE)
>>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'file' object has no attribute 'readable'

I'm trying to write code that, as far as practicable, works unchanged on
Python 2 and Python 3.

How do I wrap an arbitrary byte stream – already opened, such as a
‘Popen.stdout’ attribute – in a text wrapper with a particular encoding?

-- 
 \    “With Lisp or Forth, a master programmer has unlimited power |
  `\ and expressiveness. With Python, even a regular guy can reach |
_o__)   for the stars.” —Raymond Hettinger |
Ben Finney

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


Re: What interface is a ‘Popen.stdout’ presenting?

2015-12-23 Thread Ben Finney
I left the Subject field with the wrong question. The immediate answer
is “it presents the ‘file’ interface”. The consequent questions remain:

Ben Finney <ben+pyt...@benfinney.id.au> writes:

> $ python2
[…]
> >>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout)
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'file' object has no attribute 'readable'
>
> I'm trying to write code that, as far as practicable, works unchanged
> on Python 2 and Python 3.
>
> How do I wrap an arbitrary byte stream – already opened, such as a
> ‘Popen.stdout’ attribute – in a text wrapper with a particular
> encoding?

It appears the Python 2 ‘file’ type doesn't implement a “buffer” as
expected by ‘io.TextIOWrapper’.

So how do I get from a Python 2 ‘file’ object, to whatever
‘io.TextIOWrapper’ wants?

-- 
 \ “Nature is trying very hard to make us succeed, but nature does |
  `\   not depend on us. We are not the only experiment.” —Richard |
_o__)           Buckminster Fuller, 1978-04-30 |
Ben Finney

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


Re: convert to python code

2015-12-22 Thread Ben Finney
Rodrick Brown <rodrick.br...@gmail.com> writes:

> Tried a few things but can't seem to get it right any help ?

To convert it to Python code, you'll need to actually write some code.

Please show here in this forum the actual Python code which is not
behaving how you want, and say *exactly* what it's doing different from
what you expect (and, preferably, explain why you expect it to behave
differently).

-- 
 \  “Do I believe in God? … without clarification of a kind I have |
  `\never seen, I don’t know whether I believe or don’t believe in |
_o__)whatever a questioner has in mind.” —Noam Chomsky |
Ben Finney

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


Re: Why doesn't os.remove work on directories?

2015-12-22 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> This is surprising to anyone accustomed to the POSIX C remove
> function, which can remove either files or directories.  Is there
> any known rationale for this decision?

No, I don't know a rationale for implementing it this way.

I expect the explanation will be “mere historical accident”. My
evidence-free reconstruction of the events leading to the current state
of play:

1.  ‘os.unlink’ implemented, using C ‘unlink(3)’. Because ‘unlink(2)’
on a directory will cause an error, Python raises OSError for this.

2.  ‘os.remove’ implemented; “This is identical to the unlink() function
documented below.”.

3.  Backward compatibility concerns (existing code might depend on
‘os.remove’ raising OSError for a directory argument) justify
keeping the existing behaviour.

What you're looking for amounts to “why was ‘os.remove’ implemented as a
synonym of ‘unlink(3)’ instead of ‘remove(3)’?”.

I don't know why that behaviour was chosen, and I consider it a wart.

-- 
 \“… no testimony can be admitted which is contrary to reason; |
  `\   reason is founded on the evidence of our senses.” —Percy Bysshe |
_o__)Shelley, _The Necessity of Atheism_, 1811 |
Ben Finney

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


Meaning and purpose of the Subject field (was: Ignore error with non-zero exit status)

2015-12-21 Thread Ben Finney
Ian Kelly <ian.g.ke...@gmail.com> writes:

> Better yet, please don't change the Subject header for trivial reasons
> in the first place.

When the subject of the ongoing discussion changes, it's normal to
change the Subject field accordingly.

I agree with your admonition against trivial alterations to that field;
I hope you agree with me that it is not trivial, but rather is normal
and helpful, to update the Subject field to track significant changes in
the subject of the discussion.

> This isn't just a Usenet group; it's also a mailing list, and many
> MUAs rely on the Subject header for proper threading.

If such MUAs do that, they're misinterpreting the Subject field. Other
fields are available with the explicit meaning of relating messages to
each other regardless of what they discuss.

If the correct fields are being mangled, then the correct place to apply
pressure is on those who can fix that error. Let's not overload the
Subject field to make up the lack.

-- 
 \   “Self-respect: The secure feeling that no one, as yet, is |
  `\suspicious.” —Henry L. Mencken |
_o__)          |
Ben Finney

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


Categorising strings on meaningful–meaningless spectrum (was: Catogorising strings into random versus non-random)

2015-12-20 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> Let's call the second group "random" and the first "non-random",
> without getting bogged down into arguments about whether they are
> really random or not.

I think we should discuss it, even at risk of getting bogged down. As
you know better than I, “random” is not an observable property of the
value, but of the process that produced it.

So, I don't think “random” is at all helpful as a descriptor of the
criteria you need for discriminating these values.

Can you give a better definition of what criteria distinguish the
values, based only on their observable properties?

You used “meaningless”; that seems at least more hopeful as a criterion
we can use by examining text values. So, what counts as meaningless?

> I wish to process the strings and automatically determine whether each
> string is random or not. I need to split the strings into three groups:
>
> - those that I'm confident are random
> - those that I'm unsure about
> - those that I'm confident are non-random
>
> Ideally, I'll get some sort of numeric score so I can tweak where the
> boundaries fall.

Perhaps you could measure Shannon entropy (“expected information value”)
<URL:https://en.wikipedia.org/wiki/Entropy_%28information_theory%29> as
a proxy? Or maybe I don't quite understand the criteria.

-- 
 \  “Actually I made up the term “object-oriented”, and I can tell |
  `\you I did not have C++ in mind.” —Alan Kay, creator of |
_o__)        Smalltalk, at OOPSLA 1997 |
Ben Finney

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


Re: How does one distribute Tkinter or Qt GUI apps Developed in Python

2015-12-16 Thread Ben Finney
Bruce Whealton <futurewavewebdevelopm...@gmail.com> writes:

> What seems to be blatantly missing is how this would be distributed.

Distributing programs so that recipients can run them is an ongoing
problem.

Operating systems arenecessarily involved, and since not every recipient
uses the exact same configuration of the exact same version of the exact
same operating system, the means of getting your program installed and
working on their computer will differn significantly.

> In the first mentioned tutorial from Lynda.com the Tkinter app was
> related to a web page. However, the browser cannot run Python Bytecode
> or Python Scripts.

Web applications are attractive for developers in large part because web
standards are hard-won oases of compatibility across different operating
systems.

It is no accident that operating system vendors (Microsoft, Apple,
Google, etc.) keep trying to carve out attractive incompatible features
and areas of their system, to ensure some applications using those
non-standard features will only run smoothly on the operating system
controlled by that vendor.

> Surely, one is going to want to create GUI apps for users that are not
> Python Developers.

Indeed, and toolkits like Tkinter make this refreshingly easy to do in a
way that works across all mainstream operating systems today.

What is not standardised is installation of software for end users.

> I would want to package in some way so that when launched, it installs
> whatever is needed on the end user's computer. How is this done? 

This is the “bootstrap” problem: a Python program is only useful once
there is a Python interpreter installed and working on the recipient's
system. You still need to get the appropriate version of Python
installed on that recipient's operating system.

You'll need to know your target audience, make decisions about the set
of operating systems you want to support, and build a package for each
one.

> Are there common practices for this?

Common to all mainstream operating systems? No, installation of software
is one major area that makes operating systems incompatible.


For GNU+Linux systems: Up-to-date Python is easily installed as a
dependency of your package. Target the version(s) of Python you know
your recipients will have, and declare a dependency in the operating
system package you make.

For OS X: There is an old, minimal Python installation, which is
probably too old for you to target. I am not aware of a good dependency
resolution system; you'll need to get the latest stable Python onto the
recipient's system with their help.

For iOS: I'm not aware of a good way to install Python programs on iOS.

For Android: There is a decent dependency system, but again I'm not
aware of a good standard way to have a Python program install onto
Android.

For MS Windows: There is definitely no good dependency resolution system
for you to use. You'll need to bundle a Python interpreter with your
program as a single installable file. This makes your program much
larger and redundant with any other such program on the system; this is
what Microsoft has doomed developers to work with.

-- 
 \  “If we have to give up either religion or education, we should |
  `\  give up education.” —William Jennings Bryan, 1923-01 |
_o__)          |
Ben Finney

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


Re: TypeError: 'float' object is not iterable

2015-12-16 Thread Ben Finney
scarrer...@gmail.com writes:

> Someone stealing my points, I don't know how someone do it, but they
> had stolen some of my points.

Make new points, summarise them succinctly in the Subject field, and be
prepared to defend them.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but there's still a bug stuck in here from last time.” |
_o__)   —_Pinky and The Brain_ |
Ben Finney

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


EAFP and LBYL (was: Try: rather than if :)

2015-12-14 Thread Ben Finney
Vincent Davis <vinc...@vincentdavis.net> writes:

> In the code below try is used to check if handle has the attribute name. It
> seems an if statement could be used. Is there reason one way would be
> better than another?

The Python community refers to the difference by contrasting “look
before you leap” (LBYL) versus “easier to ask forgiveness than
permission” (EAFP), and tends to prefer the latter.

<URL:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl>

“It is easier to ask forgiveness than permission” is attributed to
computer programming legend Rear Admiral Grace Hopper (she who
documented the first actual computer bug — a large moth in the wires).

Alex Martelli explores when LBYL and EAFP are each appropriate in Python
<URL:http://pyvideo.org/video/1338/permission-or-forgiveness-0>.

-- 
 \   “The optimist thinks this is the best of all possible worlds. |
  `\   The pessimist fears it is true.” —J. Robert Oppenheimer |
_o__)          |
Ben Finney

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


Re: Why is break allowed in finally, but continue is not?

2015-12-13 Thread Ben Finney
Ned Batchelder <n...@nedbatchelder.com> writes:

> For testing coverage.py, I wrote a program to generate
> randomly-structured Python functions.  When compiling
> the results, I got a message I'd never seen before:
>
> SyntaxError: 'continue' not supported inside 'finally' clause
>
> I guess this makes sense, when cleaning up from an
> exception, continuing the loop seems an odd thing to do.
> But 'break' is allowed in 'finally' clauses!  I tried this:
>
> # Huh? This prints "here", and no exception is raised.
>
> for i in range(1):
> try:
> 1/0
> finally:
> # If you change this to "continue", you get:
> # 'continue' not supported inside 'finally' clause
> break
> print "here"
>
> The finally is perfectly willing to have a 'break', but it's
> a syntax error to have 'continue'?  Why? I don't see a
> difference between the two when it comes to cleaning up
> exceptions.

Raymond Hettinger's answer is:

The use of continue in a finally-clause is forbidden because its
interpretation would have been problematic. […]


<URL:https://stackoverflow.com/questions/8302293/why-is-continue-not-allowed-in-a-finally-clause-in-python#answer-8302601>

The example he uses::

for i in range(10):
print i
try:
   raise RuntimeError
finally:
   continue# if the loop continues, what would happen to the 
exception?
print i

What, in your opinion, should the above code do if instead of ‘continue’
some other flow-control statement is used?

> There are other things you can do in a finally clause that
> will prevent the exception from being raised, like 'return',
> and 'break' works just fine.

Hettinger doesn't defend those, and is dubious about ‘return’'s
candidacy:

Interestingly, you can put a return inside a finally-clause and it
will swallow all exceptions including KeyboardInterrupt, SystemExit,
and MemoryError. That probably isn't a good idea either ;-)

> So why treat 'continue' specially?

I am inclined to agree, but in the opposite direction: a case should be
made for allowing *any* flow-control statement in an exception-handler's
‘finally’ clause.

-- 
 \ “We can't depend for the long run on distinguishing one |
  `\ bitstream from another in order to figure out which rules |
_o__)   apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 |
Ben Finney

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


Re: Why doesn't response pydoc on my Python 2.7?

2015-12-12 Thread Ben Finney
Robert <rxjw...@gmail.com> writes:

> I want to use pydoc as some online tutorial shows

Which online tutorial? Please give the URL to the page that instructs
you to use ‘pydoc’ in that manner.

> >>> import pydoc

Allows you to use, in Python code, the ‘pydoc’ module by name.

> >>> pydoc
> 

Accesses the ‘pydoc’ name. Because this is the interactive Python shell,
it displays the result of that access: a module object.

> >>> pydoc sys
> SyntaxError: invalid syntax
> >>> import sys
> >>> pydoc sys
> SyntaxError: invalid syntax

Yes, using two names in a row like that is invalid Python syntax.

> >>> help(pydoc)
> Help on module pydoc:
> ..

Gives help from the module object you access through the name ‘pydoc’.


I suspect the tutorial instructs you to invoke the ‘pydoc’ *command* on
your operating system, not use it within Python.

But I can only guess, until you show us which page from which tutorial
you're referring to.

-- 
 \“Technology is neither good nor bad; nor is it neutral.” |
  `\   —Melvin Kranzberg's First Law of Technology |
_o__)  |
Ben Finney

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


Re: python unit test frame work

2015-12-10 Thread Ben Finney
Ganesh Pal <ganesh1...@gmail.com> writes:

> I have multiple checks if I don't meet them continuing with the main
> program doesn't make sense

That means these are not unit tests (which are isolatable, independent
test cases).

If the tests are best characterised as a sequence of steps, then the
‘unittest’ model (designed for actual unit tests) will not fit well.

You should instead just write a ‘main’ function that calls each test
case in turn and exits when one of them fails.

import sys

from .. import foo_app


def test_input_wibble_returns_lorem(frob):
""" Should process 'wibble' input and result in state 'lorem'. """
frob.process("wibble")
if frob.state != "lorem":
raise AssertionError


def test_input_warble_returns_ipsum():
""" Should process warble' input and result in state 'ipsum'. """
frob.process("warble")
if frob.state != "ipsum":
raise AssertionError


# …

EXIT_STATUS_ERROR = 1

def main(argv):
""" Mainline code for this module. """

process_args(argv)

test_cases = [
test_input_wibble_returns_lorem,
test_input_warble_returns_ipsum,
# …
]

test_frob = foo_app.Frob()

for test_case in test_cases:
try:
test_case(test_frob)
except AssertionError as exc:
sys.stderr.write("Test run failed ({exc})".format(exc=exc))
sys.exit(EXIT_STATUS_ERROR)


if __name__ == "__main__":
exit_status = main(sys.argv)
sys.exit(exit_status)

-- 
 \“The greatest tragedy in mankind's entire history may be the |
  `\   hijacking of morality by religion.” —Arthur C. Clarke, 1991 |
_o__)  |
Ben Finney

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


Re: python unit test frame work

2015-12-10 Thread Ben Finney
Cameron Simpson <c...@zip.com.au> writes:

> First, as Ben remarks, if one test _depends_ on an earlier one then it
> isn't a real unit test.
>
> On the other hand, if you simply have some simple tests followed by
> more complex tests (I have several like this) you have two facilities
> to help you.
>
> Firstly, I have observed that unittest tends to run tests in lexical
> order

Back on the first hand again, some unit test runners will deliberately
*change* the order so your test cases are tested for independence.

Really, if your test cases depend on being executed in a particular
sequence, the ‘unittest’ module is a poor fit.

-- 
 \   “Come on, if your religion is so vulnerable that a little bit |
  `\   of disrespect is going to bring it down, it's not worth |
_o__)   believing in, frankly.” —Terry Gilliam, 2005-01-18 |
Ben Finney

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ben Finney
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> writes:

> You misunderstand the koan.
>
> "There should be one way to do it" does not prohibit more than one
> way.

Further, that's omitting a very important modifier from the koan.

Even without the parenthetical, the koan reads:

There should be one obvious way to do it.

So yes, there can certainly be multiple ways to do it. But it's very
important that there be one *obvious* way.

In other words: Don't present the user with a multitude of options with
no *obvious* choice for those who don't care (yet) to learn about the
choice. Make one of them *obvious* so that's the usually-correct choice.

> (Although having multiple redundant ways is discouraged.) The koan
> exists to encourage the existence of *at least* one (but preferably
> only one) way to do it.

And the Pythonic approach is to make an *obvious* way to do it. As you
say, ‘print’ is that one obvious way for emitting simple text output.

-- 
 \ “What's another word for Thesaurus?” —Steven Wright |
  `\   |
_o__)          |
Ben Finney

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


Re: variable vs. object

2015-11-29 Thread Ben Finney
André Roberge <andre.robe...@gmail.com> writes:

> In Python, a "variable" is a name given to an object. In Python, the
> "=" sign is used to assign a name to an object: the name is on the
> left-hand side, and the object is on the right hand side. Multiple
> names can be assigned to the same object.

Take care with the directionality of those statements.

In Python we don't give the name *to* the object, which would imply that
the object “has” that name in some sense. The object is totally
unaffected, and assignment does not give the object any knowledge about
that name.

We also don't assign names *to* objects; if anything, we assign the
object to the name.

It is the name that “has” the object. Or perhaps less confusingly, the
name is *bound to* the object.

It is frequently a point of confusion that assignment *never* affects
the object, so it's best to avoid giving that false impression.

> In the example you gave, "a" is a name given to the object "10" which
> is an integer.

Rather, I'd prefer to say that ‘a’ now refers to the object ‘10’. The
object ‘10’ was not “given” anything.

-- 
 \   “When I get new information, I change my position. What, sir, |
  `\ do you do with new information?” —John Maynard Keynes |
_o__)      |
Ben Finney

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


Faviourite improvements in Python 3.5 (was: Python 3 virtualenvs)

2015-11-27 Thread Ben Finney
Laura Creighton <l...@openend.se> writes:

> […] python3.5 which I infinitely prefer over 3.4. 

That's strong language :-)

Laura – and anyone else – what in your opinion are the best improvements
brought by Python 3.5 (over Python 3.4)?

-- 
 \ “DRM doesn't inconvenience [lawbreakers] — indeed, over time it |
  `\ trains law-abiding users to become [lawbreakers] out of sheer |
_o__)frustration.” —Charles Stross, 2010-05-09 |
Ben Finney

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


Re: Help with this program???

2015-11-27 Thread Ben Finney
justin bloomer via Python-list <python-list@python.org> writes:

> Your program should contain a function that:

This is a homework assignment, yes?

We're not going to write the code for you. If you have a program you
already wrote, we can offer feedback on *your* code.

You should also collaborate with other classmates in the course, or look
into the course material your teacher has provided.

-- 
 \ “Why doesn't Python warn that it's not 100% perfect? Are people |
  `\ just supposed to “know” this, magically?” —Mitya Sirenef, |
_o__) comp.lang.python, 2012-12-27 |
Ben Finney

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


Re: Object identity has no necessary connection to memory location

2015-11-26 Thread Ben Finney
Dave Farrance <df@see.replyto.invalid> writes:

> >> >Dave Farrance <df@see.replyto.invalid>:
> >> >
> >> >> (Conversely, I see that unlike CPython, all PyPy's numbers have
> >> >> unchanging ids, even after exiting PyPy and restarting, so it seems
> >> >> that PyPy's numerical ids are "faked".)
>
> Hence
>
> https://en.wikipedia.org/wiki/Scare_quotes

I saw the scare quotes. They still communicate your position that object
identity “should” be reliably connected to the object's memory location.

Either you don't hold that position, in which case your original
statement was as ambiguous as this most recent one you wrote; or you do
hold that position, and my response stands.

-- 
 \   “When I was little, my grandfather used to make me stand in a |
  `\   closet for five minutes without moving. He said it was elevator |
_o__)practice.” —Steven Wright |
Ben Finney

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


Re: What is a function parameter =[] for?

2015-11-26 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> On Thu, 26 Nov 2015 09:34 pm, Dave Farrance wrote:
>
>
> > (Conversely, I see that unlike CPython, all PyPy's numbers have
> > unchanging ids, even after exiting PyPy and restarting, so it seems
> > that PyPy's numerical ids are "faked".)
>
> I'm pretty sure that they are faked.

It's still not been expressed what “fake” refers to here. Or, rather,
what “real” thing was being expected, and how these don't qualify.

The object IDs are real IDs, they identify the object, they're not
pretending to be anything other than object IDs, they are perfectly
compliant with the language definition and all the documentation.

What is fake? What “real” thing was expected, and *why* was that
expected?

-- 
 \ “Do unto others twenty-five percent better than you expect them |
  `\  to do unto you. (The twenty-five percent is [to correct] for |
_o__)        error.)” —Linus Pauling's Golden Rule |
Ben Finney

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


Re: What is a function parameter =[] for?

2015-11-26 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> On Fri, 27 Nov 2015 12:40 pm, Ben Finney wrote:
>
> > It's still not been expressed what “fake” refers to here. Or, rather,
> > what “real” thing was being expected, and how these don't qualify.
>
> They are faked in the sense that in this implementation, the object
> lifespan that you think of as the Python programmer has little if any
> connection to the actual lifespan of the chunk of memory representing
> that object.

Since that's nothing to do with the definition nor API of an object ID,
I think all the uses of “faked” so far in this thread just don't apply
to PyPy's object IDs.

> The PyPy implementation has to take special actions to preserve the ID
> across object recreations. That is what I mean by "faked".

Thanks for the interesting explanation. I don't think any of this makes
PyPy's object IDs in any sense not-real-object-IDs, so I disagree with
using “faked” to characterise them.

None of CPython, Jython, PyPy, etc. have object IDs that are anything
but real object IDs, IMO.

-- 
 \  “[Entrenched media corporations will] maintain the status quo, |
  `\   or die trying. Either is better than actually WORKING for a |
_o__)      living.” —ringsnake.livejournal.com, 2007-11-12 |
Ben Finney

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


Object identity has no necessary connection to memory location (was: What is a function parameter =[] for?)

2015-11-26 Thread Ben Finney
Dave Farrance <df@see.replyto.invalid> writes:

> Marko Rauhamaa <ma...@pacujo.net> wrote:
>
> >Dave Farrance <df@see.replyto.invalid>:
> >
> >> (Conversely, I see that unlike CPython, all PyPy's numbers have
> >> unchanging ids, even after exiting PyPy and restarting, so it seems
> >> that PyPy's numerical ids are "faked".)
> >
> >What's a faked id?
>
> You can figure out what I'm getting at -- i.e. I presume that the ids
> are not pointers to stored numbers in memory (as with CPython) but are
> a translation of the numerical variable's value.

Why refer to that as “faked”? That's what I can't figure out about what
you're getting at. Perhaps Marko shares my uncomprehension.

The Python language makes no promise about “pointers to stored numbers
in memory” for object identity. That is an implementation detail of
CPython, and is *explicitly* not promised for any other Python
implementation.

If you are surprised that object identity appears to have no connection
with memory location, then you've made unwarranted assumptions that are
explicitly warned against in the Python documentation.

-- 
 \“Absurdity, n. A statement or belief manifestly inconsistent |
  `\with one's own opinion.” —Ambrose Bierce, _The Devil's |
_o__)Dictionary_, 1906 |
Ben Finney

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-25 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> This is a distinction I generally make. Putting it another way: a list
> has the same meaning regardless of how many items are on it (for
> instance, a shopping list is still a shopping list whether it has five
> or fifty items on it), where a tuple is a package where each element
> has a specific meaning […]

Yes. The disctinction is even clearer, I find, by saying that the
*meaning of the position* in the sequence is significant for a tuple,
not significant for a list.

That is, the ‘2’ in ‘cartesian_point = (2, 3)’ means something different
than in ‘cartesian_point = (3, 2)’.

Whereas the ‘2’ in ‘test_scores = [2, 3]’ means exactly the same as in
‘test_scores = [3, 2]’.

If each position in the sequence gives the value there a different
menaning, use a tuple; if not, use a list.

> Nothing in the language enforces this, but the mutability of lists
> does tend to align well with things that can grow and shrink, and the
> immutability of tuples makes them more like strings or complex numbers
> (in fact, a complex number is basically a tuple of two floats).

Not only the growing and shrinking, but the re-ordering of items in a
list should not change the meaning of its items.

If you can ‘sort’ the sequence and the items still mean exactly what
they did before, then a tuple is the wrong type to use, semantically.

-- 
 \   “Crime is contagious… if the government becomes a lawbreaker, |
  `\  it breeds contempt for the law.” —Justice Louis Brandeis |
_o__)          |
Ben Finney

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-25 Thread Ben Finney
Laura Creighton <l...@openend.se> writes:

> The great sticking point for the children I am teaching is '*' means
> multiplication. […] that one can swap out a particular convention 'x
> means multiply' and swap in another one '* means multiply' while
> leaving the underlying truth unchanged.

Perhaps it would be easier if you point out that ‘x’ doesn't mean
multiply either, and they've *already* been substituting that symbol
instead of the correct ‘×’ for multiply.

-- 
 \ “Our task must be to free ourselves from our prison by widening |
  `\our circle of compassion to embrace all humanity and the whole |
_o__)   of nature in its beauty.” —Albert Einstein |
Ben Finney

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


Semantics of collection types (was: Late-binding of function defaults (was Re: What is a function parameter =[] for?))

2015-11-25 Thread Ben Finney
Ian Kelly <ian.g.ke...@gmail.com> writes:

> On Wed, Nov 25, 2015 at 5:52 PM, Random832 <random...@fastmail.com> wrote:
> > On 2015-11-25, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
> >> That is, the ‘2’ in ‘cartesian_point = (2, 3)’ means something
> >> different than in ‘cartesian_point = (3, 2)’.
> >>
> >> Whereas the ‘2’ in ‘test_scores = [2, 3]’ means exactly the same as
> >> in ‘test_scores = [3, 2]’.
> >>
> >> If each position in the sequence gives the value there a different
> >> menaning, use a tuple; if not, use a list.
> >
> > I don't think that's really right.

I was expanding on (by replying to) earlier advice about expressing
semantics in our choice of data types.

> > The difference between a tuple and a list is that one is mutable
> > and the other is not.

That is a difference enforced in the behaviour of the types, yes.

I didn't talk about behaviour, but about meaning. I'm saying that the
behavioural difference conveniently lines up with a semantic difference,
even to the point of the meaning of “tuple” that pre-dates Python.

> I think that Ben was actually trying to make a distinction between
> heterogeneity and homogeneity of the contents, not a distinction of
> whether the collection was ordered or not.

That's right, thank you.

-- 
 \   “Nothing exists except atoms and empty space; everything else |
  `\        is opinion.” —Democritus, c. 460 BCE – 370 BCE |
_o__)  |
Ben Finney

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-25 Thread Ben Finney
Ned Batchelder <n...@nedbatchelder.com> writes:

> For someone who claims to be interested in language design, you're
> remarkably dismissive of pretty much the entire industry. I don't
> think it's worth the effort to try to change your mind.

+1.

BartC, when you want to join us in discussions on good faith – that is,
honestly wanting to learn Python rather than dogmatically persisting in
your misperceptions dogmatically onto it – we'll still be here, making
happy use of Python the way it is.

-- 
 \   “Facts are meaningless. You could use facts to prove anything |
  `\that's even remotely true!” —Homer, _The Simpsons_ |
_o__)          |
Ben Finney

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


A name refers to an object, an object has a value, equality compares values (was: What is a function parameter =[] for?)

2015-11-24 Thread Ben Finney
Laura Creighton <l...@openend.se> writes:

> If I had a time machine, I would go back to early days of Python and
> ban the use of the term 'assignment' and 'value' both. I would insist
> that the term 'binding' be used instead, though if you want to use the
> verb refer, to be synonymous with bind, well, I think that would work.

+1

> (If not, next trip with the time machine, I ban that one as well.)

I've never been able to remember where the keys are kept; I'm sure they
keep being moved by previous drivers.

> It is crystal clear than people on this list mean very different
> things when they use the term 'value', and every one of them thinks
> that Python agrees with them. Cutting this knot may require a new
> word.

Indeed, in the past I used the term “value” as synonymous (in Python
context) with the term “object”. I have become convinced through this
discussion that I should no longer use the terms that way.

Instead, an object *has* a value at a point in time; if the object's
value can change, we say the object is mutable.

The syntax for literals describe a value, but the object once created
may change its value.

Typically, ‘is’ compares object identity; ‘==’ compares object value.

The concepts are distinct, so I apologise for misleadingly conflating
them in my terminology.

-- 
 \ “Skepticism is the highest duty and blind faith the one |
  `\   unpardonable sin.” —Thomas Henry Huxley, _Essays on |
_o__)   Controversial Questions_, 1889 |
Ben Finney

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


Re: Reading files from .ar / .deb archives

2015-11-24 Thread Ben Finney
Кисик Мурысик <kisik2...@live.ru> writes:

> Hello!
> I'm new to Python, so I decided to learn it

Congratulations! Python is a fine language to learn, and this is the
place to discuss general Python topics.

You may also want to join the ‘tutor’ forum
<URL:https://mail.python.org/mailman/listinfo/tutor>, which is
specifically focussed on collaborative mentoring of Python newcomers.

> and write simple apt alternative (apt is somewhat broken for me).
> But I can't decide - can I read just one file (/DEBIAN/control) from
> archive without unpacking it, or do I need to unpack? And what module
> I can use to handle .ar files? (I read in Wikipedia that .deb is just
> .ar archive with specific structure)

You're right. The ‘ar’ archive format was IIUC chosen by the early
Debian project because it is very simple.

Unfortunately it is not widely supported; there is no standard library
support in Python for ‘ar’ archives.

You can use the third-party ‘python-debian’ library for reading Debian
archive files <URL:https://pypi.python.org/pypi/python-debian/>.

-- 
 \ “I know when I'm going to die, because my birth certificate has |
  `\   an expiration date.” —Steven Wright |
_o__)          |
Ben Finney

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


Re: tuples in conditional assignment

2015-11-23 Thread Ben Finney
George Trojan <george.tro...@noaa.gov> writes:

> The following code has bitten me recently:
>
> >>> t=(0,1)
> >>> x,y=t if t else 8, 9
> >>> print(x, y)
> (0, 1) 9

You can simplify this by taking assignment out of the picture::

>>> t = (0, 1)
>>> t if t else 8, 9
((0, 1), 9)

So that's an “expression list” containing a comma. The reference for
expressions tells us::

An expression list containing at least one comma yields a tuple. The
length of the tuple is the number of expressions in the list.

<URL:https://docs.python.org/3/reference/expressions.html#expression-lists>

> I was assuming that a comma has the highest order of evaluation

You were? The operator precedence rules don't even mention comma as an
operator, so why would you assume that?


<URL:https://docs.python.org/3/reference/expressions.html#operator-precedence>

> that is the expression 8, 9 should make a tuple. Why this is not the
> case?

I'm not sure why it's the case that you assumed that :-)

My practical advice: I don't bother trying to remember the complete
operator precedence rules. My simplified precedence rules are:

* ‘+’, ‘-’ have the same precedence.
* ‘*’, ‘/’, ‘//’ have the same precedence.
* For anything else: Use parentheses to explicitly declare the
  precedence I want.

Related: When an expression has enough clauses that it's not *completely
obvious* what's going on, break it up by assigning some sub-parts to
temporary well-chosen descriptive names (not ‘t’).

-- 
 \ “It is far better to grasp the universe as it really is than to |
  `\persist in delusion, however satisfying and reassuring.” —Carl |
_o__)Sagan |
Ben Finney

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


Re: Mapping between python packages and distro packages?

2015-11-20 Thread Ben Finney
Stephane Wirtel <steph...@wirtel.be> writes:

> in fact, I would like to have a database where I want the requests
> library, I will get the python-requests for debian/ubuntu and the
> right package for the yum installer.

Okay. That's a pretty simple technical problem (a simple relation
between PyPI distribution name, GNU+Linux operating system name, and
package name).

Of course, *populating* that database, *verifying* the ambiguous inputs,
and *maintaining* that database into the future, are all social
problems. You'll probably need an organised group of people to address
it.

I'm not aware of any sufficiently motivated group of people to put in
the ongoing effort to provide what you want.

(Another social problem is convincing people not to top-post, but
instead to reply interleaved and trim irrelevant quoted material
<URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style>.)

-- 
 \   “Anyone who puts a small gloss on [a] fundamental technology, |
  `\  calls it proprietary, and then tries to keep others from |
_o__)   building on it, is a thief.” —Tim O'Reilly, 2000-01-25 |
Ben Finney

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


Re: What is a function parameter =[] for?

2015-11-18 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> On Thu, Nov 19, 2015 at 12:41 PM, BartC <b...@freeuk.com> wrote:
> > On 18/11/2015 23:22, Chris Angelico wrote:
> >> On the contrary, it is certain always to be that exact object.
> >
> > But, not the same value that appears as the default?

It depends what you mean by “the same value”.

> Nope. Mutable objects are never guaranteed to retain the same values.
> That's kinda the point.

Well, they are the *same value*, if by “value” you mean “a particular
object”.

On the other hand, the value can *change* over time, while remaining the
same object. So it will not be equal to its initial state, even though
it is the same object.

-- 
 \ “[F]reedom of speech does not entail freedom to have your ideas |
  `\accepted by governments and incorporated into law and policy.” |
_o__)       —Russell Blackford, 2010-03-06 |
Ben Finney

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


Re: What is a function parameter =[] for?

2015-11-18 Thread Ben Finney
MRAB <pyt...@mrabarnett.plus.com> writes:

> On 2015-11-19 00:34, fl wrote:
> > What does 'del' do? It does not look like a thorough list deletion
> > from the effect.
>
> No, "del list1" doesn't delete the list, it deletes the name "list1".
> The list still exists as the default parameter.

More generally, ‘del’ deletes a *reference*. Names are one kind of
reference; others include items in a collection such as a dict or set.

Deleting a reference *never* affects the value referred to.

However, once a value has no more references, the program can no longer
access it, so the Python machine is at liberty to delete the value
behind the scenes at some future point.

> A default parameter is evaluated when the function is defined, and
> that value exists as the default as long as the function exists.

So, because the function retains a reference to the value, the value
remains unaffected when you delete the reference ‘list1’.

-- 
 \ “True greatness is measured by how much freedom you give to |
  `\  others, not by how much you can coerce others to do what you |
_o__)       want.” —Larry Wall |
Ben Finney

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


Re: Mapping between python packages and distro packages?

2015-11-17 Thread Ben Finney
Stephane Wirtel <steph...@wirtel.be> writes:

> Do you know if there is a library to match a python package (from PyPI)
> and find the right debian/redhat packages ?

What would count as “the right package”?

Do you mean “the package that has that PyPI distribution URL in its
‘debian/watch’ configuration”?

Do you mean “the package that names that PyPI distribution in its
‘debian/copyright’ “Source” field”?

Or something else?

The answers will differ depending on exactly what question is being
asked of the data.

If you can define exactly what query you want to perform, perhaps a
solution can be offered.

-- 
 \ “The Vatican is not a state.… a state must have territory. This |
  `\ is a palace with gardens, about as big as an average golf |
_o__) course.” —Geoffrey Robertson, 2010-09-18 |
Ben Finney

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


Re: What meaning is 'a[0:10:2]'?

2015-11-15 Thread Ben Finney
(Please set a “From” address that has a name for you as an individual;
“fl” is rather anonymous and doesn't help us to identify you in these
conversations.)

fl <rxjw...@gmail.com> writes:

> When I learn slice

Are you working through the Python tutorial
<URL:https://docs.python.org/3/tutorial/>? These are Python concepts
that you will learn by working through the tutorial, from beginning to
end.

If you want to engage with a community dedicated to teaching Python
newcomers, you should join the Python ‘tutor’ forum
<URL:https://mail.python.org/mailman/listinfo/tutor>.

-- 
 \   “Philosophy is questions that may never be answered. Religion |
  `\  is answers that may never be questioned.” —anonymous |
_o__)          |
Ben Finney

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


Learning Python from the tutorial (was: What function is 'u0, j = random(), 0'?)

2015-11-14 Thread Ben Finney
Zachary Ware <zachary.ware+pyl...@gmail.com> writes:

> I've noticed you sending a lot of questions in the past day or two,
> many at a fairly basic level.  I think you would be well-served to
> read through the tutorial at https://docs.python.org/3/tutorial.

Better than merely reading through it: Anyone who wants to learn Python
from the official tutorial should *work through* the tutorial. Run each
example, read the tutorial to get an explanation, experiment to test
whether you understand. Only then, continue on.

-- 
 \   “I bought some powdered water, but I don't know what to add.” |
  `\—Steven Wright |
_o__)          |
Ben Finney

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


Re: new to python, help please !!

2015-11-11 Thread Ben Finney
Anas Belemlih <anas.belem...@gmail.com> writes:

> i am  a beginning programmer,  i am trying to write a simple code to
> compare two character sets in 2 seperate files. ( 2 hash value files
> basically)

Welcome, and congratulations on arriving at Python for your programming!

As a beginning programmer, you will benefit from joining the ‘tutor’
forum <URL:https://mail.python.org/mailman/listinfo/tutor>, which is
much better suited to collaborative teaching of newcomers.

-- 
 \ “As scarce as truth is, the supply has always been in excess of |
  `\   the demand.” —Josh Billings |
_o__)          |
Ben Finney

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


Re: Keeping context-manager object alive through function calls

2015-11-10 Thread Ben Finney
Pablo Lucena <plucen...@gmail.com> writes:

> In order to keep the SSH session open and not have to re-establish it
> across function calls, I would like to do add an argument to
> "do_stuff" which can optionally return the SSH session along with the
> data returned from the SSH session, as follows:
>
> def do_stuff(device, return_handle=False):
> with manager(device) as conn:
> output = conn.send_command("show ip route")
> #process output...
> if return_handle:
> return (processed_output, conn)
> else:
> return processed_output

Since you're making it the caller's responsibility to deal with the
context manager, why not require the caller to *provide* the context
manager in the first place::

def do_stuff(conn):
""" Do stuff via the device connection `conn`.

:param conn: The context manager for the device connection.
:return: The processed output.

"""
with conn:
output = conn.send_command("show ip route")
#process output...
return processed_output

Also, note that if you just unconditionally want to return the output,
do it *outside* the ‘with’ block.

Then your caller is the one responsible for creating the connection
manager, and has the option of interrogating it further if it needs to::

bsu5000_conn = make_connection("bsu5000")
gen = do_stuff(bsu5000_conn)
do_more_things_with(bsu5000_conn)

-- 
 \   “I don't know anything about music. In my line you don't have |
  `\     to.” —Elvis Aaron Presley (1935–1977) |
_o__)  |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-10 Thread Ben Finney
Laura Creighton <l...@openend.se> writes:

> In a message of Tue, 10 Nov 2015 17:10:09 +1100, Ben Finney writes:
> >I am a Bear of Little Brain, but: Isn't anything that the *compiler*
> >does, by definition done at *compile* time?
>
> No.
>
> We used to have a pretty strict defintion about what a compiler was,
> and what an interpreter was. You did the compile things at compile
> time, and then you the the interpreter things at runtime.
>
> No more. We have Just in Time compilers. They do their compiling at
> run time. Or perhaps 'there is no such thing as compile time any
> more'.

Very well. I argued on the basis of what could be determined at the time
Steven refers to as “compile time”, i.e. before any part of the module
begins to run.


Steven D'Aprano <st...@pearwood.info> writes:

> Python -- yes, even CPython -- has a runtime compiler. When you import
> a module, it is compiled (if needed) just before the import. Likewise,
> when you call the `compile`, `eval` or `exec` built-ins, the compiler
> operates.
>
> I'm not calling this a JIT compiler, because the simple-minded
> compilation performed by `compile` etc doesn't use any run-time
> information. It just statically compiles the code to byte-code.

That's what I though. I'm aware of JIT compilers, and was pretty sure
Python doesn't have them. What's more, if it operates at a whole-module
level, and not later than when the module is imported.

Under those conditions, I maintain my objection to the proposed
optimisation.

The proposal is explicitly for optimisations made by the Python
compiler. As proposed, it only seems to be worthwhile once Python no
longer has a distinct “compiler” and “interpreter” is dissolved. Until
then, it seems pointless.

-- 
 \ “There is something wonderful in seeing a wrong-headed majority |
  `\   assailed by truth.” —John Kenneth Galbraith, 1989-07-28 |
_o__)  |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-09 Thread Ben Finney
BartC <b...@freeuk.com> writes:

> On 09/11/2015 01:04, Ben Finney wrote:
> > There isn't a way for the compiler to *know*, in all cases, whether
> > module attributes will be updated during the lifetime of the program
>
> In what way can an attribute be updated, other than deleting it
> altogether?

* Bind a new name to a value.
* Re-bind an existing name to a different value.
* Delete an existing name.

Any of those can be done at run-time, in any module's namespace, by
arbitrary code somewhere in the program.

-- 
 \“Sane people have an appropriate perspective on the relative |
  `\ importance of foodstuffs and human beings. Crazy people can't |
_o__) tell the difference.” —Paul Z. Myers, 2010-04-18 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-09 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> The compiler doesn't need to decide in advance whether or not the
> module attributes have been changed. It can decide that at runtime,
> just before actually looking up the attribute. In pseudo-code:
>
> if attribute might have changed:
> use the slow path just like today
> else:
> use the optimized fast path

As you have pointed out earlier, the “attribute might have changed”
condition is set by *any* non-trivial code — notably, a function
call, though that doesn't exhaust the ways of setting that condition.

So the remaining space of code that is safe for the proposed
optimisation is trivially small. Why bother with such optimisations, if
the only code that can benefit is *already* small and simple?

I'm not asking you (Steven) to defend the proposal, I'm pointing out
that the “problem” being addressed is essentially the dynamism of
Python. The proposal is misguided.

-- 
 \ “Truth would quickly cease to become stranger than fiction, |
  `\ once we got as used to it.” —Henry L. Mencken |
_o__)          |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-09 Thread Ben Finney
Steven D'Aprano <st...@pearwood.info> writes:

> Ben, I fear that you are not paying attention to me :-)

Possibly, though I also think there's miscommunication in this thread.

You speak of “compile time” and “run time”. You also speak of what the
compiler can do, at run time.

I am a Bear of Little Brain, but: Isn't anything that the *compiler*
does, by definition done at *compile* time?

The run-time behaviour of the program is, of course, *affected* by what
the compiler has done in the past. But the compiler acts only at compile
time, and its compile-time behaviour can't be determined by what's
happening at run time.

If that's not true, I fear we're not talking about the same things.

> At compile time, `func(x)` might do anything. But at runtime, we know
> exactly what it did, because it just did it.

Sure. All my statements about compile-time optimisations are those that
can be applied at compile time (which I intend to be synonymous with
“when the compiler is doing its job”), and so can't be informed by what
happens at run time.

If the proposal is to make optimisations that must be informed by the
run-time state of the running program, we're surely talking about not
just the compiler any more. No?

-- 
 \  “Any sufficiently advanced bug is indistinguishable from a |
  `\  feature.” —Rich Kulawiec |
_o__)          |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-09 Thread Ben Finney
Laura Creighton <l...@openend.se> writes:

> In a message of Tue, 10 Nov 2015 06:45:40 +1100, Ben Finney writes:
> >So the remaining space of code that is safe for the proposed
> >optimisation is trivially small. Why bother with such optimisations, if
> >the only code that can benefit is *already* small and simple?
>
> You have things backwards.
> The reason that you want to optimise this is that it is small, simple, 
> and slow_slow_slow_slow_slow.
>
> It is the things that are complicated and large that usually aren't
> worth optimising. You don't call them often enough for it to be worth
> it to optimise them.

I appreciate you making the the distinction explicit between a small and
simple *code unit* (e.g. an small, simple, often-called function),
versus a large and complex *code unit* (e.g. a large, complex,
infrequently-called class definition).

I'm pointing out an orthogonal issue: The only code to which the
proposed optimisation could apply is *module-level* (infrequently
called) code, which *has no complications* (i.e. not a code unit).

The simplicitly of the small section of code is not the issue; the
dynamism of the entire program is what negates the applicability of the
optimisation.

If the simple, predictable-by-the-compiler segment of code were actually
isolated in a simple unit, then yes, such optimisations might be
considered. But, as already discussed, the optimisation is not intended
to apply to such code units. So that is moot in this case.

Instead, we're talking about optimisations proposed *only* for
module-level code (i.e. not isolated); and what negates their
applicability is *any* dynamism (i.e. not simple), anywhere in the
program (i.e. not a code unit). The space of applicability for the
proposed optimisation shrinks to irrelevance, AFAICT.

-- 
 \“If the arguments in favor of atheism upset you, explain why |
  `\they’re wrong. If you can’t do that, that’s your problem.” |
_o__)         —Amanda Marcotte, 2015-02-13 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-09 Thread Ben Finney
Antoon Pardon <antoon.par...@rece.vub.ac.be> writes:

> Op 07-11-15 om 04:43 schreef Ben Finney:
> > Python assumes the programmers using it are consenting adults. Doing
> > harmful things is difficult but not forbidden.
>
> I find that to be contradictory. Why should you make something difficult
> if you are consenting adults?

It's no more contradictory than the fact Python makes it difficult for
consenting adults to exchange hard-to-follow code indentation. The
principle that There Should Be (Preferably Only) One Obvious Way To Do
It directly implies that other ways should be difficult. That's not a
contradiction with treating Python programmers as consenting adults.

> This whole idea of python assuming we are consenting adults and thus
> making it impossible to not consent seems weird.

You misunderstand the implication: I'm saying that because Python
assumes we are consenting adults, that such actions remain possible.

> > Notably, the author of a library should not be forbidding the Pythonic
> > ability to change name bindings as needed.
>
> If the author of a library doesn't wish to consent to this I don't see
> what is wrong with that.

Who is doing what to whom? The user of the library isn't doing anything
to the library author, so what is it the library author would consent
to? Instead, you seem to be trying to assert a *power* of the library
author to restrict the library user. Such a power is not granted by
Python.

Instead, the library author is obliged to treat the library user as an
adult who consents to the freedoms inherent to Python's design, and to
not restrict their use of the library needlessly.

-- 
 \ “Facts are stubborn things; and whatever may be our wishes, our |
  `\   inclinations, or the dictates of our passion, they cannot alter |
_o__)the state of facts and evidence.” —John Adams, 1770-12-04 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-08 Thread Ben Finney
BartC <b...@freeuk.com> writes:

> I've never understood why this seems to be necessary in Python. Why do
> names have to be looked up? (I'm assuming this is searching by name in
> some sort of table.)

No, it is literally looking the name up as a key in a namespace
dictionary — which is just like any other Python dictionary, but
nominated internally for use as the namespace dictionary.

The distinction is important, because like any other dictionary it can
change at run-time and the bindings between name and value can change,
can be added, and can be removed.

> When a module is compiled, while the compiler can't see the
> definitions inside the imported modules, it /will/ know all the names
> that appear in this module, so it can organise them into fixed tables.

Not true. The namespace can change dynamically, which is another way of
what people have been trying to tell you all through this thread.

The compiler *cannot* know what the names will be at every single point
they'll be looked un in the namespace dictionary. This dynamism of each
namespace is a Python feature.

-- 
 \  “It is … incumbent upon us to recognize that it is |
  `\inappropriate for religion to play any role in issues of state |
_o__)[of] a modern democracy.” —Lawrence M. Krauss, 2012-05-28 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-08 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> Hmm, then I was misunderstanding what BartC was advocating. I didn't
> think it would *fail* in the presence of dynamic attributes, but
> merely *perform suboptimally* (and presumably worse than current
> CPython).

There isn't a way for the compiler to *know*, in all cases, whether
module attributes will be updated during the lifetime of the program
(short of, as pointed out elsewhere, running the entire program under
all possible conditions).

So the optimisation can't be applied by the compiler without risking
breaking perfectly valid code.

That is enough, IMO, to kill the proposal; if the compiler could break
*any* valid code, it's no longer a Python compiler.

-- 
 \   “If [a technology company] has confidence in their future |
  `\  ability to innovate, the importance they place on protecting |
_o__) their past innovations really should decline.” —Gary Barnett |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-08 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> Testing/mocking is a completely separate consideration (eg you can
> inject a shadow for a built-in name)

Not for the purpose of making compiler optimisations, as BartC is
advocating.

The compiler definitely should not treat “is this code part of a test
suite?” as a relevant criterion for deciding what optimisation. We
should certainly not have a compiler that makes needless difference to
code behaviour under test conditions versus non-test conditions.

So, since those optimisations would cripple perfectly normal test code,
that should be sufficient to quash the desire to make them.

-- 
 \   “If you define cowardice as running away at the first sign of |
  `\   danger, screaming and tripping and begging for mercy, then yes, |
_o__)   Mr. Brave man, I guess I'm a coward.” —Jack Handey |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-08 Thread Ben Finney
BartC <b...@freeuk.com> writes:

> Is this typical Python code? Creating global objects in other modules
> (or writing all over essential data structures in a library module).

Not “creating global objects”, but changing the referent of a name in
some other module. Yes, that's quite a common technique. Does that
surprise you?

If it surprises you, hopefully you can learn some more Python with this
new knowledge.

-- 
 \ “We can't depend for the long run on distinguishing one |
  `\ bitstream from another in order to figure out which rules |
_o__)   apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-08 Thread Ben Finney
Chris Angelico <ros...@gmail.com> writes:

> On Mon, Nov 9, 2015 at 11:26 AM, Ben Finney <ben+pyt...@benfinney.id.au> 
> wrote:
> > Chris Angelico <ros...@gmail.com> writes:
> >
> >> Testing/mocking is a completely separate consideration (eg you can
> >> inject a shadow for a built-in name)
> >
> > Not for the purpose of making compiler optimisations, as BartC is
> > advocating. […] since those optimisations would cripple perfectly
> > normal test code, that should be sufficient to quash the desire to
> > make them.
>
> But I distinguish between crippling *performance* and crippling
> *functionality*. If the compiler optimizations are defeated, so the
> test suite falls back on the slow path, that means your tests run
> slower. Unless you're testing the optimizer itself, this shouldn't be
> a problem.

You misunderstand me. I'm not saying the optimisations would be
crippled. I am saying that, in order to achieve those optimisations, the
*test code* would be crippled.

I am pointing out that the assumption necessary for the optimisation
BartC is advocating – the optimisation of module attributes to be
immutable after compilation – depends on crippling the *functionality*
needed for many uses, including test code uses.

Since the compiler should not be in the position of deciding whether
code is test code or not, it cannot use that criterion to decide whether
to enable or disable the optimisation.

So either the optimisation should never be enabled (my perference), or
test code will unwittingly be crippled by the assumptions needed for
that optimisation.

-- 
 \ “We are all agreed that your theory is crazy. The question that |
  `\  divides us is whether it is crazy enough to have a chance of |
_o__)being correct.” —Niels Bohr (to Wolfgang Pauli), 1958 |
Ben Finney

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


<    2   3   4   5   6   7   8   9   10   11   >