Re: Question about math.pi is mutable

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

> On 08/11/2015 21:00, Ben Finney wrote:
> > 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.
>
> Suppose this is the python program:
>
> import m
> a=10
> b=20
> c=30
> m.f()
>
> The set of global names the compiler knows will be ("m","a","b","c").
>
> I don't believe code can remove these names (that would cause
> problems).

It may indeed cause problems. Those names can nevertheless be changed.

Names at module level are simply attributes on the module object. The
module can gain attributes, lose attributes, and its attributes can
chage; its namespace is just as mutable as any other object's namespace.

> You say the set of global names can be added to - after this lot, but
> I can't see that the first four are going to change.

You have not yet learned enough about the Python data model:

A module object has a namespace implemented by a dictionary object
(this is the dictionary referenced by the __globals__ attribute of
functions defined in the module). Attribute references are
translated to lookups in this dictionary, e.g., m.x is equivalent
to m.__dict__["x"]. A module object does not contain the code
object used to initialize the module (since it isn’t needed once
the initialization is done).

<URL:https://docs.python.org/3/reference/datamodel.html>

Any name can be deleted, just like any other reference, with the ‘del’
statement.

Any reference (including names) can be added or changed in a module
namespace like any other object's namespace.

> Attributes are harder because they are more of a free-for-all

Please understand that a module *is* an object, and a name in a module's
namespace *is* an attribute on that module.

Also, please *learn about* the way Python works; you have certainly been
here long enough to know how to look up answers in the documentation
instead of making ignorant assertions here.

-- 
 \   “What I resent is that the range of your vision should be the |
  `\     limit of my action.” —Henry James |
_o__)  |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-07 Thread Ben Finney
Bartc <b...@freeuk.com> writes:

> To my mind, Python allows far too much freedom in being able to change
> anything at any time.

You're welcome to that opinion. I don't see you present a reason why it
should affect anyone else's opinion of Python, though.

> Yet Python has to assume 100% of the time that it could have been
> changed. Think of the opportunities for optimising if the probability
> was 0%.

Such a pity that Python is missing all those opportunities for
widespread adoption, by not hewing closer to your preferences.

-- 
 \“That's the essence of science: Ask an impertinent question, |
  `\and you're on the way to the pertinent answer.” —Jacob |
_o__) Bronowski, _The Ascent of Man_, 1973 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-07 Thread Ben Finney
Bartc <b...@freeuk.com> writes:

> On 07/11/2015 03:43, Ben Finney wrote:
> > Bartc <b...@freeuk.com> writes:
> >
> >> Is there no way then in Python to declare:
> >>
> >> pi = 3.141519 # etc
> >>
> >> and make it impossible to override?
> >
> > No, and it would be a bad thing if that were something a library author
> > could forbid.
> >
> > Python assumes the programmers using it are consenting adults. Doing
> > harmful things is difficult but not forbidden.
>
> But surely it can't hurt to ensure certain values can't be changed
> accidentally or maliciously?

The value ‘3.141519’ (in your example above) can't be changed. That
value will always be exactly the same, as long as the program is
running.

What I think you mean is “surely it can't hurt to ensure certain names
can never be bound to any value but their initial binding”.

On that I strongly disagree, for the reasons already discussed in this
thread: it arrogates to the library author the power to forbid patching
the library, which cripples extending, debugging, introspection, and a
host of other useful activities.

-- 
 \ “I object to doing things that computers can do.” —Olin Shivers |
  `\       |
_o__)  |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-07 Thread Ben Finney
Bartc <b...@freeuk.com> writes:

> On 06/11/2015 22:26, Thomas 'PointedEars' Lahn wrote:
> > Bartc wrote:
> > ^
> > Please fix.
>
> What's the problem?

As far as I can tell, you're being asked to change that to your “real”
name, whatever that is supposed to mean.

I recommend you ignore that request; “Bartc” is fine as a name here,
IMO.

-- 
 \“Your [government] representative owes you, not his industry |
  `\   only, but his judgment; and he betrays, instead of serving you, |
_o__)if he sacrifices it to your opinion.” —Edmund Burke, 1774 |
Ben Finney

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


Re: Question about math.pi is mutable

2015-11-06 Thread Ben Finney
Bartc <b...@freeuk.com> writes:

> Is there no way then in Python to declare:
>
>pi = 3.141519 # etc
>
> and make it impossible to override?

No, and it would be a bad thing if that were something a library author
could forbid.

Python assumes the programmers using it are consenting adults. Doing
harmful things is difficult but not forbidden.

Notably, the author of a library should not be forbidding the Pythonic
ability to change name bindings as needed.

If you want to have a different value bound to the name ‘math.pi’, and
you go ahead and explicitly ask to change that binding, the library
author has no business forbidding that.

-- 
 \  “Software patents provide one more means of controlling access |
  `\  to information. They are the tool of choice for the internet |
_o__) highwayman.” —Anthony Taylor |
Ben Finney

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


Re: Regular expressions

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

> On Wed, 4 Nov 2015 07:57 pm, Peter Otten wrote:
>
> > I tried Tim's example
> > 
> > $ seq 5 | grep '1*'
> > 1
> > 2
> > 3
> > 4
> > 5
> > $
>
> I don't understand this. What on earth is grep matching? How does "4"
> match "1*"?

You can experiment with regular expressions to find out. Here's a link
to the RegExr tool for the above pattern <URL:http://regexr.com/3c4ot>.

Matching patterns can include specifications meaning “match some number
of the preceding segment”, with the ‘{n,m}’ notation. That means “match
at least n, and at most m, occurrences of the preceding segment”. Either
‘n’ or ‘m’ can be omitted, meaning “at least 0” and “no maximum”
respectively.

Those are quite useful, so there are shortcuts for the most common
cases: ‘?’ is a short cut for ‘{0,1}’, ‘*’ is a short cut for ‘{0,}’,
and ‘+’ is a short cut for ‘{1,}’.

In this case, ‘*’ is a short cut for ‘{0,}’ meaning “match 0 or more
occurences of the preceding segment”. The segment here is the atom ‘1’.
Since ‘1*’ is the entirety of the pattern, the pattern can match zero
characters, anywhere within any string. So, it matches every possible
string.

To match (some atom) 1 or more times, ‘+’ is a short cut for ‘(1,}’
meaning “match 1 or more occurrences of the preceding segment”.

-- 
 \學而不思則罔,思而不學則殆。 (To study and not think is a waste. |
  `\ To think and not study is dangerous.) |
_o__)—孔夫子 Confucius (551 BCE – 479 BCE) |
Ben Finney

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


Re: Regular expressions

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

> Yes yes, I know that regexes aren't the only tool in my tool box, but
> *right now* I want to learn how to use regexes.

I'll gently suggest this isn't a particularly good forum to do so.

Learn them with a tool like <URL:http://www.regexr.com/> and a tutorial
<URL:http://www.usna.edu/Users/cs/wcbrown/regexp/RegexpTutorial.html> or
something longer.

-- 
 \“Fascism is capitalism plus murder.” —Upton Sinclair |
  `\   |
_o__)      |
Ben Finney

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


What does “grep” stand for? (was: Regular expressions)

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

> On Wednesday 04 November 2015 13:55, Dan Sommers wrote:
>
> > Its very name indicates that its default mode most certainly is
> > regular expressions.
>
> I don't even know what grep stands for. 

“grep” stands for ‘g/RE/p’.

The name is a mnemonic for a compound command in ‘ed’ [0], a text editor
that pre-dates extravagant luxuries like “presenting a full screen of
text at one time”.


In an ‘ed’ session, the user is obliged to keep mental track of the
current line in the text buffer, and even what that text contains during
the session.

Single-letter commands, with various terse parameters such as the range
of lines or some text to insert, are issued at a command prompt one
after another.

For these reasons, the manual page describes ‘ed’ as a “line-oriented
text editor”. Everything is done by specifying lines, blindly, to
commands which then operate on those lines.

The name of the ‘vi’ editor means “visual interface (to a text editor)”,
to proudly declare the innovation of a full screen of text that updates
content during the editing session. That was not available for users of
‘ed’.


A very common command to issue, then, is “actually show me the line of
text I just specified”; the ‘p’ (for “print”) command.

Another very common command is “find the text matching this pattern and
perform these commands on it”, which is ‘g’ (for “global”). The ‘g’
command addresses text matching a regular expression pattern, delimited
by slashes ‘/’.

So, for users with feeble human brains incapable of remembering
perfectly the entire content of the text while it changes and therefore
not always knowing exactly which lines they wanted to operate on without
seeing them all the time, a very frequent combination command is:

g/RE/p

meaning “find lines forward from here that match the regular expression
pattern “RE”, and do nothing to those lines except print them to
standard output”.


Wikipedia has useful pages on both ‘grep’ and ‘ed’
<URL:https://en.wikipedia.org/wiki/Grep>
<URL:https://en.wikipedia.org/wiki/Ed_%28text_editor%29>.

You can see a full specification of how the ‘ed’ interface is to behave
as part of the “Open Group Base Specifications Issue 7”, which is the
specification for Unix.

<URL:http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ed.html>

See the manual for GNU ed which includes an example session to
appreciate just how far things have come.


<URL:https://www.gnu.org/software/ed/manual/ed_manual.html#Introduction-to-line-editing>

Of course, if you yearn for the days of minimalist purity, nothing beats
Ed, man! !man ed


[0] The standard text editor.
<URL:https://www.gnu.org/fun/jokes/ed-msg.txt>

-- 
 \ “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 PNG Viewer(Browser Based)

2015-11-03 Thread Ben Finney
Arshpreet Singh <arsh...@gmail.com> writes:

> On Tuesday, 3 November 2015 21:32:03 UTC+5:30, Chris Warrick  wrote:
> > Your problem is lack of basic understanding of the Internet. 
>
> Yes That's true at some level.

More specifically, your problem is not “how do I do this with Python?”
but rather “what is a web page?”.

So, the research you need to do is not Python-specific, instead you need
to learn about the structure of web pages and web applications.

> My present working system shows me list of all files (PNGs, JPGs, txt,
> SVGs) in browser, when I click on file it opens it and show contents
> of it.

You are directing your web browser to visit a folder on your local file
system. It is obliging you by presenting a directory of local files.

Instead, you need to learn how to author web pages.

There are countless resources for learning about generating a web page
from scratch. You could learn a lot from the Wikibooks project
<URL:https://en.wikibooks.org/wiki/Authoring_Webpages>.

You'll also need to appreciate that developing web pages is a *very*
extensive topic. You might need nothing more than to create simple
static pages; you don't need Python at all for that. You might need a
powerful Web programming framework, Python has excellent support for
that <URL:https://wiki.python.org/moin/WebFrameworks>.

Without you learning the very basics of web sites, though, you won't get
much use from Python-specific knowledge about web frameworks.

Good hunting!

-- 
 \  “Ridicule is the only weapon which can be used against |
  `\   unintelligible propositions.” —Thomas Jefferson, 1816-07-30 |
_o__)          |
Ben Finney

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


Re: need help understanding a python program

2015-11-02 Thread Ben Finney
Lee Bradley <teamprimalfo...@gmail.com> writes:

> http://pastebin.com/ndDYjYe1

We much prefer to discuss code in the context of plain text messages
right here, because this forum is archived longer than the expected
lifetime of content hosted on other services.

> For now I am looking for someone who can dig into this code and
> explain what's going on. I understand a lot of it but not enough to
> really *get it*.

Could you discuss your own impressions of it so far, with (parts of) the
code pasted here as plain text for context of your commentary?

-- 
 \   Moriarty: “Forty thousand million billion dollars? That money |
  `\must be worth a fortune!” —The Goon Show, _The Sale of |
_o__)       Manhattan_ |
Ben Finney

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


Re: Python 2 vs Python 3 for teaching

2015-11-01 Thread Ben Finney
<paul.hermeneu...@gmail.com> writes:

> This would make an excellent opportunity to develop a curriculum to
> teach students how to maintain a 2.x and 3.x code base using 2to3.

The advice today reflects the great progress that has been made over
many years of migrating projects and organisations to Python 3.

Instead of ‘2to3’, the best advice today is: write new code targeting
Python 3 directly, and only if necessary back-port to Python 2.

> 2.x is not going away as fast as some would like.

Likewise, Python 3 as a primary development target is not as difficult
as some would fear.

Python 2 is unarguably a legacy platform, but it has good support for
receiving code carefully targeting both Python 2 and Python 3. So it's
best to target Python 3 primarily, and back-port code to Python 2 only
as and when needed.

-- 
 \   “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: Problem in implementing Romania Map using Paython Script

2015-11-01 Thread Ben Finney
amn...@gmail.com writes:

> I need a help in completing the Class Roaming problem using Euclidean
> function , Completing the Class Node .

I think you need to research how to solve this algorithm, and only
*then* think about how to code it in Python.

Is this a homework assignment?

> And def treesearch and graph search problem ?
>
> Waiting for reply 

You may not intend it, but adding multiple question marks communicates
urgent insistence, and is rather rude in a request to a community of
volunteers.

-- 
 \ “I may disagree with what you say, but I will defend to the |
  `\death your right to mis-attribute this quote to Voltaire.” |
_o__)   —Avram Grumer, rec.arts.sf.written, 2000-05-30 |
Ben Finney

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


Re: How to make this simple code look better

2015-10-27 Thread Ben Finney
Dennis Lee Bieber <wlfr...@ix.netcom.com> writes:

>   Actually, if 0 is success, and you are testing for a failure, it
> should probably just be
>
>   if ret:
>   #do error

That obscures the intent; there is nothing about “is ‘ret’ false?” that
tells me what the meaning of that test is.

It happens to be the case that “success” is a false-y value, but that's
not clear from reading a simple “if ret” test.

Instead, I advise making it clear *why* we're checking zero in
particular: because in this case zero means success. That's not obvious,
and should be explicit.

EXIT_CODE_SUCCESS = 0

# …

(stdout_content, stderr_content) = proc.communicate()
if proc.returncode != EXIT_CODE_SUCCESS:
handle_the_failure(proc)

-- 
 \  “The process by which banks create money is so simple that the |
  `\ mind is repelled.” —John Kenneth Galbraith, _Money: Whence It |
_o__)   Came, Where It Went_, 1975 |
Ben Finney

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


Re: Ignore stderr and use return code

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

> In the below code, we found that the command i.e cmd = "mount
> /filesystem1" succeeded. But the test failed due to the weaker stderr

I don't know what you mean by stderr being “weaker”.

> def mount_me():
> cmd = "mount /filesystem1"
> proc = subprocess.Popen(shlex.split(cmd),
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> out, err = proc.communicate()
> if err != "":
> logging.error("Can't run %s got %s!" % (cmd, err))
> return False

The test ‘if err != ""’ implies you are checking *only* whether the value
is an empty string. It might be clearer if you write ‘if err’.

The error message implies the process *could not* run, but that's not
the case. If that line is reached, the process did run to completion.
The presence of output on stderr does not imply the process failed.

If instead you want to check whether the process failed, check its exit
status. The “exit status” of a process, indicating success or failure,
is “returned” by the subprocess back to Python and is available as
‘Popen.returncode’::

EXIT_STATUS_SUCCESS = 0
if proc.returncode != EXIT_STATUS_SUCCESS:
logging.error(
"Subprocess {cmd} failed with code {code:d},"
" error output {err}".format(
cmd=cmd, code=proc.returncode, err=err))

> Verification:

I don't quite understand the claim of “weaker”, so I don't know what is
verified here.

>  - To handle this case, Iam planning to use return code and modify the
> above code as below ( Any other suggestions please let me know)

You may also want to think about whether raising an exception is
appropriate (rather than just returning False).

> -  Do I need to add more check to ensure the mount actually succeeds,
> may be a function?

I'd suggest relying on the exit status from the command, unless you have
good evidence it is unreliable.

-- 
 \ “When people believe that they have absolute knowledge, with no |
  `\ test in reality, this [the Auschwitz crematorium] is how they |
_o__) behave.” —Jacob Bronowski, _The Ascent of Man_, 1973 |
Ben Finney

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


Please post “text/plain” message body (was: Best way to do background calculations?)

2015-10-25 Thread Ben Finney
Israel Brewster <isr...@ravnalaska.net> writes:

[no text]

Please ensure your email message body is “text/plain” (and preferably
not HTML) when posting to unfamiliar recipients — which is always, on a
public forum like this.

-- 
 \“Pinky, are you pondering what I'm pondering?” “Umm, I think |
  `\   so, Brain, but three men in a tub? Ooh, that's unsanitary!” |
_o__)   —_Pinky and The Brain_ |
Ben Finney

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


Re: OT snake_case

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

> I just discovered today that writing names in lowercase with
> underscores is sometimes called "snake case".
>
> Seems kind of apt for Python! :-)

Cute!

> Apparently, it was coined in the Ruby community...

Do you have references for tracing the origin of that term?

-- 
 \   “You can be a theist, and you can be a skeptic. But if you're |
  `\  both, you're not very good at one of them.” —Dave Silverman, |
_o__)       2011-11-19 |
Ben Finney

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


What does it mean for Python to have “constants”? (was: variable scope of class objects)

2015-10-20 Thread Ben Finney
Dennis Lee Bieber <wlfr...@ix.netcom.com> writes:

> (Python does not have anything that one might consider a true constant
> -- other than the language defined singletons: None, and maybe by now
> True and False).

Python now deals with those by making the names keywords::

>>> True = object()
  File "", line 1
SyntaxError: can't assign to keyword
>>> False = object()
  File "", line 1
SyntaxError: can't assign to keyword
>>> None = object()
  File "", line 1
SyntaxError: can't assign to keyword

which seems to rather avoid the question of whether they are “constants”
as would be understood by newcomers experienced with that term in other
languages.

-- 
 \   “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: Stylistic question regarding no-op code and tests

2015-10-14 Thread Ben Finney
Jason Swails <jason.swa...@gmail.com> writes:

> What I recently realized, though, that what this construct allows is
> for the coverage testing package (which I have recently started
> employing for my project... thanks Ned and others!) to detect whether
> or not both code paths are covered in the test suite.

Coverage.py has, for many releases now, had good measurement of branch
coverage by your tests. Enable it with the ‘--branch’ option to ‘run’
<URL:https://coverage.readthedocs.org/en/latest/branch.html>.

-- 
 \  “They who can give up essential liberty to obtain a little |
  `\temporary safety, deserve neither liberty nor safety.” |
_o__)   —Benjamin Franklin, 1775-02-17 |
Ben Finney

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


[issue25392] setup.py --quiet doesn't silence "no previously-included directories" warnings from MANIFEST.in

2015-10-13 Thread Ben Finney

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


--
nosy: +bignose

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25392>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Strong typing implementation for Python

2015-10-12 Thread Ben Finney
Sibylle Koczian <nulla.epist...@web.de> writes:

> Am 12.10.2015 um 13:39 schrieb Steven D'Aprano:
> > Auto-complete is a fine and useful tool. But if you are crippled as a
> > programmer without it, well, then you can hardly claim to understand the
> > language or framework you are programming in if you cannot use it without
> > an IDE doing half the work for you.
> >
>
> Well ... you're certainly quite right as far as Python and its
> standard library is concerned. But I don't know who would really want
> to use .NET without auto-complete and for all I know Java may be just
> as awful.

Yes, and that is quite compatible with Steven's assertion. The two
assertions:

* A programmer who feels crippled without auto-complete cannot claim to
  understand the language or framework they're programming in.
  (assertion made by Steven)

* The overwhelming majority of .NET and Java programmers would feel
  crippled without auto-complete. (assertion made by Sibylle)

can both be true. An obvious resolution is to conclude that the
overwhelming majority of Java and .NET programmers cannot claim to
understand those technologies.

Python, on the other hand, has the huge advantage that programming in
even a bare minimal editor is feasible, and editor features that make
the programmer's life easier are conveniences, not essential to be
competent in Python.

-- 
 \   “Free thought is a necessary, but not a sufficient, condition |
  `\   for democracy.” —Carl Sagan |
_o__)          |
Ben Finney

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


Re: Python 2.2 or 3.5

2015-10-11 Thread Ben Finney
Rustom Mody <rustompm...@gmail.com> writes:

> On Sunday, October 11, 2015 at 11:09:17 AM UTC+5:30, Mark Lawrence wrote:
> > On 11/10/2015 06:11, Rustom Mody wrote:
> > > At https://docs.python.org/3.5/faq/[…]
> > >
> > > it says
> > > In Python 2.2, you can inherit from built-in classes such as int, list, 
> > > dict, etc.
> > >
> > > So is it 3.5 or 2.2?
[…]
>
> Leave aside the decimal point I did not even specify 2 or 3
>
> Just gave "embedding python alternative to swig" to google and I get
> that 3.3 page

Fascinating, I'm sure. How is this relevant to your question about the
*content of the Python docs*?

If you want to complain about Google's search results, you know where to
find Google.

If you want to discuss the content of the Python docs, citing “what
Google showed me” is irrelevant.

-- 
 \“The idea that He would take his attention away from the |
  `\   universe in order to give me a bicycle with three speeds is |
_o__)  just so unlikely that I can't go along with it.” —Quentin Crisp |
Ben Finney

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


Re: Static typing implementation for Python

2015-10-11 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> Ben Finney <ben+pyt...@benfinney.id.au> writes:
> > The opposite of string typing is weak typing.
>
> Well, I would say *string* typing [as used in, for example, sh and tcl]
> is actually a form of weak typing.

I infer a smile as you write that, but to clarify for others: I made a
typo, and meant to contrast weak typing with strong typing.

-- 
 \“Like the creators of sitcoms or junk food or package tours, |
  `\ Java's designers were consciously designing a product for |
_o__)   people not as smart as them.” —Paul Graham |
Ben Finney

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


Static typing implementation for Python (was: Strong typing implementation for Python)

2015-10-10 Thread Ben Finney
John Michael Lafayette <johnmichaelreed...@gmail.com> writes:

> I would like Python to have a strong typing feature that can co-exist
> with the current dynamic typing system.

You have incorrectly conflated two separate matters.

The opposite of string typing is weak typing. Python has strong typing:
its objects will only behave according to the type they're defined as,
and won't pretend to be what they're not.

The opposite of dynamic typing is static typing. Python has dynamic
typing: references are not at all restricted in what type of object they
reference.

> I would like Python to also be able to also do this:
>
> Animal a = Factory.make("dog")# okay. Dog is Animal.
> Dog d = Factory.make("dog") # okay. Dog is Dog.
> Cat c = Factory.make("cat")   # Runtime error. Dog is not Cat.

By that example, you appear to want static typing: references are
restricted to a particular type and cannot refer to other types.

The two ends of that spectrum are pretty much incompatible: to gain
static typing, you must lose dynamic typing.

That does not strike me as an improvement for Python. There are plenty
of statically-typed languages; why would you want Python to lose its
dynamic typing?

> With a strong typing option that performs runtime type checking, the
> reader can be certain that the program is running the type they
> expect. Also, the IDE can be more helpful.

Type annotations <URL:https://www.python.org/dev/peps/pep-3107/> and
type hints <URL:https://www.python.org/dev/peps/pep-0484/> are both in
Python already.

They are entirely optional: code which does not use them can ignore them
completely. However, they appear to provide the benefits you describe,
without losing any of the power of dynamic typing.

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

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


Re: doc-generation tool

2015-10-06 Thread Ben Finney
<c.bu...@posteo.jp> writes:

> I am confused about to much possible tools and conventions for
> doc-strings and the doc-generating tools using it.

Thank you for taking seriously the job of documenting your software!

> My code isn't about a package interface. It is just a simple
> application I want I readable documentation for.

I am confused; maybe you can help me.

You say that you *don't* want documentation for “a package interface”,
by which I think you mean the interface a programmer needs to use your
code <URL:https://en.wikipedia.org/wiki/Application_programming_interface>.

So I think for “a simple application I want readable documentation for”,
I think you are explicitly asking for documentation to be read primarily
by the (non-programmer) *users* of the application.

> I have the following needs
>  - in-code doc-string should be readable for humans (e.g.
>reStructuredText, markup)
>  - type of a methode-argument or class-attribute can be specified
>  - no seperation between class-doc-string and
>class-attribute-doc-strings. the attribute should be described in
>the class-doc-string itself

That is all related to the documentation of very fine-grained parts of
your code; exactly the kind of documentation that is useful for a
programmer needing API documentation.

Your list, above, is *not* what I would expect for an application's
(non-programmer) end-user documentation.

Which is it? Do you want to produce API documentation, or end-user
documentation?

-- 
 \ “I still have my Christmas Tree. I looked at it today. Sure |
  `\   enough, I couldn't see any forests.” —Steven Wright |
_o__)          |
Ben Finney

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


Re: Python 2 ‘print’, coercing arguments to Unicode

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

> Hmm, now that I read the six document again
>  @six.python_2_unicode_compatible


Peter Otten <__pete...@web.de> writes:

> I don't think this is possible with the print statement, but the
> print() function can be replaced with anything you like:


Hmm. I am more looking for something that doesn't involve replacing
‘print’, but rather to hook into whatever it uses to coerce the type of
its arguments.

-- 
 \“The problem with television is that the people must sit and |
  `\keep their eyes glued on a screen: the average American family |
_o__) hasn't time for it.” —_The New York Times_, 1939 |
Ben Finney

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


Python 2 ‘print’, coercing arguments to Unicode

2015-10-06 Thread Ben Finney
Howdy all,

In Python 2.7, I am seeing this behaviour for ‘print’::

Python 2.7.10 (default, Sep 13 2015, 20:30:50)
[GCC 5.2.1 20150911] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> from __future__ import print_function
>>> import io
>>> print(None)
None
>>> print(None, file=io.StringIO())
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unicode argument expected, got 'str'

So, although my string literals are now Unicode objects, apparently
‘print’ still coerces objects using the bytes type ‘str’.

Binding the ‘str’ name to the Unicode type doesn't help::

>>> str = unicode
>>> print(None, file=io.StringIO())
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unicode argument expected, got 'str'

The reason I need to do this is that I'm replacing the standard streams
(‘sys.stderr’, etc.) with ‘io.StringIO’ instances in a test suite. That
works great for everything but ‘print’.

Since this is a test suite for existing code, I don't have the option to
change all the existing statements; I need them to work as-is.

How can I convince ‘print’, everywhere throughout a module, that it
should coerce its arguments using ‘unicode’?

-- 
 \  “Not using Microsoft products is like being a non-smoker 40 or |
  `\ 50 years ago: You can choose not to smoke, yourself, but it's |
_o__)   hard to avoid second-hand smoke.” —Michael Tiemann |
Ben Finney

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


Re: Python 2 ‘print’, coercing arguments to Unicode

2015-10-06 Thread Ben Finney
Terry Reedy <tjre...@udel.edu> writes:

> On 10/6/2015 6:45 AM, Ben Finney wrote:
> > Ben Finney <ben+pyt...@benfinney.id.au> writes:
>
> > How can I convince ‘print’, everywhere throughout a module, that it
> > should coerce its arguments using ‘unicode’?
>
> Use Python 3.  I am only half joking.  Switching to unicode  instead
> of bytes as the default text type fixed numerous bugs all at once.

This is all part of a transition to Python 3, so I am fully on board
with that. It doesn't help address the problem to tell me I want to do
what I'm already in pursuit of doing :-)

-- 
 \“Intellectual property is to the 21st century what the slave |
  `\  trade was to the 16th.” —David Mertz |
_o__)          |
Ben Finney

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


Re: Python 2 ‘print’, coercing arguments to Unicode

2015-10-06 Thread Ben Finney
Peter Otten <__pete...@web.de> writes:

> Have a look at PyFile_WriteObject in Objects/fileobject.c.
> As I understand the code it basically does
>
> if isinstance(obj) and stream.encoding is not None:
> s = obj.encode(stream.encoding))
> else:
> s = str(obj)
> stream.write(s)

So as I understand it I'm looking for the hypothetical

from __future__ import print_coerce_args_to_unicode

and without that, I'm stuck with the hard-coded ‘str’ coercion.

Thanks, at least now I can stop flailing to try to get it working.

-- 
 \   “Fear him, which after he hath killed hath power to cast into |
  `\   hell; yea, I say unto you, Fear him.” –Jesus, as quoted in Luke |
_o__)         12:5 |
Ben Finney

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


Re: Python 2 ‘print’, coercing arguments to Unicode

2015-10-06 Thread Ben Finney
Ben Finney <ben+pyt...@benfinney.id.au> writes:

> In Python 2.7, I am seeing this behaviour for ‘print’::
>
> Python 2.7.10 (default, Sep 13 2015, 20:30:50)
> [GCC 5.2.1 20150911] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from __future__ import unicode_literals
> >>> from __future__ import print_function
> >>> import io
> >>> print(None)
> None
> >>> print(None, file=io.StringIO())
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: unicode argument expected, got 'str'
>
> So, although my string literals are now Unicode objects, apparently
> ‘print’ still coerces objects using the bytes type ‘str’.

To eliminate ‘from __future__ import print_function’ as a possible
factor, here is another demonstration without that::

Python 2.7.10 (default, Sep 13 2015, 20:30:50) 
[GCC 5.2.1 20150911] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> import sys
>>> import io
>>> print "foo"
foo
>>> print None
None
>>> sys.stdout = io.StringIO()
>>> print "foo"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unicode argument expected, got 'str'
>>> print None
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unicode argument expected, got 'str'

So it appears that even a string literal, which is explicitly Unicode by
the above ‘from __future__ import unicode_literals’, is still being
coerced to a bytes ‘str’ object by ‘print’.

How can I convince ‘print’, everywhere throughout a module, that it
should coerce its arguments using ‘unicode’?

-- 
 \  “Pity the meek, for they shall inherit the earth.” —Donald |
  `\  Robert Perry Marquis |
_o__)  |
Ben Finney

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


Re: Pyarmor, guard your python scripts

2015-10-05 Thread Ben Finney
Josef Pktd <josef.p...@gmail.com> writes:

> related

Care to give us a summary of what that is, and describe what you think
is the relevant point?

-- 
 \  “The best way to get information on Usenet is not to ask a |
  `\   question, but to post the wrong information.” —Aahz |
_o__)          |
Ben Finney

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


Re: Idiosyncratic python

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

> On Thursday 24 September 2015 16:16, Paul Rubin wrote:
>
> > Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> writes:
> >> for k, v in mydict.items():
> >> del(k)
>
> […] The obvious intent is to iterate over the *values* of the
> dictionary, but the coder didn't know about values, so he iterated
> over (key,value) pairs, then deleted the key local variable (not the
> key in the dict!) to keep the namespace clean.

That's not obvious to me. It's plausible, now that you say it. I find it
also plausible, though, that the author is under the mistaken impression
that the key and value must both be deleted, and has found a way that
appears to do that.

Perhaps what we're illustrating here is exactly why such idiosyncratic
code *is* bad: it obscures the intent of the code for programmers who
know idiomatic Python.

And those readers are hopefully the ones the author should be trying to
communicate to, on the theory that we've all got the goal to become a
programmer who knows idiomatic Python.

-- 
 \“The fact of your own existence is the most astonishing fact |
  `\you'll ever have to confront. Don't dare ever see your life as |
_o__)boring, monotonous, or joyless.” —Richard Dawkins, 2010-03-10 |
Ben Finney

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


Re: Pyarmor, guard your python scripts

2015-09-18 Thread Ben Finney
Jondy Zhao <jondy.z...@gmail.com> writes:

> In reality, when we leave the house, we lock the door, even the lock
> could not make sure the safe of our property. It's just make it
> difficult. It's same in the software world. Someone need the lock in
> both of the world.

Yes, please don't encourage authors to put locks into people's computers
that restrict those people's access to use them.

And we won't come to install a lock that restricts your access to your
house.

In other words: Please don't arrogate to anyone the presumed right to
restrict how people run programs on their own computers.

-- 
 \   “It ain't so much the things we don't know that get us in |
  `\trouble. It's the things we know that ain't so.” —Artemus Ward |
_o__) (1834–1867), U.S. journalist |
Ben Finney

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


Re: Pyarmor, guard your python scripts

2015-09-17 Thread Ben Finney
Jondy Zhao <jondy.z...@gmail.com> writes:

> Think that python developer is manufacturer, and he want to sell his
> product to the customers who don't know anything about programming.

Are you also assuming those customers have no-one they can talk with who
knows programming?

> He don't hope his customers redistribute his product, that's protected
> by Pyarmor.

Pyarmor is not going to stop them redistributing anything. If they're
motivated to redistribute the code, this won't stop them. If they're
motivated to examine what the code does, this will increase the effort
but not stop them.

At best, it will annoy customers who want to get someone's help in
debugging the product. That sounds like an anti-feature.

-- 
 \ “This world in arms is not spending money alone. It is spending |
  `\  the sweat of its laborers, the genius of its scientists, the |
_o__)   hopes of its children.” —Dwight Eisenhower, 1953-04-16 |
Ben Finney

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


Automating build from source (was: Automating Sphinx generated documentation)

2015-09-17 Thread Ben Finney
David Aldrich <david.aldr...@emea.nec.com> writes:

> I have setup Sphinx for my Python project. We keep all our code and
> documentation in Subversion.

It's a good idea to keep *source* files in VCS.

It's a bad idea to keep automatically-generated files in VCS; it's
especially bad to do so if they need to be generated again after
changing the source files.

> So, following changes to the Python code, I need to regenerate and
> commit the Sphinx generated documentation.

Instead, the build products – anything generated automatically by the
computer, such as the compiled code, compiled documentation – should be
flagged for “ignore” by the VCS, and never committed.

The VCS should track only those files that humans edit directly.

> I just wondered how people manage this. I'm thinking of using Jenkins
> (a continuous integration tool) to check for changes, regenerate the
> docs and check them in.

Deploying the code base, whether for testing or to staging or production
or wherever, should entail a build step. That build step is responsible
for going from source-files-only, checked out from the VCS, to a
complete ready-to-deploy tree of files.

That build step should always start from a clean source tree, so that
you always know the end result reflects what was committed to VCS.

Build tools include old-school Makefile, or newer tools like Meson.

Note that this is automated build. This is a different question from
automated deployment (you might like Fabric for that), and is a
different question from automated integration (you might like Jenkins
for that).

First, though, you need an automated build, so you can separate “what's
tracked in VCS” versus “what's generated automatically”.

-- 
 \   “If we listen only to those who are like us, we will squander |
  `\   the great opportunity before us: To live together peacefully in |
_o__)a world of unresolved differences.” —David Weinberger |
Ben Finney

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


Re: Pyarmor, guard your python scripts

2015-09-17 Thread Ben Finney
Jondy Zhao <jondy.z...@gmail.com> writes:

> For example, I develop a game by python. What I want to do is that the
> player or the agent could not simply copy the game to others. For the
> player or the agent, they needn't research the game.

Deciding for the customer what they may not do, on their own computer,
is quite hostile. Please don't enable such restrictions.

-- 
 \   “We must find our way to a time when faith, without evidence, |
  `\disgraces anyone who would claim it.” —Sam Harris, _The End of |
_o__) Faith_, 2004 |
Ben Finney

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


Re: Terminology: "reference" versus "pointer"

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

> On Wed, Sep 16, 2015 at 6:14 PM, Gregory Ewing
> <greg.ew...@canterbury.ac.nz> wrote:
> > This suggests an alternative model for Python computation. All data
> > is represented by cats. A variable is a box containing a cat.
> > Assignment replaces one cat with an entangled copy of another cat,
> > so that mutating either one affects the other.
>
> Quantum computing is the way of the future!

Tachyon computing is the way of the future *and* the past.

-- 
 \  “[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


Re: Pyarmor, guard your python scripts

2015-09-15 Thread Ben Finney
Jondy Zhao <jondy.z...@gmail.com> writes:

> Pyarmor is a simple to use tool which is capable of importing or
> running encrypted Python script files. Moreover, it can apply encoding
> algorithms to your Python scripts, in order to help you protect them
> before you can distribute them. You may also generate license files
> with custom validity conditions.

Protect them from whom? What is the threat model against which Pyarmor
is claimed to protect? Who is the attacker, who is being protected?

> The program allows you to encrypt files, but to also open and run them
> as if no protection was applied. Moreover, it can run or import
> encrypted Python scripts in any target machine, only in specified
> machines or before a specified date. This aspect can be controlled by
> the creation of the license files: bound to a hard disk serial number
> or by an expiration date.

So a Python file encrypted this way will be arbitrarily restricted in
how it can be inspected for debugging, performance monitoring, and
testing?

This seems to explicitly treat the user of the Python software as a
hostile attacker. That is not a friendly or respectful position, and I
hope I misunderstand Pyarmor's operation.

-- 
 \   “Any fool can write code that a computer can understand. Good |
  `\   programmers write code that humans can understand.” —Martin |
_o__)      Fowler, _Refactoring_, 2000 |
Ben Finney

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


Re: Putting the main program in a main function

2015-09-14 Thread Ben Finney
"ast" <nom...@invalid.com> writes:

> The author says that with this structure there are no global variables
> (except when using "global' keyword) and that the program can be
> loaded as a module without be ran to test the function in the python
> shell.
>
> is it advised to always write programs like that ?

Writing all the code in functions makes your code more reliably tested:
you can write a unit test that exercises the code and know whether it is
behaving correctly.

Writing all the code in functions makes your code more understandable:
the possible interactions between different parts of the program are
more explicitly and strictly defined.

So yes, it's advisable to write a ‘main’ function for the application
and keep to absolute minimum the ‘if __name__ == "__main__"’ block.

That said, your ‘main’ function can be slightly more self-contained. The
paradigm for invoking a command-line program is that its input
parameters are the process's command-line arguments, and its return
value is the process's exit status.

So you can write a ‘main’ function that explicitly allows those input
and output to be handled as for a normal function::

import sys

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

:param argv: The sequence of command-line arguments used to
invoke this program. Defaults to `sys.argv`.
:return: ``None``.

"""
if argv is None:
argv = sys.argv

try:
handle_the_command_line(argv)
do_various_things()

except SystemExit as exc:
exit_status = exc.code
else:
# No exit requested; return “success” status.
exit_status = 0

return exit_status

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

That way, the ‘if __name__ == "__main__"’ block will use the
conventional input (command-line arguments) and output (process exit
status); the rest of the application code may call ‘sys.exit’ or raise
‘SystemExit’ as normal; but your code will wrap it all up as the inputs
and outputs of the ‘main’ function, making it much easier to control for
testing.

Python's BDFL wrote an article many years ago describing this pattern
<URL:http://www.artima.com/weblogs/viewpost.jsp?thread=4829>, mine is a
small refinement of that.

-- 
 \ “It is the fundamental duty of the citizen to resist and to |
  `\  restrain the violence of the state.” —Noam Chomsky, 1971 |
_o__)  |
Ben Finney

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


Re: Terminology: "reference" versus "pointer"

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

> I think Ben's referring to taunting jmf, whom Mark called the "RUE" or
> "Resident Unicode Expert". There has been a long-standing antagonism
> between those two (which is completely understandable), and one which
> often spills over into vitriolic posts (which is less acceptable).

Chris has it right.

What's especially unacceptable is invoking that person for amusement,
irrelevant to the conversation. It's one thing to respond when a person
comes into a thread to troll unbidden; it is quite another to taunt them
unprompted.

-- 
 \ “I call him Governor Bush because that's the only political |
  `\  office he's ever held legally.” —George Carlin, 2008 |
_o__)          |
Ben Finney

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


Re: Terminology: "reference" versus "pointer"

2015-09-12 Thread Ben Finney
Rustom Mody <rustompm...@gmail.com> writes:

> On Saturday, September 12, 2015 at 11:57:01 AM UTC+5:30, Ben Finney wrote:
> > You've clearly committed to some ontology that just doesn't match
> > the Python data model.
>
> How about lay-English ontology in which "point to" and "refer to" are fairly
> synonymous?

That's important. It's unrelated, though, to the very specific technical
programming concepts to which I was responding.

-- 
 \  “One bad programmer can easily create two new jobs a year. |
  `\  Hiring more bad programmers will just increase our perceived |
_o__)     need for them.” —David Lorge Parnas, 1999-03 |
Ben Finney

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


Re: Terminology: "reference" versus "pointer"

2015-09-12 Thread Ben Finney
Michael Torrie <torr...@gmail.com> writes:

> On 09/12/2015 08:22 PM, Mark Lawrence wrote:
> > You appear to have the same level of knowledge of Python internals as 
> > the RUE has of the Python 3.3+ FSR unicode implementation.  Let's have 
> > some fun, is Python pass by value or pass by reference?  It has to be 
> > more interesting debating that than the drivel that's gone before in 
> > this thread.
>
> Oh you are a devious one there! This should get good.

No, it should stop there. Taunting trolls is no more welcome here than
trolling.

-- 
 \   “I have always wished for my computer to be as easy to use as |
  `\   my telephone; my wish has come true because I can no longer |
_o__)  figure out how to use my telephone.” —Bjarne Stroustrup |
Ben Finney

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


Re: Terminology: “reference” versus “pointer”

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

> Ben Finney <ben+pyt...@benfinney.id.au> writes:
> > The reference value is inaccessible to the program, it can only be
> > used to get at the referenced object.
>
> What does it mean to access something, if not to do some operation on
> it? Getting the referenced object is the operation you can do with it.

You've clearly committed to some ontology that just doesn't match the
Python data model.

The following are some of the axioms in Python's data model:

* All values are objects that persist over time.

* All objects have an immutable identity, that is guaranteed different
  from all other coexisting objects.

* The identity of an object has no particular relationship to the
  object's implementation or location [0], it is an abstract value that
  has no meaning other than uniquely identifying the object.

* The ‘id’ function returns the identity of the object passed as the
  parameter to the call.

* A name used to access an object is a reference to that object,
  equivalent to an item in a dictionary.

* A collection instance — a list, a dict, a set, etc. — contains
  references to objects, and provide access to those references via the
  container type's API.

If you don't agree with those, that's too bad, and it means there's not
much point continuing the discussion. I hope, therefore, that you do
agree with those axioms.

If you do agree with those, some corollaries follow:

* Container types do not contain objects.

  It is a useful analogy to say the objects are “in” the container; but
  that would imply they are not simultaneously in any other container.
  That's not true, so it's a flawed (though very useful) analogy.

* Names do not contain anything.

  They aren't what some other languages call “variables”. They are
  oblivious to the type of the value and can never exist except while
  referencing some object.

* References are not values.

  The reference obviously must have an implementation that deals with
  values, but those values are not available in Python. Each reference
  is inaccessible, hidden away; it is not a value, it is not an object.

> So, if you have a list x, and assign a new value to x[0], it doesn't
> change the list, because you can't compare the list to the value the
> list had before?

Yes, it changes the list. It doesn't change any of the references
themselves.

The list's value is the sequence of references it contains. Removing one
reference changes the list's value; putting a different reference in the
collection changes the list's value.

None of that changes any reference, it just changes *which* references
are in the list.

The references themselves don't have any value accessible to Python.

> You're not making any sense. It's a value. Changing it and "throwing
> away and replacing with a different one" are the same thing.

Not true. To throw away one and replace it with another is to switch to
a different value with a different identity::

>>> foo = 17 # One reference to the integer object.
>>> bar = foo# A different reference to the object.
>>> id(foo) == id(bar)# Are these references to the same object?
True
>>> bar = 9   # Try to “change” the object.
>>> id(foo) == id(bar)# Is ‘bar’ still the same object?
False

To change a value is to keep the same identity::

>>> foo = [17, 23, 42]# One reference to the list object.
>>> bar = foo # A different reference to the object.
>>> id(foo) == id(bar)# Are these references to the same object?
True
>>> id(foo[2]) == id(bar[2])  # How about the references contained in the 
list?
True
>>> bar[2] = 9# Try to “change” the object.
>>> id(foo) == id(bar)# Is ‘bar’ still the same object?
True

References aren't values, so their identity doesn't even feature in
Python's data model.

From the point of view of a Python program, a reference *has no value*
(and no identity). It is just a metaphorical label, tag, or “sticky
note” one can invoke to make a specific object available.

> > That's significant, because unlike a mutable value you can never
> > again get at the old reference in the Python program.
>
> I don't understand what you mean by "can never again get at" it if you
> think you _can_ do it for mutable values.

In the above example, the different references originally created for
‘foo’ and ‘bar’ are inaccessible. ‘foo’ and ‘bar’ are not the same, they
are different references that happen to lead to the same object.

When ‘bar’ switches to a different reference, whatever reference it had
at prior points in time are gone for good. Any other references to the
same object continue on unaffected, because they are not the same
reference.



[0]: Thi

Re: Terminology: “reference” versus “pointer”

2015-09-11 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> Ben Finney <ben+pyt...@benfinney.id.au> writes:
> > With the significant difference that “pointer” implies that it has its
> > own value accessible directly by the running program, such as a pointer
> > in C.
>
> Its own value *is* what you're accessing when you assign or return it.

You're not describing Python references. But I don't know what you are
describing with all those “it”s — what language, what behaviour, what
concept?

Can you clarify what you mean, and what in my description you are
disagreeing with?

> > That's different from a “reference”, which to my understanding
> > implies the running program does *not* normally have direct access
> > to it as a distinct value. The only way you can use a reference is
> > to get at the object to which it refers.
>
> In C++, references cannot be reassigned. I consider *that* the
> fundamental difference - a pointer is a variable that you can reassign
> and return; a reference always refers to the same object once created.

Sure, that will work fine.

So in Python, we don't have pointers because we don't have access to
change or reassign them.

A Python reference isn't accessible and can't be changed; you can just
make another reference and switch to that.

You can't, for example, keep the old reference (there are no references
to references in Python), because they're not accessible as values in
themselves. Once you assign a different reference, the old one is gone
and can't be found again.

-- 
 \“[T]he great menace to progress is not ignorance but the |
  `\   illusion of knowledge.” —Daniel J. Boorstin, historian, |
_o__)    1914–2004 |
Ben Finney

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


Re: Terminology: “reference” versus “pointer”

2015-09-11 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> Ben Finney <ben+pyt...@benfinney.id.au> writes:
>
> > Random832 <random...@fastmail.com> writes:
> >
> >> Ben Finney <ben+pyt...@benfinney.id.au> writes:
> >> > With the significant difference that “pointer” implies that it has its
> >> > own value accessible directly by the running program, such as a pointer
> >> > in C.
> >>
> >> Its own value *is* what you're accessing when you assign or return it.
> >
> > You're not describing Python references.
>
> Yes I am. You're just making the implicit assumption that a "value" has
> to be a number, and I was ignoring that assumption. The value is the
> address of an object. Like I said, an arrow on a diagram.

I made no assumption about the type; I don't care how the reference is
implemented in the Python interpreter. That's not accessible to the
running Python program without some API.

My assertion still stands: the address of the object is *not* what the
reference is, in Python. Calling ‘id(foo)’ does not return a reference
to ‘foo’, so I don't know how you think the value is accessible in the
Python program.

The reference value is inaccessible to the program, it can only be used
to get at the referenced object.

> > So in Python, we don't have pointers because we don't have access to
> > change or reassign them.
>
> Yes you do. That's _exactly what happens_ in an assignment statement -
> you are reassigning it to the address of another object. And that's
> something you *can't do* with references in C++.

The operation you describe doesn't change the reference; it doesn't
mutate an existing value which can be compared with whatever value it
had before. Instead, it throws away one reference and replaces it with a
different one.

That's significant, because unlike a mutable value you can never again
get at the old reference in the Python program.

> > You can't, for example, keep the old reference (there are no references
> > to references in Python), because they're not accessible as values in
> > themselves. Once you assign a different reference, the old one is gone
> > and can't be found again.
>
> You can keep it by copying it to somewhere.

How do you propose to “copy” a reference in Python? Making a new
reference to the referenced object is not making a copy of the
reference.

-- 
 \ “Demagogue: One who preaches doctrines he knows to be untrue to |
  `\ men he knows to be idiots.” —Henry L. Mencken |
_o__)  |
Ben Finney

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


Terminology: “reference” versus “pointer” (was: Python handles globals badly.)

2015-09-11 Thread Ben Finney
Random832 <random...@fastmail.com> writes:

> Honestly, whether you want to call the thing a pointer or a reference,
> you have to call it *something*, and I think "reference" is a worse
> fit based on its connotations from C++. Whatever you call it, it's an
> arrow on a diagram.

With the significant difference that “pointer” implies that it has its
own value accessible directly by the running program, such as a pointer
in C.

That's different from a “reference”, which to my understanding implies
the running program does *not* normally have direct access to it as a
distinct value. The only way you can use a reference is to get at the
object to which it refers.

That's the distinction I've been reying on for years, anyway: Python's
names are references, collections are collections of references, etc.
They aren't pointers because you can't get them as a distinct value; you
can only use them to refer to the object at the other end.

-- 
 \ “If we don't believe in freedom of expression for people we |
  `\   despise, we don't believe in it at all.” —Noam Chomsky, |
_o__)       1992-11-25 |
Ben Finney

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


Re: Context-aware return

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

> I have a function which is intended for use at the interactive
> interpreter, but may sometimes be used non-interactively. I wish to
> change it's output depending on the context of how it is being called.
> […]
>
> x = func()
> assert x == 999
>
> L = [1, 2, func(), 4]
> assert L[2] == 999
>
> func()
> # interactive interpreter prints "Awesome"
>
> Is such a thing possible, and if so, how would I do it?

That makes my skin creep. In the name of all the tea I've sacrificed to
Python over the years, I pray this isn't possible.

> If I did this thing, would people follow me down the street booing and
> jeering and throwing things at me?

First thing in the morning I will purchase a head of cabbage and store
it in a warm place to make it rot, on the off chance you find some
obscure way to achieve your benighted goal, just so I can be first in
line to throw it as you pass.

If ever I have to worry that some arbitrary Python function, unbenownst
to me, might have a branch that will make it behave differently
depending on *whether I bind a reference to its return value*, then I'll
know you are sent to us as an evil spirit to make all software suck.

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

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


Re: Context-aware return

2015-09-10 Thread Ben Finney
"Sven R. Kunze" <srku...@mail.de> writes:

> http://stackoverflow.com/questions/2356399/tell-if-python-is-in-interactive-mode

I'm pretty sure Steven knows full well the answer to that question,
which is not anything like the one he asked. Would you care to read the
question he did ask?

-- 
 \   “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


Reply to author, reply to list, reply to all (was: Need Help w. PIP!)

2015-09-09 Thread Ben Finney
Terry Reedy <tjre...@udel.edu> writes:

> On 9/8/2015 6:19 PM, Cody Piersall wrote:
> > On Sat, Sep 5, 2015 at 3:14 AM, Thomas 'PointedEars' Lahn
> > <pointede...@web.de <mailto:pointede...@web.de>> wrote:
> >  >
> >  > Cody Piersall wrote:
> >  >
> >  > > Please respond to the list as well as the person you're
> >  > > actually talking to. It works out better for everyone that way.
> >  > > (You should just have to "reply all" instead of "reply").
>
> [Reply] should send the reply to the list.

The function named “reply” normally means “reply individually to the
author”, and that's how it needs to stay.

The “reply to the list” function is present in many mail clients, and
works fine for this mailing list; Google Mail seems to be a notable
exception that its users should ask to change.

> > Some people email the list, but aren't subscribed to it.

People who fit that description are not participants in the forum, so
excluding them from forum replies is the right thing to do.

> > So I guess a better rule is to just reply-to-all for the OP?
>
> Please no, not as a routine.

Agreed.

-- 
 \   “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: Reply to author, reply to list, reply to all

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

> Personally, what I do (which I'm doing with this post) is to use
> Gmail's "reply-all" feature, and then manually delete the individual
> addresses.

That is testimony in support of the position that Google Mail is a
poorly-designed interface for discussion forums such as mailing lists.

Google Mail, like any other mail client, has full access to all the
technical information (specified in RFC 3696) needed to implement a
correct “reply to list” behaviour.

Users shouldn't need to do anything tediously manual like you describe,
they should be presented with an obvious “reply to the same place”
function, as implemented in many mail clients for over a decade.

That Google Mail continues to fail in this regard is something its users
need to apply pressure to fix, or choose better mail clients until it
improves.

-- 
 \  “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: Reply to author, reply to list, reply to all

2015-09-09 Thread Ben Finney
Nick Sarbicki <nick.a.sarbi...@gmail.com> writes:

> My question then is do you reply to all (with a clean cc list but
> including an OP from outside the list) in response to a persons
> question

If the question was addressed to this forum, then answering the question
should also be addressed to this forum. So: reply to list.

> even if the question is relatively simple.

I don't think the simplicity of the question changes the above.

> For me it's appreciated so that you know someone is dealing with it.

If you're asking a question in a public discussion forum (such as this
one), then to see the ensuing dicussion you need to subscribe.

> But then it can also result in flooding your inbox.

If you don't want that, then don't have them delivered to your inbox.
You can, for example, filter messages that are part of this forum to a
separate mailbox; or you can subscribe using a non-email method such as
NNTP.

-- 
 \  “Courage is not the absence of fear, but the decision that |
  `\ something else is more important than fear.” —Ambrose Redmoon |
_o__)      |
Ben Finney

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


Re: Lesson 39 of Learning Python the Hard Way hangs

2015-09-09 Thread Ben Finney
Gary Roach <gary719_li...@verizon.net> writes:

> Python 2.7 (It's going to be a while before 2,7 goes away. There is
> just too much code out there.

The time since Python 2 got any improvements is long in the past, and it
will never get any more.

It is rapidly becoming the case that new libraries just don't support
Python 2, for the same reason.

Rather than learning the dead-end Python 2, you should be using the time
better by learning Python 3 which is actively-developed and will serve
you much longer.

-- 
 \   “Remember: every member of your ‘target audience’ also owns a |
  `\   broadcasting station. These ‘targets’ can shoot back.” —Michael |
_o__)   Rathbun to advertisers, news.admin.net-abuse.email |
Ben Finney

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


Re: Python handles globals badly.

2015-09-08 Thread Ben Finney
Mario Figueiredo <mar...@gmx.com> writes:

> Note:
> You know, it is a pointless exercise to try and downplay programming
> languages (any programming language) that has proven its worth by
> being generally adopted by the programming community. Adoption is the
> sign of a respected and well designed language.

I can think of numerous widely-adpoted languages that disprove that
assertion, by nevertheless being poorly-designed languages that are
loathed by the vast majority of programmers who use them.

On the other hand, I think there is merit in an argument that runs the
other way: the quality of languages that a community adopts are
predictive of the quality of programs that community will produce.

-- 
 \  “It's up to the masses to distribute [music] however they want |
  `\… The laws don't matter at that point. People sharing music in |
_o__)their bedrooms is the new radio.” —Neil Young, 2008-05-06 |
Ben Finney

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


Re: Python handles globals badly.

2015-09-08 Thread Ben Finney
Mario Figueiredo <mar...@gmx.com> writes:

> On 09-09-2015 02:26, Ben Finney wrote:
> > Mario Figueiredo <mar...@gmx.com> writes:
> >
> >> You know, it is a pointless exercise to try and downplay
> >> programming languages (any programming language) that has proven
> >> its worth by being generally adopted by the programming community.
> >> Adoption is the sign of a respected and well designed language.
> >
> > I can think of numerous widely-adpoted languages that disprove that
> > assertion, by nevertheless being poorly-designed languages that are
> > loathed by the vast majority of programmers who use them.
>
> I'll have to agree to an extent. And you did remind me of PHP. So
> there's that.
>
> But in a way PHP served an important purpose in its time.

Important, yes.

> In any case, it stands that, unless a programming language is so
> ruined by bad design choices it is unusable, there is some kind of
> merit to its ability to solve computational problems.

That's a *very much* lower bar than your earlier claim I responded to:
that “[widespread] adoption is the sign of a respected and well designed
language”.

> I can't stand Java. I just don't think calling it a mistake. It's
> worth has been proven by its level of adoption and by the usable
> software that has been made with it. Javascript/ECMAScript is
> criticized by so many and yet there's no denying of its importance.

You're making the case for importance, and capability to implement
programs that solve problems.

Maybe it's true, but it's irrelevant to the earlier point. It is quite
separate from the language being well designed, and it is quite separate
from the language being respectable. Many languages — some of which
you've named — are poorly-designed, are not deserving of respect,
despite being widely-adopted.

> Even today we struggle to find a better alternative to client-side
> scripting. Python is criticized by so many. And yet I don't think
> calling on Python developers as an inferior breed of programmers.

Glad to know that :-)

-- 
 \ “I have the simplest tastes. I am always satisfied with the |
  `\           best.” —Oscar Wilde |
_o__)  |
Ben Finney

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


Re: Why Python is not both an interpreter and a compiler?

2015-08-31 Thread Ben Finney
Mahan Marwat <mahanmar...@gmail.com> writes:

> > Python programs *could* easily be compiled the same way, but it generally  
> > hasn't been considered all that useful.
>
> If it hasn't been considered all that useful, then why the tools like
> cx_freeze, pytoexe are doing very hard!

Thay don't compile to machine code for the host CPU. That's the step
that “compiled the same way” refers to above, as not having been
considered all that useful.

What those tools do – compile to Python virtual machine code, and then
bundle that machine code with the virtual machine into a single
executable file – is quite useful.
-- 
 \“Some people, when confronted with a problem, think ‘I know, |
  `\   I'll use regular expressions’. Now they have two problems.” |
_o__)   —Jamie Zawinski, in alt.religion.emacs |
Ben Finney

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


Re: Hi am new to python

2015-08-31 Thread Ben Finney
Chubasco Diranga <alphar...@gmail.com> writes:

> Can anyone please help me with the following please?

Welcome!

Is this a homework assignment? It's okay to ask for help with those, but
we're not going to do the work for you.

> My question is in a while loop; how do l sum all the numbers in the
> given list (list_a)?

There is a built-in function to do that. Have you completed the Python
tutorial <URL:https://docs.python.org/3/tutorial/>?

You may also want to participate in the ‘tutor’ forum for Python
<URL:https://mail.python.org/mailman/listinfo/tutor> which is
specialised to help beginners in Python.

-- 
 \  “Reichel's Law: A body on vacation tends to remain on vacation |
  `\unless acted upon by an outside force.” —Carol Reichel |
_o__)          |
Ben Finney

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


Re: Why Python is not both an interpreter and a compiler?

2015-08-31 Thread Ben Finney
Mahan Marwat <mahanmar...@gmail.com> writes:

> What I know about an interpreter and a compiler is: they both convert
> source code to machine code

Yes, Python implementations always compile the source code to machine
code. The target machine for the Python compiler, though, is a virtual
machine which then gets emulated by a Python runtime interpreter.

You can prove this by doing *only* the compile step, and later do
*only* the interpret step::

$ python -m compileall foo.py
Compiling foo.py ...

$ python foo.pyc
Hello, world!

So anything which is going to run your Python source code first needs
that source code to be compiled to machine code, and then later use an
interpreter to run that machine code.

That's true of pretty much every programming language today: To run it,
the source code is first compiled to a machine code, which is then
interpreted at run-time by some 

You might want to target some other machine code; ultimately, you might
want to the machine code of the CPU you intend to run the program. That
is a special case, though, and is by far not the only case of compiling
code.

> and the only difference is, an interpreter convert it, line by line
> while compiler convert the whole source file.

Hmm, by that definition, there are almost no language interpreters in
use today for running a program – not Python, not Ruby, not JavaScript,
not Perl – that meets your definition. They all need a compiler first to
produce machine code from the source code file.

> Now if we compile a C source file on C compiler, it will produce a
> small executable file. But if we compile (freeze) a Python source file
> on Python interpreter (using cx_freeze), it will produce a big
> executable file.

Yes, that's because the C language is low-level enough that a compiler
can target directly the host CPU's machine code. A Python program,
though, is written in a dynamic language, which is compiled to a virtual
machine code, which needs the Python virtual machine as well to
interpret that machine code.

> Now the thing is C compiler does not embed a C compiler inside our
> program, while the Python interpreter (cx_freeze, pytoexe) embed
> Python interpreter inside our program, what is the reason?

Because Python is a dynamic language. A great many facts about the
run-time state are deferred to be figured out at run-time, so can't be
decided at compile time. The resulting machine code assumes a very
powerful, dynamic machine language, which is not the same as the host
CPU's machine language.

> Cant we program a language, which is both interpreted and compiled?

I hope you see now that Python is both interpreted and compiled, by
necessity.

What you seem to want is a Python compiler that targets the host CPU;
but your target host CPU can't execute the dynamic runtime that Python
machine code needs.

In other words: The very dynamic nature that makes Python so expressive,
succinct, and efficient to write, makes it that much more distant from
the extremely low-level machine operations of the host CPU. That power
comes at the cost of a level of abstraction, in the Python virtual
machine interpreter.

-- 
 \   “Pray, v. To ask that the laws of the universe be annulled in |
  `\ behalf of a single petitioner confessedly unworthy.” —Ambrose |
_o__)   Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney

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


[RELEASE] ‘python-daemon’ version 2.0.6 released

2015-08-30 Thread Ben Finney
Howdy all,

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

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

Starting with this version, the uploads to PyPI are signed with my
GnuPG key, so the downloaded file can be automatically verified.


Significant changes since the previous version
==

This is a bug fix release, addressing this bug:

* Use current Python concept of “basestring” to test for an
  attribute name.

  This addresses a bug in Python 2 where specifying a signal handler
  by name would fail if the specified name was type ‘str’.

The Trove classifiers now also declare the “Development Status” to be
“Production/Stable”.


What is the ‘python-daemon’ library?


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

-- 
 \  “One time I went to a drive-in in a cab. The movie cost me |
  `\  ninety-five dollars.” —Steven Wright |
_o__)  |
Ben Finney b...@benfinney.id.au
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-29 Thread Ben Finney
kbtyo ahlusar.ahluwa...@gmail.com writes:

 I am using Jupyter Notebook and Python 3.4.

Thank you for saying so! It is not always required, but when it matters,
this information is important to state up front.

 I have a data structure in the format, (type list):

 [{'AccountNumber': N,
 'Amount': '0',
  'Answer': '12:00:00 PM',
   'ID': None,
   'Type': 'WriteLetters',
   'Amount': '10',
   {'AccountNumber': Y,
   'Amount': '0',
   'Answer': ' 12:00:00 PM',   
'ID': None,
   'Type': 'Transfer',
   'Amount': '2'}]

 The end goal is to write this out to CSV.

So that assumes that *every* item will be a mapping with all the same
keys. CSV is limited to a sequence of “records” which all have the same
fields in the same order.

 The list comprehension data is to maintain the integrity of the
 column headers and the values for each new instance of the data
 structure (where the keys in the dictionary are the headers and values
 - row instances). The keys in this specific data structure are meant
 to check if there is a value instance, and if there is not - place an
 ''.


[…]
 for row in results:
 data = [row.get(index, '') for index in results]

The ‘for’ statement iterates over ‘results’, getting an item each time.
The name ‘row’ is bound to each item in turn.

Then, each time through the ‘for’ loop, you iterate *again* over
‘results’. The name ‘index’ is bound to each item.

You then attempt to use the dict (each item from ‘results’ is itself a
dict) as a key into that same dict. A dict is not a valid key; it is not
a “hashable type” i.e. a type with a fixed value, that can produce a
hash of the value).

So you're getting dicts and attempting to use those dicts as keys into
dicts. That will give the error “TypeError: unhashable type: 'dict'”.

I think what you want is not items from the original sequence, but the
keys from the mapping::

for input_record in results:
output_record = [input_record.get(key, ) for key in input_record]

But you're then throwing away the constructed list, since you do nothing
with it before the end of the loop.

 writer.writerow(data)

This statement occurs only *after* all the items from ‘results’ have
been iterated. You will only have the most recent constructed row.

Perhaps you want::

for input_record in results:
output_record = [input_record.get(key, ) for key in input_record]
writer.writerow(output_record)

-- 
 \   “An idea isn't responsible for the people who believe in it.” |
  `\  —Donald Robert Perry Marquis |
_o__)  |
Ben Finney

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


Re: OFF-TOPIC Ben's sig monster quote [was Re: Parametrized Unit Tests]

2015-08-28 Thread Ben Finney
Steven D'Aprano st...@pearwood.info writes:

 With the greatest of respect to Chomsky, I think he is simply wrong
 about Hitler. Hitler actually believed that war was good for the
 national character, and indeed good for the soul, and that long
 periods of peace would enfeeble a nation and make it decadent and
 effete.

I think the beliefs of Adolf Hitler have been interpreted in a great
many ways by many people, and support for many contradictory positions
can be found in his writings and actions.

Hitler certainly made *offers* of peace several times during the Third
Reich. Those may well have been insincere, but he intended at least some
of his own citizens to be convinced by them.

So I interpret Chomsky's meaning as being that any demagogue can, and
all popular despots do, claim they have all manner of virtuous goals;
therefore we must, to understand their intent, ask anyone speaking of
such virtuous goals what exactly is meant by their pleasing words.

Regardless: I have found that aphorism to be overly flippant and
obscure, I will take this as an opportunity to cull it from my database.

 Many people over the ages have thought that if only war was more
 terrible, we would stop making it. Alas, that appears to be false: no
 matter how terrible war is, there is always someone who thinks that it
 is better than peace.

Those who benefit from a continuance of war have tended to exert
significant effort to reduce the awfulness of war for their own,
non-combatant, civilians: either by making war at a greater remove (the
latest iteration being remote-piloted drone attacks), or by ensuring
civilians don't get to see reports of the awfulness of war.

So the mere fact that we continue to make war doesn't argue against the
hypothesis, because war is still not particularly awful to those that
approve and fund it.

Nonetheless, I also disagree with the hypothesis. I disagree on the
ground that the awfulness of war is determined less by some external
“awfulness of war” parameter, but in large part by the activities of
those who plan it and engage in it. They get the war they create.

-- 
 \ “Capitalism is the astounding belief that the most wickedest of |
  `\men will do the most wickedest of things for the greatest good |
_o__)   of everyone.” —John Maynard Keynes |
Ben Finney

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


Re: Casting to a number (both int and float)?

2015-08-27 Thread Ben Finney
Victor Hooi victorh...@gmail.com writes:

 Many of the fields are meant to be numerical, however, some fields are
 wrapped in a floatApprox dict, which messed with my parsing.

The examples you give of ‘floatApprox’ are not dicts, so I'm not sure
quite what that means.

 For example:

 {
 hostname: example.com,
 version: 3.0.5,
 pid: {
 floatApprox: 18403
 }
 network: {
 bytesIn: 123123,
 bytesOut: {
 floatApprox: 213123123
 }
 }

 The floatApprox wrapping appears to happen sporadically in the input.

What do you mean by “wrapping”?

Can you show exactly what output values you would expect for these
example inputs?

 However, this relies on casting to int, which will only work for ints
 - for some fields, they may actually be floats, and I'd like to
 preserve that if possible.

(A terminology question: Note that “cast to int” isn't something that
happens in Python. You never “cast” an object as a different type, the
object is exactly what type it is and no other.

The example code you showed is not casting, but creating. Calling the
‘int’ type makes a new object of that type. Python doesn't have “cast”
as a concept.)

The question that needs to be answered is, how do you know what values
are “actually” floats?

In JSON there is no distinction at all, the only numeric type is
‘float’. What information is there in the input that can be used to know
which values should result in an ‘int’ instance, versus values that
should result in a ‘float’ instance?

-- 
 \ “I'm a great lover, I'll bet.” —Emo Philips |
  `\   |
_o__)  |
Ben Finney

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


Re: Parametrized Unit Tests

2015-08-27 Thread Ben Finney
rambius rambiusparkisan...@gmail.com writes:

 Hello,

 петък, 21 август 2015 г., 21:43:19 UTC-4, Ben Finney написа:
  The ‘testscenarios’ library is one way to have a set of scenarios
  applied at run-time to produce tests across all combinations
  URL:https://pypi.python.org/pypi/testscenarios/.

 testscenarios worked for me. Thank you for your recommendation.

You're welcome! You may be interested in the ‘testing-in-python’ forum
URL:http://lists.idyll.org/listinfo/testing-in-python to discuss other
aspects of writing test cases in Python.

-- 
 \“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


Please don't make unfounded legalistic demands (was: [a, b, c, d] = 1, 2, 3, 4)

2015-08-26 Thread Ben Finney
Jean-Michel Pichavant jeanmic...@sequans.com writes:

 -- IMPORTANT NOTICE: 

 The contents of this email and any attachments are confidential and
 may also be privileged. If you are not the intended recipient, please
 notify the sender immediately and do not disclose the contents to any
 other person, use it for any purpose, or store or copy the information
 in any medium. Thank you.

Misleading, intimidating, hostile nonsense. If you want to participate
here, please do so from a mail system which does not make these
legalistic demands.

-- 
 \   “It's easy to play any musical instrument: all you have to do |
  `\   is touch the right key at the right time and the instrument |
_o__)will play itself.” —Johann Sebastian Bach |
Ben Finney

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


Re: Please don't make unfounded legalistic demands

2015-08-26 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 I disagree with prohibiting people encumbered by such systems from
 participating.

I have no power to prohibit people here. I do strongly request that such
threatening legalistic screeds stay away from this forum.

 On 8/26/2015 5:02 AM, Jean-Michel Pichavant wrote:
  I agree with you. Unfortunately my request for removing this
  nonsense has been denied by my employer. To the point where I'm
  restrincting myself from posting from time to time. I will probably
  restrict myself even more.

 How about instead you augment your signature with Please ignore the
 boilerplate below.

Better: Don't use that mail system to participate here, and instead post
using a mail system that doesn't add those obnoxious threats.

-- 
 \ “I went camping and borrowed a circus tent by mistake. I didn't |
  `\  notice until I got it set up. People complained because they |
_o__)   couldn't see the lake.” —Steven Wright |
Ben Finney

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


Re: required help with python code.

2015-08-25 Thread Ben Finney
Srinivas, Jostna jostna.srini...@staples.com writes:

 I am trying to write a python code to create tableau data extract
 using tableau API.

What is that? Does it have a website? Does it have its own community of
users and developers?

Your questions about Python are welcome here, and we'll help if we can.
That said, if the thing you're using has its own specific community, you
should also try the forums of that community to get more specific help.

 In the process I am facing following error.

Please don't post attachments, they don't propagate correctly across
this forum.

Instead make a Short, Self-contained, Complete, Correct Example
URL:http://sscce.org/ that we can also execute to see the behaviour.

If it's not Short, you need to contrive a short example that *only*
demonstrates the problem.

If it's not Self-contained and Complete and Correct for demonstrating
the behaviour, you need to refine it until that's the case. Otherwise we
can't see the behaviour you're seeing, which is necessary to understand
what the problem is.

 Please help me to fix. I tried a lot but couldn't get over net. Its
 critical requirement and we need your help.

We can't be held to whatever critical requirements you have; but I
sympathise with your position. Please help us help you, by making a
SSCCE that we can run to see the behaviour.

-- 
 \“Good judgement comes from experience. Experience comes from |
  `\  bad judgement.” —Frederick P. Brooks |
_o__)  |
Ben Finney

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


Re: Sometimes bottle takes a lot of time

2015-08-23 Thread Ben Finney
Johannes Bauer dfnsonfsdu...@gmx.de writes:

 You're entirely right that this kind of personal feud and immature
 mockery is inappropriate for a mailing list and you're also right that
 it does create a toxic atmosphere. Since Python is the lanauge I'm
 most passionate about a detrimental effect on the Python community is
 something that is surely the exact opposite of what I want.
[…]

 I'll follow your advice and thank you for your honest words.

Thank you for publicly acknowledging this, and for taking responsibility
for positive change. This is essential to keeping our community healthy.

-- 
 \“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: Parametrized Unit Tests

2015-08-21 Thread Ben Finney
rambius rambiusparkisan...@gmail.com writes:

 I am running one and the same unit tests that test some web
 application. I would like to execute them against different servers
 that may host different instances of the application.

Those aren't unit tests, then. A unit test, by definition, tests a small
unit of code; usually one true-or-false assertion about one function
call.

What you describe sounds more like integration tests or feature tests or
acceptance tests; something where large parts of the code base are all
exercised at once.

 Is there a better a way to pass the server, the user and the password
 to the test without resolving to global variables?

The ‘testscenarios’ library is one way to have a set of scenarios
applied at run-time to produce tests across all combinations
URL:https://pypi.python.org/pypi/testscenarios/.

 Although I developed these tests as unit tests they are more of
 integration tests. Is there an integration testing framework that
 supports a more convenient passing of test parameters / data?

You may want to look at behaviour-driven testing, e.g. using Behave
URL:https://pypi.python.org/pypi/behave/.

Another resource to use is the ‘testing-in-python’ forum
URL:http://lists.idyll.org/listinfo/testing-in-python where there is
more focussed discussion on testing in Python.

-- 
 \   “Repetition leads to boredom, boredom to horrifying mistakes, |
  `\   horrifying mistakes to God-I-wish-I-was-still-bored, and it |
_o__)  goes downhill from there.” —Will Larson, 2008-11-04 |
Ben Finney

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


Re: AttributeError

2015-08-15 Thread Ben Finney
Ltc Hotspot ltc.hots...@gmail.com writes:

 So calling people stupid and ignorant on the internet makes you sexual
 arousal and to masturbate with yourself

With that, you have worn out your welcome here. Please don't post here
again until you can refrain from puerile demeaning insults.

-- 
 \ “Alternative explanations are always welcome in science, if |
  `\   they are better and explain more. Alternative explanations that |
_o__) explain nothing are not welcome.” —Victor J. Stenger, 2001-11-05 |
Ben Finney

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


Re: Ensure unwanted names removed in class definition

2015-08-13 Thread Ben Finney
Peter Otten __pete...@web.de writes:

 Ben Finney wrote:

  Peter Otten __pete...@web.de writes:
  
  That's an unexpected inconsistency between list comprehensions
  versus generator expressions, then. Is that documented explicitly in
  the Python 2 documentation?

 https://docs.python.org/2.4/whatsnew/node4.html

Or 
URL:https://docs.python.org/2/whatsnew/2.4.html#pep-289-generator-expressions.

Also in the PEP that introduces generator expressions, PEP 289:

List comprehensions also leak their loop variable into the
surrounding scope. This will also change in Python 3.0, so that the
semantic definition of a list comprehension in Python 3.0 will be
equivalent to list(generator expression).

URL:https://www.python.org/dev/peps/pep-0289/#the-details

Thanks for seeking the answer. Can you describe an improvement to
URL:https://docs.python.org/2/reference/expressions.html#list-displays
that makes clear this unexpected, deprecated behaviour which is only in
Python 2?

-- 
 \ “What is needed is not the will to believe but the will to find |
  `\   out, which is the exact opposite.” —Bertrand Russell, _Free |
_o__)   Thought and Official Propaganda_, 1928 |
Ben Finney

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


Re: Mock object but also assert method calls?

2015-08-13 Thread Ben Finney
Thomas Lehmann via Python-list python-list@python.org writes:

 How about asserting that test2 of class Bar is called?

It is unusual to call class methods; do you mean a method on an
instance?

You will make a mock instance of the class, or a mock of the class; and
you'll need to know which it is.

 Of course I can do a patch for a concrete method but I was looking for
 something like:

 mocked_object.assert_method_called_with(name=test2, hello)

The ‘mock’ library defaults to providing ‘MagicMock’, which is “magic”
in the sense that it automatically provides any attribute you request,
and those attributes are themselves also MagicMocks::

import unittest.mock

def test_spam_calls_foo_bar():
 Should call the `spam` method on the specified `Foo` instance. 
mock_foo = unittest.mock.MagicMock(system_under_test.Foo)
system_under_test.spam(mock_foo)
mock_foo.spam.assert_called_with(hello)

 If find following totally different to the normal API which
 is provided by the mock library:

 assert call().test2(hello) in mocked_objects.mock_calls

The ‘assert’ statement is a crude tool, which knows little about the
intent of your assertion. You should be instead using the specialised
methods from ‘unittest.TestCase’ and the methods on the mock objects
themselves.

-- 
 \   “It is the mark of an educated mind to be able to entertain a |
  `\ thought without accepting it.” —Aristotle |
_o__)  |
Ben Finney

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


Re: Ensure unwanted names removed in class definition

2015-08-12 Thread Ben Finney
MRAB pyt...@mrabarnett.plus.com writes:

 Have you thought about catching the NameError?

I had not, but that is obvious now you say it. Thanks.

Where there isn't a more elegant solution, I'll use that. It might not
be elegant, but it's at least clear and expressive of the intent.


Jussi Piitulainen e...@kun.ei.invalid writes:

 Make them an implementation detail:

 plumage = [
 (__foo__, __bar__) for (__foo__, __bar__) in feathers.items()
 if __bar__ == beautiful ]

That still makes the name persist, so doesn't meet the requirements. It
also commits the further mistake of using a ‘__dunder__’ name style for
something that *isn't* a Python magic attribute.

Thanks for the attempt :-)

-- 
 \ “Teeth extracted by the latest Methodists.” dentist |
  `\  advertisement, Hong Kong |
_o__)  |
Ben Finney

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


Re: Ensure unwanted names removed in class definition

2015-08-12 Thread Ben Finney
Peter Otten __pete...@web.de writes:

 I would probably use a generator expression. These don't leak names:

That's an unexpected inconsistency between list comprehensions versus
generator expressions, then. Is that documented explicitly in the Python
2 documentation?

 Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
 [GCC 4.8.2] on linux2
 Type help, copyright, credits or license for more information.
  class Parrot:
 ... a = [per for per in abc]
 ... b = list(trans for trans in def)
 ... 
  Parrot.per
 'c'
  Parrot.trans
 Traceback (most recent call last):
   File stdin, line 1, in module
 AttributeError: class Parrot has no attribute 'trans'

We have a winner! That's elegant, expressive, and has the right
behaviour on both Python 2 and Python 3.

-- 
 \ “I turned to speak to God/About the world's despair; But to |
  `\   make bad matters worse/I found God wasn't there.” —Robert Frost |
_o__)  |
Ben Finney

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


Ensure unwanted names removed in class definition

2015-08-12 Thread Ben Finney
How can I ensure incidental names don't end up in the class definition,
with code that works on both Python 2 and Python 3?

With the following class definition, the incidental names `foo` and
`bar`, only needed for the list comprehension, remain in the `Parrot`
namespace::

__metaclass__ = object

class Parrot:
 A parrot with beautiful plumage. 

plumage = [
(foo, bar) for (foo, bar) in feathers.items()
if bar == beautiful]

assert hasattr(Parrot, 'plumage')  # ← okay, has the wanted name
assert not hasattr(Parrot, 'foo')  # ← FAILS, has an unwanted name
assert not hasattr(Parrot, 'bar')  # ← FAILS, has an unwanted name

So I can remove those names after using them::

__metaclass__ = object

class Parrot:
 A parrot with beautiful plumage. 

plumage = [
(foo, bar) for (foo, bar) in feathers.items()
if bar == beautiful]
del foo, bar

assert hasattr(Parrot, 'plumage')  # ← okay, has the wanted name
assert not hasattr(Parrot, 'foo')  # ← okay, no unwanted name
assert not hasattr(Parrot, 'bar')  # ← okay, no unwanted name

But that fails on Python 3, since the names *don't* persist from the
list comprehension:

__metaclass__ = object

class Parrot:
 A parrot with beautiful plumage. 

plumage = [
(foo, bar) for (foo, bar) in feathers.items()
if bar == beautiful]
del foo, bar  # ← FAILS, “NameError: name 'foo' is not defined”

How can I write the class definition with the list comprehension and
*not* keep the incidental names — in code that will run correctly on
both Python 2 and Python 3?

-- 
 \   “Pinky, are you pondering what I'm pondering?” “Well, I think |
  `\   so, but *where* do you stick the feather and call it macaroni?” |
_o__)   —_Pinky and The Brain_ |
Ben Finney

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


Re: Linux users: please run gui tests

2015-08-06 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 I would appreciate it if some people could run the linux version of
 py -3.4 -m test -ugui test_tk test_ttk_guionly test_idle
 (or 3.5).  I guess this means 'python3 for the executable.

Could you verify exactly what is the command to run? I'd hate for a
bunch of commands to be run and reported that don't actually give you
the information you need.

-- 
 \  “It is clear that thought is not free if the profession of |
  `\   certain opinions makes it impossible to earn a living.” |
_o__)  —Bertrand Russell, _Free Thought and Official Propaganda_, 1928 |
Ben Finney

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


Test doubles for Python standard library HTTP classes

2015-08-06 Thread Ben Finney
Howdy all,

What standard Python library is there to make test doubles of
‘httplib.HTTPConnection’ and ‘urllib2.HTTPBasicAuthHandler’ and so on?

I have a code base (Python 2 code) which performs HTTP sessions using
the various HTTP-level classes in the standard library.

Testing this code will be made much easier if I can create numerous test
doubles[0] with pre-determined behaviour and instrumentation for later
inspection, to allow the functions I'm testing to interact with those
doubles instead of the real thing.

There are some libraries that provide a much higher-level API, but I
need to provide double behaviour at the level this code expects, i.e. at
the level of the API provided by ‘httplib’ and ‘urllib2’ classes.

What standard code libraries provide classes which make it easy to
double the behaviour of ‘httplib’ classes and ‘urllib2’ classes, etc.
for test cases?


[0] Test double URL:http://xunitpatterns.com/Test%20Double.html is a
more general term covering all of stubs, fakes, spies, mocks, etc. to
double specifically as a fixture in a test case.

-- 
 \  “The most merciful thing in the world… is the inability of the |
  `\human mind to correlate all its contents.” —Howard Philips |
_o__)Lovecraft |
Ben Finney

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


Re: Who uses IDLE -- please answer if you ever do, know, or teach

2015-08-05 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 Private answers are welcome. They will be deleted as soon as they are
 tallied (without names).

Are you also expecting questionnaire answers in this forum? I suspect it
will become a free-ranging discussion; hopefully you're prepared to pick
through and collect the responses if so.

-- 
 \   “The Stones, I love the Stones; I can't believe they're still |
  `\  doing it after all these years. I watch them whenever I can: |
_o__)Fred, Barney, ...” —Steven Wright |
Ben Finney

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


Re: Most Pythonic way to store (small) configuration

2015-08-04 Thread Ben Finney
marco.naw...@colosso.nl writes:

 Why not use Python files itself as configuration files?

Because configuration data will be user-editable. (If it's not
user-editable, that is itself a poor design choice.)

If you allow executable code to be user-edited, that opens your program
to arbitrary injection of executable code. Your program becomes wide
open for security exploits, whether through malicious or accidental
bugs, and simple human error can lead to arbitrary-scope damage to the
user's system.

On another dimension, configuration files specifying the behaviour of
the system are much more useful if their format is easily parsed and
re-worked by tools the user chooses.

Your program should not be the only tool (and Python should not be the
only language) that can read and/or write the configuration data with
straightfoward data manipulation.

So a complex full-blown programming language like Python is a poor
choice for configuration data for that reason, too.

Much better to choose a tightly-defined, limited-scope configuration
data format that you can be confident any user cannot employ to run
arbitrary code.

-- 
 \ “For myself, I am an optimist — it does not seem to be much use |
  `\  being anything else.” —Winston Churchill, 1954-11-09 |
_o__)  |
Ben Finney

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


Re: Most Pythonic way to store (small) configuration

2015-08-02 Thread Ben Finney
Cecil Westerhof ce...@decebal.nl writes:

 Because of this I think a human readable file would be best.

I agree with that criterion; in the absence of compelling reasons
otherwise, human-readable and -editable text is a good default.

 Personally I do not find XML very readable. So a conf or json file
 looks the most promising to me. And I would have a slight preference
 for a json file.

XML and JSON should both be considered data serialisation formats only.

JSON is human-readable to an extent, but it is quite brittle, and there
are no comments permitted in the syntax.

So, both XML and JSON should be considered write-only, and produced only
for consumption by a computer; they are a poor choice for presenting to
a human.

The “INI” format as handled by the Python ‘configparser’ module is what
I would recommend for a simple flat configuration file. It is more
intuitive to edit, and has a conventional commenting format.

If it were more complex I might recommend YAML, which is a very
widespread, flexible hierarchical format, that still allows fairly
natural editing and commenting. Its main downside (as opposed to INI
format) is that the Python standard library does not support it.

-- 
 \ “Simplicity and elegance are unpopular because they require |
  `\   hard work and discipline to achieve and education to be |
_o__)appreciated.” —Edsger W. Dijkstra |
Ben Finney

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


Re: Most Pythonic way to store (small) configuration

2015-08-02 Thread Ben Finney
Cecil Westerhof ce...@decebal.nl writes:

 On Sunday  2 Aug 2015 13:54 CEST, Ben Finney wrote:

  So, both XML and JSON should be considered write-only, and produced
  only for consumption by a computer; they are a poor choice for
  presenting to a human.

 Well, I would use nested data. (A file will have extra fields besides
 the name.)

In that case, your needs are more complex than “store some simple
configuration”. You need a human-editable format (so, not JSON and not
XML) which handles structured data well, and is widely implemented.

For nested configuration data, you would be better served by YAML
URL:https://en.wikipedia.org/wiki/YAML, and the PyYAML library
URL:https://pypi.python.org/pypi/PyYAML/ is the one to use.

-- 
 \學而不思則罔,思而不學則殆。 |
  `\(To study and not think is a waste. To think and not study |
_o__) is dangerous.) —孔夫子 Confucius (551 BCE – 479 BCE) |
Ben Finney

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


Re: debugging during package development

2015-07-31 Thread Ben Finney
Seb splu...@gmail.com writes:

 With lots of debugging to do, the last thing I'd want is to worry
 about the search path.

Short answer: you need ‘python3 ./setup.py develop’.

Medium-length answer: you need to add some infrastructure to get your
project to the point where you can run ‘python3 ./setup.py develop’.

Longer answer below.

 So I've been searching for better ways to work,
 but I can't seem hit the right keywords and come with all sorts of
 tangentially related stuff.

The Python module search path is an abstraction, with only a partial
relationship to the location of modules files in the filesystem.

The expectation is that a module (or a package of modules) will be
*installed* to a location already in the module search path (with
‘python ./setup.py .

This allows for cross-platform package management, especially on systems
that don't have a working OS package manager. The trouble is that it
does cause a significant learning curve for Python programmers, and is
an ongoing sore point of Python.

 I'm sure there must be some tool that sets up the development
 environment when the package source is not on `sys.path`. Any advice
 on this topic would be appreciated.

What you need is to tell Distutils which Python modules form your
project URL:https://docs.python.org/3/library/distutils.html.

Once you've got a working ‘setup.py’ for your project, run ‘python3
./setup.py develop’ to allow your packages to be run in-place while you
develop them.

-- 
 \“I think it would be a good idea.” —Mohandas K. Gandhi (when |
  `\asked what he thought of Western civilization) |
_o__)  |
Ben Finney

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


Re: Gmail eats Python

2015-07-25 Thread Ben Finney
Laura Creighton l...@openend.se writes:

 So it was my fault by sending him a reply with  to the far left.

No, it was Google Mail's failt for messing with the content of the
message.

Never forget that these services are meant to serve us. When they fail
to do so because they're violating internet standards, it's not our
fault.

 Thank you Zach, I had no idea. I will change my behaviour.

Google can't force you to change your behaviour; they only have that
power if you give it to them.

-- 
 \   “People come up to me and say, ‘Emo, do people really come up |
  `\to you?’” —Emo Philips |
_o__)  |
Ben Finney

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


Re: Gmail eats Python

2015-07-25 Thread Ben Finney
Zachary Ware zachary.ware+pyl...@gmail.com writes:

 If the gmail app on my phone had the option, I'd only send the plain
 text.

Isn't that a good reason to avoid composing email messages on a program
that lacks the correct capability?

If the GMail app lacks the ability to send plain text, there are better
alternatives (including avoiding GMail entirely).

-- 
 \ “If I had known what it would be like to have it all... I might |
  `\ have been willing to settle for less.” —Jane Wagner, via Lily |
_o__)   Tomlin |
Ben Finney

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


Re: unexpected output while using list(and nested dictionary)

2015-07-23 Thread Ben Finney
max scalf oracle.bl...@gmail.com writes:

 I am sorry for doing what i did (asking question in Stackoverflow and
 pasting the link here).

No harm done. The rule isn't special to this forum; it's best to
minimise the fragility of your message by not relying on many sites all
staying the same over a long time.

 Do you guys have any suggestion as to what to use if the code is lone,
 as the formatting gets lost in an email...

First, always post in “plain text”; don't present program code in a
“rich text” or “HTML mail” or any other magical formatting tool.

Second, don't post long code examples. Work up a small, self-contained,
complete compilable example URL:http://sscce.org/ so that there isn't
any extraneous material, only the code that demonstrates the behaviour
that confuses you.

The reason to do that for presentation here is that you want the code to
be short enough that people will find it worth their time to volunteer
to help you.

But an important side benefit is: in stripping the example down so that
it doesn't contain anything not needed to demonstrate the behaviour, you
may end up understanding it well enough to solve the problem yourself —
which is a valuable skill and very much worth your while :-)

-- 
 \   “If you always want the latest and greatest, then you have to |
  `\  buy a new iPod at least once a year.” —Steve Jobs, MSNBC |
_o__) interview 2006-05-25 |
Ben Finney

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


Re: Integers with leading zeroes

2015-07-22 Thread Ben Finney
Laura Creighton l...@openend.se writes:

 The biggest use I have for decimal numbers that begin with 0 is in
 credit card numbers, account numbers and the like where the first
 check you do is 'does this thing have the correct number of digits'.

The following are examples of types from the real world that people
think of, and casually discuss, as “numbers”.

* Postal code
* Credit card number
* Telephone number
* Car registration plate number
* Personal Identification Number (PIN)

You can no doubt come up with other examples.

Despite that they are represented in text with digits, and the authority
that generates them may even use some sequence of integers, the types
should not be treated as numbers.

They are not quantities. Performing arithmetic on them (adding two
together, dividing by two, etc.) makes no sense. Representing them in a
different number base (e.g. hexadecimal) utterly changes their meaning.

And, as you've found, a leading zero makes a difference to the value. To
a computer (ignoring the legacy of octal representation), that makes
nonsense of the idea these are numbers.

So these types are not numbers and should not be treated that way in the
program.

These are, from the point of view of your computer program, opaque
tokens. They should be encoded not using a number type, but a type which
represents them as only a string of decimal digits.

Best if they're stored without spaces or punctuation; convert to and
from some format for human use if you must, but only at the input/output
borders of the program.

 So far, all the examples I've been able to find in my code -- which
 does this sort of stuff a lot -- is looking at string versions of
 decimal numbers, but I suspect there is old code out there in the
 wild which just used integers.

Maybe so, but I consider the latter kind of code to be a terrible
practice since it leads to assumptions in the code which are unfounded,
and which no human would ever make. Treat them the way a human actually
would: as an opaque tokem, a text (sequence of characters) that happen
to contain digits.

-- 
 \“Simplicity is prerequisite for reliability.” —Edsger W. |
  `\  Dijkstra |
_o__)  |
Ben Finney

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


Re: unexpected output while using list(and nested dictionary)

2015-07-22 Thread Ben Finney
max scalf oracle.bl...@gmail.com writes:

 I have posted a question on stack overflow for better readability ... but
 is intended for python list Please see question below...

Please post (as a reply to your initial post, if you like) with the full
question text in a message. Keep the discussion here in this forum
self-contained; linking to context elsewhere is less reliable across time.

-- 
 \   “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


[issue24651] Mock.assert* API is in user namespace

2015-07-21 Thread Ben Finney

Changes by Ben Finney ben+pyt...@benfinney.id.au:


--
nosy: +bignose

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



Re: Mapping, with sequence as key, wildcard and subsequence matching

2015-07-16 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 On 7/15/2015 9:51 PM, Ben Finney wrote:
  What well-defined data type exists with the following properties:
 
  * Mapping, key → value.
 
  * Each key is a sequence (e.g. `tuple`) of items such as text strings.
 
  * Items in a key may be the sentinel `ANY` value, which will match any
 value at that position.
 
  * A key may specify that it will match *only* sequences of the same
 length.
 
  * A key may specify that it will match sequences with arbitrarily many
 additional unspecified items.

 Every key should signal which of the last two alterntives holds. One
 can be a default.  The signal can be 'in-band', in the tuple key
 itself, or 'out-of-band', not in the tuple key.

Thanks. The part which puzzle me though: How do we teach the mapping
type about that matching behaviour?

-- 
 \“Without cultural sanction, most or all of our religious |
  `\  beliefs and rituals would fall into the domain of mental |
_o__) disturbance.” —John F. Schumaker |
Ben Finney

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


Re: Mapping, with sequence as key, wildcard and subsequence matching

2015-07-16 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 I'm not sure you really need a mapping type per se.

My reasons include (but I can probably think of more) testing membership
via the ‘key in mapping’ syntax.

 with the match any concept, there's actually a potential for
 ambiguities, which means you need a sequential (strictest first)
 check. In any case, it's virtually impossible to hash a tuple of
 strings such that it can match multiple targets, based only on what
 the targets do.

I'm fine with not having the keys hashed, so long as I can use the
mapping API (membership test, item retrieval by key, rejecting keys that
already match one of the items, etc.).

In other words, I'm not limiting myself to Python's ‘dict’ type, which
is why I've only been talking about a type which can be classified as a
mapping type.

 Steven's suggestion to turn this into an honest linear search is
 probably what I'd do; ultimately, a dict that can't hash its keys
 properly is going to devolve to that anyway.

Fine by me. What is the mapping API that needs to be implemented though?

I can guess, but for code I intend to release, API design should not be
a matter of guessing. I'd rather have an already-worked example of a
custom mapping type that fully implements the API used by Python's
mapping type, without having to discover it all by trial and error. Once
this is out in the wild, I don't want to discover I made a bad API
design decision.

-- 
 \   “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: Mapping, with sequence as key, wildcard and subsequence matching

2015-07-16 Thread Ben Finney
Ethan Furman et...@stoneleaf.us writes:

 On 07/15/2015 10:53 PM, Ben Finney wrote:
  Are those the ‘__contains__’, ‘__getitem__’ methods? What actually
  is the API of a mapping type, that would need to be customised for
  this application?

 The problem is that potential key matches are found by hashes

For the Python ‘dict’ type, yes. I already know that I don't want that
type, I want a custom mapping type which matches keys according to the
algorithm I specify.

So, I'm not asking “how do I make ‘dict’ do this?”. I am instead asking
“how do I implement a custom type which can duck-type for ‘dict’ but
have a different key-lookup implementation?”.

-- 
 \   “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


Re: Mapping, with sequence as key, wildcard and subsequence matching

2015-07-16 Thread Ben Finney
Zachary Ware zachary.ware+pyl...@gmail.com writes:

 On Thu, Jul 16, 2015 at 1:31 AM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  Fine by me. What is the mapping API that needs to be implemented though?

 Have a look at collections.MutableMapping.

Thank you, that's great! I hadn't realised the ‘collections’ module had
such comprehensive coverage of Python built-in type APIs.

Now to focus back on the “existing debugged implementation” part :-)

-- 
 \   “Nothing is so common as to imitate one's enemies, and to use |
  `\   their weapons.” —Voltaire, _Dictionnaire Philosophique_ |
_o__)  |
Ben Finney

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


Mapping, with sequence as key, wildcard and subsequence matching

2015-07-15 Thread Ben Finney
Howdy all,

What well-defined data type exists with the following properties:

* Mapping, key → value.

* Each key is a sequence (e.g. `tuple`) of items such as text strings.

* Items in a key may be the sentinel `ANY` value, which will match any
  value at that position.

* A key may specify that it will match *only* sequences of the same
  length.

* A key may specify that it will match sequences with arbitrarily many
  additional unspecified items.

If it matters: I'm using Python 2 to implement this.


The “match any item” type is simple enough; I'm aware of the
`unittest.mock.ANY` sentinel, and that meets my needs.

What I'm hoping to find is a general, existing, solution to the problem
of a mapping that uses keys which, in their value, encapsulate the fact
that the key does, or does not, match sequences of arbitrary length
longer than itself.

Example of what I'd like::

from unittest import mock

responses = SubsequenceMatchingType([
('foo', 'bar', 'baz'):
Simple three-argument command.,
('wibble', mock.ANY, 'wubble'):
Second argument ANY.,
('lorem', 'ipsum'):
Arbitrary trailing arguments.,
])

responses[('foo', 'bar')]  # raises KeyError
responses[('foo', 'bar', 'baz')]  # → Simple three-argument command.
responses[('foo', 'bar', 'baz', 'bork')]  # raises KeyError

responses[('wibble', 'wobble')]  # raises KeyError
responses[('wibble', 'wobble', 'wubble')]  # → Second argument ANY.
responses[('wibble', 'wobble', 'baz')]  # raises KeyError
responses[('wibble', 'wobble', 'wubble', 'baz')]  # raises KeyError

responses[('lorem',)]  # raises KeyError
responses[('lorem', 'ipsum')]  # → Arbitrary trailing arguments.
responses[('lorem', 'ipsum', 'dolor', 'sit', 'amet')]  # → Arbitrary 
trailing arguments.

So some kind of distinguishing feature needs to be added to those keys
which should match arbitrary trailing items: not ‘('foo', 'bar', 'baz')’
but ‘('lorem', 'ipsum')’.

The trouble I'm having is that the keys in the mapping, and the
candidate sequences, are simple tuples. Adding a sentinel item at the
end would make it a different sequence, and indistinguishable from
specifying an additional item at that position.

Is this a problem already solved (and implemented, and debugged!) in a
general form that I can use?

-- 
 \  “I am too firm in my consciousness of the marvelous to be ever |
  `\   fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__) Shadow-Line_ |
Ben Finney

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


Re: Mapping, with sequence as key, wildcard and subsequence matching

2015-07-15 Thread Ben Finney
Steven D'Aprano st...@pearwood.info writes:

 Sounds like a regular expression. Remember that computer science
 theoretical regular expressions don't just match strings, they can
 apply to any sequence of primitive values.

Good insight, thank you.

 In your case, you only need two special tokens, match-one and
 match-one-or-more (which may be like r'.' and r'.*').

It actually needs “one” and “zero-or-more”. Which does match your
analogous regex ‘.’ and ‘.*’ patterns.

 Otherwise, you can create your own sequence type and simple regex
 engine (you only need two meta-items, [ONE and ZERO-OR-MORE]) to
 perform equality tests.

It may have to come to that. That's not such a problem, but:

 You can't use a dict for the mapping, not unless you're smarter than
 me, due to the requirement to hash the keys.

Dang. It's the mapping that I really need to solve, I think. A mapping
that has a custom “does this candidate match any existing key” and
“return the value for this key” to defer to the matching behaviour
described above.

Are those the ‘__contains__’, ‘__getitem__’ methods? What actually is
the API of a mapping type, that would need to be customised for this
application?

-- 
 \   “If we listen only to those who are like us, we will squander |
  `\   the great opportunity before us: To live together peacefully in |
_o__)a world of unresolved differences.” —David Weinberger |
Ben Finney

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


Foo.__new__ is what species of method?

2015-07-13 Thread Ben Finney
Howdy all,

The Python reference says of a class ‘__new__’ method::

object.__new__(cls[, ...])

Called to create a new instance of class cls. __new__() is a static
method (special-cased so you need not declare it as such) that takes
the class of which an instance was requested as its first argument.

URL:https://docs.python.org/3/reference/datamodel.html#object.__new__

But a “static method” is described, elsewhere in the documentation
URL:https://docs.python.org/3/library/functions.html#staticmethod, as
“A static method does not receive an implicit first argument”.

What the ‘__new__’ documentation describes would match a “class method”
URL:https://docs.python.org/3/library/functions.html#classmethod
“A class method receives the class as implicit first argument”.

I suspect this a bug in the reference documentation for ‘__new__’, and
it should instead say “__new__ is a class method …”. Am I wrong?

-- 
 \“Cooles  Heates: If you want just condition of warm in your |
  `\room, please control yourself.” —air conditioner instructions, |
_o__)Japan |
Ben Finney

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


Re: Foo.__new__ is what species of method?

2015-07-13 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 py class Spam(object):
 ... def __new__(cls):
 ... print cls
 ... 
 py Spam.__new__()  # implicit first arg?
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: __new__() takes exactly 1 argument (0 given)

Thanks, I'm glad I checked before filing a bug report.

Hopefully I'll remember that clear test, when I need to remember which
species it is :-)

-- 
 \   “Instead of having ‘answers’ on a math test, they should just |
  `\   call them ‘impressions’, and if you got a different |
_o__)   ‘impression’, so what, can't we all be brothers?” —Jack Handey |
Ben Finney

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


Re: understanding why there is no setup.py uninstall

2015-07-06 Thread Ben Finney
c.bu...@posteo.jp writes:

 I want to understand the design concept behind it.
 Why isn't there no uninstall routine implemented?

What form of answer are you looking for?

Will you be disappointed if the answer entails (as I fear it must)
“because no-one put in the sustained effort to make it work”?

If you merely want to know the sequence of events that led to the
situation, you'll need to go digging through the history of Distutils.

If, on the other hand, you are feeling wronged and want someone to take
responsibility and justify their actions:

 For me as a user and admin it feels quite dirty when installing
 something with the setup.py but then not being able to remove it clean
 like I would do it with packages of my system-package-manager (e.g.
 with apt-get on a debianized system).

… then I think you'll find it more productive to realise we *do* have a
better system now.

Part of the better system is that we have the Python Packaging Authority
URL:http://pypa.io/ which didn't exist when Distutils was designed.
Read the documents there and I hope you'll be glad at the improvement!

More specifically, an important part of the better system is that we now
have Pip URL:https://pypi.python.org/pypi/pip/, which is the PyPA
recommended tool for end-users to install *and* uninstall Python packages.

Hopefully by the time you're done with that, you won't need anyone to
justify their actions to you any more :-)

-- 
 \  “I used to be an airline pilot. I got fired because I kept |
  `\   locking the keys in the plane. They caught me on an 80 foot |
_o__)stepladder with a coathanger.” —Steven Wright |
Ben Finney

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


Re: Looking up a dictionary _key_ by key?

2015-06-23 Thread Ben Finney
Dan Stromberg drsali...@gmail.com writes:

 Is there a way of getting the key used by the dictionary, short of
 storing a reference to it in the value, or using a second dictionary?

The dictionary knows its keys and can provide them on request. Call the
‘dict.keys’ method to get them as a collection.

-- 
 \ “Capitalism has destroyed our belief in any effective power but |
  `\  that of self interest backed by force.” —George Bernard Shaw |
_o__)  |
Ben Finney

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


Re: Looking up a dictionary _key_ by key?

2015-06-23 Thread Ben Finney
Dan Stromberg drsali...@gmail.com writes:

 On Tue, Jun 23, 2015 at 5:33 PM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  Dan Stromberg drsali...@gmail.com writes:
 
  Is there a way of getting the key used by the dictionary, short of
  storing a reference to it in the value, or using a second dictionary?
 
  The dictionary knows its keys and can provide them on request. Call the
  ‘dict.keys’ method to get them as a collection.

 So it appears:

 $ ./pythons --command 'd={1:2, 2:4, 3:8}; print(d.keys())'
[…]
 /usr/local/cpython-3.0/bin/python good dict_keys object at 0x8514fa4
 /usr/local/cpython-3.1/bin/python good dict_keys([1, 2, 3])
 /usr/local/cpython-3.2/bin/python good dict_keys([1, 2, 3])
 /usr/local/cpython-3.3/bin/python good dict_keys([1, 2, 3])
 /usr/local/cpython-3.4/bin/python good dict_keys([1, 2, 3])
 /usr/local/cpython-3.5/bin/python good dict_keys([1, 2, 3])
 /usr/local/pypy3-2.4.0/bin/pypy3 good dict_keys([1, 2, 3])

Note that none of these (from Python 3) are lists; I don't promise a
list, only a collection :-)

 Would I have to do an O(n) search to find my key?

If you're wanting to *locate* a particular item, you'll need to find it
using whatever comparisons the values support. You described some custom
type; the answer will depend on what that type supports for comparing
values.

What I can say at this point is: we are no longer talking about anything
special to dictionary keys. You just have a collection of values, which
you can iterate over and compare to some target.

-- 
 \   “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: instance as module

2015-06-19 Thread Ben Finney
Robin Becker ro...@reportlab.com writes:

 For the specific case of the canvas_basefontname I don't actually need
 to do anything specific since it is just a string

The configuration values should be nothing but immutable values:
strings, integers, booleans. Possibly collections of those.

You seem to be implying that some configuration values are complex
objects; that's undesirable.

You seem to be further implying that configuration is executable code;
that is *definitely* undesirable (look at the awful mess created by
making Distutils configuration an executable program).

 however, before it can be used in action support has to be provided ie
 I must register the font used.

That's fine, it is a step that should come *after* configuration is
entirely completed and the static values are known.

 I could just make the few usages of this value check for callability
 at use time, but that would scatter the problem; if one default is
 special why not all.

Indeed. The correct solution is not to make configuration executable,
but instead make it static data, read by the program as simple immutable
values.

 Effectively the defaults setup is not complex enough to allow use of
 itself; that must be a fairly common problem.

The common solution is:

* Use a non-executable configuration file format. ‘configparser’ from
  the standard library is a good option, YAML is another.

* Use the conventional precedence order for applying configuration
  values: default values, overridden by config files, overridden by
  environment variables, overridden by command-line options.

* Only after configuration using the above precedence is complete, use
  the immutable values defined to change program behaviour (e.g. create
  or modify dynamic, complex objects that respond to the config
  options).

If you've got a config file that is executable, and attempts to define
program objects, then yes you're going to get the complex mess you
describe in your initial posting of this thread.

Avoid that by migrating away from such a poor configuration format:
Switch to a ‘configparser’ format, or some other static, non-executable
data file.

 Probably the correct thing to do was always to use an object to hold
 the defaults.

Yes, a ‘configparser.ConfigParser()’ instance can store defaults which
will be over-ridden by the sequence of configuration files read.

-- 
 \   “I do not believe in forgiveness as it is preached by the |
  `\church. We do not need the forgiveness of God, but of each |
_o__)other and of ourselves.” —Robert G. Ingersoll |
Ben Finney

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


Re: Documenting a function signature

2015-06-18 Thread Ben Finney
Laura Creighton l...@openend.se writes:

 In a message of Thu, 18 Jun 2015 10:04:46 +1000, Ben Finney writes:
 Since the introduction of keyword-only arguments in Python functions,
 the question arises of how to communicate this in documentation.

 I suppose it is way too late to scream I hate keyword-only
 arguments!

It's never too late for screams, go right ahead.

If you're hoping those screams will result in the keyword-arguments not
being part of Python now and in the future; yes, I think it's too late
for that :-)

-- 
 \  “If sharing a thing in no way diminishes it, it is not rightly |
  `\  owned if it is not shared.” —Augustine of Hippo (354–430 CE) |
_o__)  |
Ben Finney

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


Documenting a function signature (was: Set a flag on the function or a global?)

2015-06-17 Thread Ben Finney
Steven D'Aprano st...@pearwood.info writes:

 The full signature is:

 edir([object [, glob=''] [, dunders=True] [, meta=False]])

 All four arguments are optional, and dunders and meta are
 keyword-only.

The official documentation seems to prefer this style::

edit(object, glob='', *, dunders=True, meta=False)

(I think that's the style, anyway.)

I like that it gets rid of square brackets; with the notation showing a
default value, that already communicates that a parameter is optional.

Since the introduction of keyword-only arguments in Python functions,
the question arises of how to communicate this in documentation.

The lone asterisk showing the separation of keyword-only arguments from
the rest is confusing to me. Not least because it is (if I understand
correctly) invalid syntax to actually have that in Python code.

What are your thoughts, dear reader, on the documentation style for
showing a Python function signature, now that we have not only default
arguments but also keyword-only arguments?

-- 
 \  “It is difficult to get a man to understand something when his |
  `\   salary depends upon his not understanding it.” —Upton Sinclair, |
_o__) 1935 |
Ben Finney

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


Re: Set a flag on the function or a global?

2015-06-15 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 On Tue, Jun 16, 2015 at 9:57 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
  I can use a flag set on the function object itself:
 
  edir.dunders = False

 For most situations, the last one is extremely surprising - attributes
 on functions aren't normally meant to be changed by outside callers,
 it always feels wrong (they belong to the function itself).

I'm surprised by your assertion. To my mind, outside callers get simple
and direct access to the attribute, whereas the code of the function
itself does not have such easy access; unlike ‘self’ for the current
instance of a class, there's no obvious name to use for referring to the
function object within the function object's own code.

In what sense do they “belong to” the function itself *more than* to
outside callers?

-- 
 \   “It's easy to play any musical instrument: all you have to do |
  `\   is touch the right key at the right time and the instrument |
_o__)will play itself.” —Johann Sebastian Bach |
Ben Finney

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


<    3   4   5   6   7   8   9   10   11   12   >