Re: Unicode humor

2013-05-10 Thread Ned Batchelder

On 5/10/2013 11:06 AM, jmfauth wrote:

On 8 mai, 15:19, Roy Smith  wrote:

Apropos to any of the myriad unicode threads that have been going on
recently:

http://xkcd.com/1209/

--


This reflects a lack of understanding of Unicode.

jmf


And this reflects a lack of a sense of humor.  :)

--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for philosophers

2013-05-11 Thread Ned Batchelder


On 5/11/2013 4:03 PM, Citizen Kant wrote:

Hi,
this could be seen as an extravagant subject but that is not my 
original purpose. I still don't know if I want to become a programmer 
or not. At this moment I'm just inspecting the environment. I'm making 
my way to Python (and OOP in general) from a philosophical perspective 
or point of view and try to set the more global definition of Python's 
core as an "entity". In order to do that, and following Wittgenstein's 
indication about that the true meaning of words doesn't reside on 
dictionaries but in the use that we make of them, the starting 
question I make to myself about Python is: which is the single and 
most basic use of Python as the entity it is? I mean, beside 
programming, what's the single and most basic result one can expect 
from "interacting" with it directly (interactive mode)? I roughly came 
to the idea that Python could be considered as an *economic mirror for 
data*, one that mainly *mirrors* the data the programmer types on its 
black surface, not exactly as the programmer originally typed it, but 
expressed in the most economic way possible. That's to say, for 
example, if one types >>>1+1 Python reflects >>>2. When data appears 
between apostrophes, then the mirror reflects, again, the same but 
expressed in the most economic way possible (that's to say without the 
apostrophes).


So, would it be legal (true) to define Python's core as an entity that 
mirrors whatever data one presents to it (or feed it with) showing 
back the most shortened expression of that data?


Don't get me wrong. I can see the big picture and the amazing things 
that programmers write on Python, it's just that my question points to 
the lowest level of it's existence.


Thanks a lot for your time.




Python is straightforward: you write instructions, and it executes 
them.  At its core, that's all it does.  Why does the core have to be 
any different than that?


--Ned.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Message passing syntax for objects | OOPv2

2013-05-12 Thread Ned Batchelder

On 5/8/2013 10:39 PM, Mark Janssen wrote:

...The field needs re-invented and re-centered.[...]

For anyone who want to be involved.  See the wikiwikiweb -- a tool
that every programmer should know and use --  and these pages:
ComputerScienceVersionTwo and ObjectOrientedRefactored.


I've never understood why people use that site: the pages end up being 
unintelligible cocktail-party noise-scapes with no hope of understanding 
who is saying what, or in response to whom.


--Ned.


Cheers!


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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-12 Thread Ned Batchelder

On 5/12/2013 7:23 PM, Mr. Joe wrote:

I seem to stumble upon a situation where "!=" operator misbehaves in
python2.x. Not sure if it's my misunderstanding or a bug in python
implementation. Here's a demo code to reproduce the behavior -
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function

class DemoClass(object):
 def __init__(self, val):
 self.val = val

 def __eq__(self, other):
 return self.val == other.val

x = DemoClass('a')
y = DemoClass('a')

print("x == y: {0}".format(x == y))
print("x != y: {0}".format(x != y))
print("not x == y: {0}".format(not x == y))
"""

In python3, the output is as expected:
"""
x == y: True
x != y: False
not x == y: False
"""


In Python 3, if __ne__ isn't defined, "!=" will call __eq__ and negate 
the result.

In python2.7.3, the output is:
"""
x == y: True
x != y: True
not x == y: False
"""
Which is not correct!!


In Python 2, "!=" only calls __ne__.  Since you don't have one defined, 
it's using the built-in object comparison, and since x and y are 
different objects, they are not equal to each other, so x != y is True.



Thanks in advance for clarifications.
Regards,
TB


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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-13 Thread Ned Batchelder


On 5/13/2013 1:26 PM, Fábio Santos wrote:



On 13 May 2013 11:04, "Alister" > wrote:

> this looks to me like an issue with operator precidence
>
> you code is evaluating as (Not x) == y
> rather than not (x == y)

I can say for sure that the precedence is as expected. I always use 
"not ... == ..." Instead of !=.





If you don't mind my asking, why do you do that?

--Ned.

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


Re: Python for philosophers

2013-05-15 Thread Ned Batchelder

On 5/11/2013 4:03 PM, Citizen Kant wrote:
Don't get me wrong. I can see the big picture and the amazing things 
that programmers write on Python, it's just that my question points to 
the lowest level of it's existence.


Sometimes a cigar is just a cigar.  Python is a tool, it does what you 
tell it.  To make an analogy, or maybe to clarify your philosophical 
view of the world, consider a hammer.  What is the "lowest level of its 
existence"?


--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: spilt question

2013-05-16 Thread Ned Batchelder

On 5/16/2013 11:00 AM, loial wrote:

I want to split a string so that I always return everything BEFORE the LAST 
underscore

HELLO_.lst # should return HELLO
HELLO_GOODBYE_.ls  # should return HELLO_GOODBYE

I have tried with rsplit but cannot get it to work.

Any help appreciated


>>> "HELLO_GOODBYE_.ls".rpartition('_')
   ('HELLO_GOODBYE', '_', '.ls')
>>> "HELLO_GOODBYE_.ls".rsplit('_', 1)
   ['HELLO_GOODBYE', '.ls']
>>> "HELLO_GOODBYE_.ls".rpartition('_')[0]
   'HELLO_GOODBYE'
>>> "HELLO_GOODBYE_.ls".rsplit('_', 1)[0]
   'HELLO_GOODBYE'


For the future, getting help works better if you show what you tried, 
and what it produced.


--Ned.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with Threading

2013-05-20 Thread Ned Batchelder

On 5/20/2013 6:09 AM, Chris Angelico wrote:

Referencing a function's own name in a default has to have one of
these interpretations:

1) It's a self-reference, which can be used to guarantee recursion
even if the name is rebound
2) It references whatever previously held that name before this def statement.


The meaning must be #2.  A def statement is nothing more than a fancy 
assignment statement.  This:


def foo(a):
return a + 1

is really just the same as:

foo = lambda a: a+1

(in fact, they compile to identical bytecode).  More complex def's don't 
have equivalent lambdas, but are still assignments to the name of the 
function.  So your "apparently recursive" print function is no more 
ambiguous "x = x + 1".  The x on the right hand side is the old value of 
x, the x on the left hand side will be the new value of x.


# Each of these updates a name
x = x + 1
def print(*args,print=print,lock=Lock(),**kwargs):
  with lock:
print(*args,**kwargs)

Of course, if you're going to use that code, a comment might be in order 
to help the next reader through the trickiness...


--Ned.

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


Re: Myth Busters: % "this old style of formatting will eventually be removed from the language"

2013-05-21 Thread Ned Batchelder

On 5/21/2013 10:26 PM, Carlos Nepomuceno wrote:

I was looking for something else and just found what I think is the place where 
I was first exposed to the myth[1]:

"Since str.format() is quite new, a lot of Python code still uses the % operator. 
However, because this old style of formatting will eventually be removed from the 
language, str.format() should generally be used."

Is this tutorial outdated or this still an issue?

[1] http://docs.python.org/2/tutorial/inputoutput.html#old-string-formatting



That tutorial is out of date.  %-formatting isn't being removed.

--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-22 Thread Ned Batchelder


On 5/21/2013 11:38 PM, Carlos Nepomuceno wrote:

From:steve+comp.lang.pyt...@pearwood.info
>Subject: Re: PEP 378: Format Specifier for Thousands Separator
>Date: Wed, 22 May 2013 03:08:54 +
>To:python-list@python.org

[...]

>>So, the only alternative to have "'%,d' % x" rendering the thousands
>>separator output would a C source code modification?

>
>That's one alternative. But the language you would be then running will
>no longer be Python.
>
>Another alternative would be to write a pre-processor that parses your
>Python source code, extracts any reference to the above, and replaces it
>with a call to the appropriate format call. But not only is that a lot of
>work for very little gain, but it's also more or less impossible to do in
>full generality. And again, what you are running will be something
>different than Python, it will be Python plus a pre-processor.
>
>
>Don't fight the language. You will lose.

Not fighting the language. In fact it's not even a language issue.
All I need is a standard library[1] improvement: "%,d"! That's all!


You have to keep in mind that 2.7 is not getting any new features, no 
matter how small they seem.  If you create a patch that implements the 
comma flag in %-formatting, it *might* go into 3.x, but it will not go 
into 2.7.


--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-22 Thread Ned Batchelder


On 5/22/2013 10:58 AM, Steven D'Aprano wrote:

On Wed, 22 May 2013 05:45:12 -0500, Skip Montanaro wrote:


I didn't mean to create a tempest in a teapot.  I was away from
comp.lang.python, python-bugs, and python-dev for a few years.  In
particular, I didn't ever see the aforementioned thread from Feb 2012.
  Had I known of that thread I would have worded the sentence which
shall not be repeated differently.

My apologies...

No problem, it's not about you specifically, it's just that some of us
fans of % formatting can be a tad sensitive about it, especially since
the idea that it has been deprecated (or soon will be deprecated, or one
day will be deprecated, and therefore code using it is bad) is relatively
widespread on the Internet.


Seems like maybe this should become a question in the Python FAQ.

--Ned.



Glad to have you back here!





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


Re: Simple algorithm question - how to reorder a sequence economically

2013-05-24 Thread Ned Batchelder

On 5/24/2013 6:52 AM, Steven D'Aprano wrote:

On Fri, 24 May 2013 01:14:45 -0700, Peter Brooks wrote:


What is the easiest way to reorder a sequence pseudo-randomly?

import random
random.shuffle(sequence)


The sequence is modified in place, so it must be mutable. Lists are okay,
tuples are not.



That is, for a sequence 1,2,3,4 to produce an arbitrary ordering (eg
2,1,4,3) that is different each time.

You can't *guarantee* that it will be different each time. With a four-
item list, there are only 4! = 24 combinations, so on average you'll get
the original order one time in 24. For a ten-item list, that is once
every 3628800 times, and for a twenty-item list, once in
243290200817664 times. But of course these are *random*, and there's
always a chance of this:

http://dilbert.com/strips/comic/2001-10-25




Also, heed the note in the docs:  "Note that for even rather small 
len(x), the total number of permutations of /x/ is larger than the 
period of most random number generators; this implies that most 
permutations of a long sequence can never be generated."  The default 
random number generator has a period of 2**19937-1, which means that 
lists longer than 2080 have more permutations than the period of the 
generator (because factorial(2081) > 2**19937). Most shuffles involve 
lists far shorter than 2080, but it's still good to keep it in mind.


--Ned.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an integer from a sequence of bytes

2013-05-27 Thread Ned Batchelder

On 5/27/2013 10:45 AM, Mok-Kong Shen wrote:

From an int one can use to_bytes to get its individual bytes,
but how can one reconstruct the int from the sequence of bytes?



The next thing in the docs after int.to_bytes is int.from_bytes: 
http://docs.python.org/3.3/library/stdtypes.html#int.from_bytes


--Ned.


Thanks in advance.

M. K. Shen


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


Re: Getting a callable for any value?

2013-05-29 Thread Ned Batchelder

On 5/29/2013 1:46 PM, Croepha wrote:

Is there anything like this in the standard library?

class AnyFactory(object):
def __init__(self, anything):
self.product = anything
def __call__(self):
return self.product
def __repr__(self):
return "%s.%s(%r)" % (self.__class__.__module__, 
self.__class__.__name__, self.product)


my use case is: 
collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None


And I think lambda expressions are not preferable...



It's not clear to me that this does what you want.  Won't your 
defaultdict use the same defaultdict for all of its default values? This 
is hard to describe in English but:


d = 
collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None

d[1][1] = 1
d[2][2] = 2

print d[1]
#->  defaultdict(__main__.AnyFactory(None), {1: 1, 2: 2})
print d[1] is d[2]
#->  True

It might not be possible to get this right without lambdas:

d = collections.defaultdict(lambda: collections.defaultdict(lambda: None))

d[1][1] = 1
d[2][2] = 2

print d[1]
#->  defaultdict( at 0x02091D70>, {1: 1})
print d[1] is d[2]
#->  False


--Ned.

I found itertools.repeat(anything).next and 
functools.partial(copy.copy, anything)


but both of those don't repr well... and are confusing...

I think AnyFactory is the most readable, but is confusing if the 
reader doesn't know what it is, am I missing a standard implementation 
of this?






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


Re: How to get an integer from a sequence of bytes

2013-05-30 Thread Ned Batchelder


On 5/30/2013 2:26 PM, Mok-Kong Shen wrote:

Am 27.05.2013 17:30, schrieb Ned Batchelder:

On 5/27/2013 10:45 AM, Mok-Kong Shen wrote:

From an int one can use to_bytes to get its individual bytes,
but how can one reconstruct the int from the sequence of bytes?


The next thing in the docs after int.to_bytes is int.from_bytes:
http://docs.python.org/3.3/library/stdtypes.html#int.from_bytes


I am sorry to have overlooked that. But one thing I yet wonder is why
there is no direct possibilty of converting a byte to an int in [0,255],
i.e. with a constrct int(b), where b is a byte.



Presumably you want this to work:

>>> int(b'\x03')
3

But you also want this to work:

>>> int(b'7')
7

These two interpretations are incompatible.  If b'\x03' becomes 3, then 
shouldn't b'\x37' become 55?  But b'\x37' is b'7', and you want that to 
be 7.


--Ned.


M. K. Shen



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


Re: PyWart: The problem with "print"

2013-06-02 Thread Ned Batchelder


On 6/2/2013 2:18 PM, Rick Johnson wrote:

On Sunday, June 2, 2013 12:49:02 PM UTC-5, Dan Sommers wrote:

On Mon, 03 Jun 2013 03:20:52 +1000, Chris Angelico wrote:

On Mon, Jun 3, 2013 at 3:04 AM, Rick Johnson

[...]
Or use the logging module.  It's easy to get going quickly
(just call logging.basicConfig at startup time), and with
a little care and feeding, you can control the output in
more ways than can fit into the margin. Oh, yeah, I'm sure
it introduces some overhead.  So does everything else.

I hate log files, at least during development or testing. I prefer to debug on 
the command line or using my IDE. Log files are for release time, not 
development.

Rick, you should give the logging module a try.  The default 
configuration from basicConfig is that the messages all go to stderr, so 
no log files to deal with.  And it's configurable in the ways you want, 
plus a lot more.


--Ned.


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


Re: Output from to_bytes

2013-06-02 Thread Ned Batchelder

On 6/2/2013 3:09 PM, Mok-Kong Shen wrote:

Am 28.05.2013 17:35, schrieb Grant Edwards:

On 2013-05-26, Mok-Kong Shen  wrote:

I don't understand why with the code:

 for k in range(8,12,1):
   print(k.to_bytes(2,byteorder='big'))

one gets the following output:

 b'\x00\x08'
 b'\x00\t'
 b'\x00\n'
 b'\x00\x0b'

I mean the 2nd and 3rd should be b'\x00\x09' and b'x00\x0a'.
Anyway, how could I get the output in the forms I want?


Well, it would help if you told us what output form you want.


As I stated, I like the 2nd and 3rd be b'\x00\x09' and b'\x00\x0a'
respectively. This is what would expeacted to be in a hexadecimal
notation IMHO in other PLs.



When you print bytes, Python doesn't use "hexadecimal notation."  It 
prints a Python bytes literal.  That literal will use printable 
characters like 'Q', or hex escapes like '\x00', or other escapes like 
'\n', depending on the character.   If you want hex output, you have to 
create it yourself, for example with the binascii module.


--Ned.


M. K. Shen



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


Re: Bools and explicitness [was Re: PyWart: The problem with "print"]

2013-06-04 Thread Ned Batchelder


On 6/4/2013 12:19 PM, Rick Johnson wrote:

On Jun 4, 11:00 am, Chris Angelico  wrote:

You know, if you want a language with strict type declarations and
extreme run-time efficiency, there are some around.

I don't like declaring types everywhere, i hate it. I prefer duck
typed languages, HOWEVER, in order for duck typing to work
consistently you must have checks and balances that the programmer can
apply when he feels necessary. My "is_valid" built in will bridge the
gap. We won't be forced to declare types, but we should ALWAYS add
"type checks" to our "truth tests" unless we want to create subtle
bugs. "is_valid" IS the answer!



You are mis-using the term "duck typing." It doesn't mean just, "no type 
declarations." It also means, "the type of the value is irrelevant, all 
that matters is what it can do."  Insisting that something be a list (or 
a dict, ...) is unnecessary and counter to the duck-typing philosophy.  
What's important is that you can iterate, or index it, or whatever it is 
you want to do with the list.  The abstract base classes in the 
collections module were designed to help with determining these 
capabilities: 
http://docs.python.org/2/library/collections.html#collections-abstract-base-classes 
Of course, often, it's best just to do what you want to do rather than 
checking first.


Also, I have no idea why [] isn't a "valid" list.  Surely different 
applications will have different needs for what counts as valid once the 
type-check is passed.


--Ned.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-10 Thread Ned Batchelder
On Monday, June 10, 2013 3:48:08 PM UTC-4, jmfauth wrote:
> -
> 
> 
> 
> A coding scheme works with three sets. A *unique* set
> of CHARACTERS, a *unique* set of CODE POINTS and a *unique*
> set of ENCODED CODE POINTS, unicode or not.
> 
> The relation between the set of characters and the set of the
> code points is a *human* table, created with a sheet of paper
> and a pencil, a deliberate choice of characters with integers
> as "labels".
> 
> The relation between the set of the code points and the
> set of encoded code points is a "mathematical" operation.
> 
> In the case of an "8bits" coding scheme, like iso-XXX,
> this operation is a no-op, the relation is an identity.
> Shortly: set of code points == set of encoded code points.
> 
> In the case of unicode, The Unicode consortium endorses
> three such mathematical operations called UTF-8, UTF-16 and
> UTF-32 where UTF means Unicode Transformation Format, a
> confusing wording meaning at the same time, the process
> and the result of the process. This Unicode Transformation does
> not produce bytes, it produces words/chunks/tokens of *bits* with
> lengths 8, 16, 32, called Unicode Transformation Units (from this
> the names UTF-8, -16, -32). At this level, only a structure has
> been defined (there is no computing). 

This is a really good description of the issues involved with character sets 
and encodings, thanks.

> Very important, an healthy
> coding scheme works conceptually only with this *unique" set
> of encoded code points, not with bytes, characters or code points.
> 

You don't explain why it is important to work with encoded code points.  What's 
wrong with working with code points?

> 
> The last step, the machine implementation: it is up to the
> processor, the compiler, the language to implement all these
> Unicode Transformation Units with of course their related
> specifities: char, w_char, int, long, endianess, rune (Go
> language), ...
> 
> Not too over-simplified or not too over-complicated and enough
> to understand one, if not THE, design mistake of the flexible
> string representation.
> 
> jmf

Again you've made the claim that the flexible string representation is a 
mistake.  But you haven't said WHY.  I can't tell if you are trolling us, or 
are deluded, or genuinely don't understand what you are talking about.

Some day you might explain yourself. I look forward to it.

--Ned.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] Python 3.3.0 alpha 1

2012-03-05 Thread Ned Batchelder

On 3/5/2012 2:54 AM, Georg Brandl wrote:

On behalf of the Python development team, I'm happy to announce the
first alpha release of Python 3.3.0.

This is a preview release, and its use is not recommended in
production settings.

Python 3.3 includes a range of improvements of the 3.x series, as well 
as easier
porting between 2.x and 3.x.  Major new features in the 3.3 release 
series are:


* PEP 380, Syntax for Delegating to a Subgenerator ("yield from")
* PEP 393, Flexible String Representation (doing away with the
  distinction between "wide" and "narrow" Unicode builds)
* PEP 409, Suppressing Exception Context
* PEP 3151, Reworking the OS and IO exception hierarchy
* The new "packaging" module, building upon the "distribute" and
  "distutils2" projects and deprecating "distutils"
* The new "lzma" module with LZMA/XZ support
* PEP 3155, Qualified name for classes and functions
* PEP 414, explicit Unicode literals to help with porting
* The new "faulthandler" module that helps diagnosing crashes
* Wrappers for many more POSIX functions in the "os" and "signal"
  modules, as well as other useful functions such as "sendfile()"

For a more extensive list of changes in 3.3.0, see

http://docs.python.org/3.3/whatsnew/3.3.html

The 3.3 whatsnews page doesn't seem to mention PEP 414 or Unicode 
literals at all.


--Ned.

To download Python 3.3.0 visit:

http://www.python.org/download/releases/3.3.0/

Please consider trying Python 3.3.0a1 with your code and reporting any
bugs you may notice to:

http://bugs.python.org/


Enjoy!

--
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
___
Python-Dev mailing list
python-...@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/ned%40nedbatchelder.com



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


Re: Can I use functions while defining paths?

2017-09-04 Thread Ned Batchelder
On 9/4/17 4:08 AM, Andrej Viktorovich wrote:
> Hello,
>
> Trying to import my made module to python with helper function:
>
> import os.path.join 
> ("D","pyth_nonsens","workspace_python","PyhonTutorial","reader")
>
>
>
 import os.path.join 
 ("D","pyth_nonsens","workspace_python","PyhonTutorial","reader")
>   File "", line 1
> import os.path.join 
> ("D","pyth_nonsens","workspace_python","PyhonTutorial","reader")
> ^
>
>
> Can I use functions while defining paths?

As others have said, the import statement takes identifiers, not
expressions.  More importantly, it's unusual to try to name a specific
absolute path in an import statement. The best thing is to install
libraries so that you can import them like this:

    import reader

If you can't import them, the next best thing is to use an environment
variable to adjust PYTHONPATH so that the library can be found:

    PYTHONPATH=D:\pyth_nonsens\workspace_python\PyhonTutorial python
myprog.py

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


Re: Run python module from console

2017-09-05 Thread Ned Batchelder
On 9/5/17 11:16 AM, Stefan Ram wrote:
> Andrej Viktorovich  writes:
>> I suppose I can run python module by passing module as param for executable:
>> python.exe myscr.py
>> But how to run script when I'm inside of console and have python prompt:

The Python console isn't meant for ad-hoc execution of random scripts. 
It's designed for running one program, from the OS command line.  If you
need to run different scripts within one interpreter session, it might
be better to reorganize your code, or find a different execution
environment.

> exec( compile( open( 'myscr.py', 'rb' ).read(), 'myscr.py', 'exec' ))
>
>   . This looks quite complicated, but there are rumors
>   that Python 4 might have a »execfile« function, and
>   one then will be able to write:
>
> execfile(  'myscr.py' )

It's better to not start rumors about fictitious Python versions.

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


Re: A question on modification of a list via a function invocation

2017-09-05 Thread Ned Batchelder
On 9/5/17 1:02 PM, Steve D'Aprano wrote:
> On Tue, 5 Sep 2017 11:37 pm, Gregory Ewing wrote:
>
>> Dennis Lee Bieber wrote:
>>> Pascal, probably Modula-2, Visual BASIC are closer to the C++ reference
>>> semantics, in that the definition of a function declares how the
>>> argument(s) are passed.
>> Well, sort of. In Pascal and Modula, and also VB I think,
>> parameters are the only things that can be declared as having
>> reference semantics, whereas references in C++ are first-class
>> things that can be stored in any variable.
> No, they aren't first-class. 

Did you mis-read Gregory's claim? He said, "references *in C++* are
first-class things".  You seem to be talking below about Python things.

>
> - It is not possible to refer to a reference after it is defined; any 
>   occurrence of its name refers directly to the object it references.
>
> - Since you cannot refer directly to a reference, but only the object
>   it points to, you cannot have a reference to a reference.
>
> - Containers of references are not allowed.
>
> - Once a reference to an object is created, it cannot be changed to 
>   reference another object ("to be reseated").
>
> The last is only a limitation if you think of references as mutable pointers 
> in
> the C sense. But if you think of them as objects in the Python sense, that
> makes them merely immutable.
>
> But the inability to refer to the reference itself, the lack of references to
> references, and the inability to have a container of references, makes them
> second-class values -- or possibly not values at all.
>
> (I don't know enough about C++ to distinguish between the last two opinions, 
> but
> I'm strongly leaning towards "not values at all".)
>
>
>

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


Re: A question on modification of a list via a function invocation

2017-09-05 Thread Ned Batchelder


On 9/5/17 1:28 PM, Chris Angelico wrote:
> On Wed, Sep 6, 2017 at 3:15 AM, Ned Batchelder  wrote:
>> On 9/5/17 1:02 PM, Steve D'Aprano wrote:
>>> On Tue, 5 Sep 2017 11:37 pm, Gregory Ewing wrote:
>>>
>>>> Dennis Lee Bieber wrote:
>>>>> Pascal, probably Modula-2, Visual BASIC are closer to the C++ reference
>>>>> semantics, in that the definition of a function declares how the
>>>>> argument(s) are passed.
>>>> Well, sort of. In Pascal and Modula, and also VB I think,
>>>> parameters are the only things that can be declared as having
>>>> reference semantics, whereas references in C++ are first-class
>>>> things that can be stored in any variable.
>>> No, they aren't first-class.
>> Did you mis-read Gregory's claim? He said, "references *in C++* are
>> first-class things".  You seem to be talking below about Python things.
>>
> And everything Steve said was about C++ references, which are a form
> of alias. Not a 'thing'.

I see, I misunderstood. Sorry for the distraction.

>
> ChrisA

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


Re: Using Python 2

2017-09-08 Thread Ned Batchelder
On 9/8/17 6:12 AM, Leam Hall wrote:
> I've read comments about Python 3 moving from the Zen of Python. I'm a
> "plain and simple" person myself. Complexity to support what CompSci
> folks want, which was used to describe some of the Python 3 changes,
> doesn't help me get work done. 

I've heard a lot of FUD about the Python 3 transition, but this one is
new to me.  What is it that CompSci folks want that developers don't
want, that ruined Python 3?

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


Re: Using Python 2

2017-09-08 Thread Ned Batchelder

On 9/8/17 10:23 AM, Leam Hall wrote:
> On 09/08/2017 09:57 AM, Ned Batchelder wrote:
>> I've heard a lot of FUD about the Python 3 transition, but this one is
>> new to me.  What is it that CompSci folks want that developers don't
>> want, that ruined Python 3?
>
>
> It's not FUD if it's true. Calling it FUD without checking is, um,
> FUD. The phrase was "many of the changes in Python 3 are theoretically
> based, cleaning up of how Python does things to make them fit with
> what Computer Science teaches."

I tried to check, but Google doesn't find me that quote, so I'm not sure
if there was further elaboration. I still don't know which of the Python
3 changes were foisted on us by those bothersome theoretical Computer
Science people.

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


Re: The Incredible Growth of Python (stackoverflow.blog)

2017-09-10 Thread Ned Batchelder
On 9/10/17 10:46 AM, Rick Johnson wrote:
> The stain of Python3's violent and radical changes to the
> core philosophy of the language may never be washed clean,
> and although we might have survived Python3 _eventually_,
> type-hints is like a wooden stake driven into the heart of
> this community. It's almost like they _want_ to destroy this
> language. 

Given the recent Stack Overflow blog post about Python's accelerating
growth, and TIOBE rating it #1, you'd think the sky-is-falling
doom-sayers would get tired of being wrong all the time.

I guess not.

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


Re: The Incredible Growth of Python (stackoverflow.blog)

2017-09-12 Thread Ned Batchelder
On 9/12/17 7:40 AM, Chris Angelico wrote:
> On Tue, Sep 12, 2017 at 9:34 PM, Leam Hall  wrote:
>> On 09/12/2017 07:27 AM, Chris Angelico wrote:
>>> On Tue, Sep 12, 2017 at 9:20 PM, Leam Hall  wrote:
 Hey Chris,

 This is an area the Python community can improve on. Even I would
 encourage
 someone new to Python and wanting to do webdev to use Python 3.

 But if someone comes onto the list, or IRC, and says they need to stay on
 Python 2 then please drop the dozens of e-mails and comments about
 upgrading. Help the person learn; that makes them happier with Python and
 when the time comes to switch to Python 3 they probably will.
>>>
>>> If you read back in my emails, you may find that I actually wasn't
>>> telling you to upgrade to Python 3 - just to Python 2.7, which is an
>>> easy upgrade from 2.6, and gives you the security fixes and other
>>> improvements that come from using a supported version of the language.
>>> Is it "hostile" to tell people to upgrade like that? If someone is
>>> using Python 3.2 today, I'm going to strongly recommend upgrading to
>>> the latest 3.x. If someone's using Windows 98, I'm not going to say
>>> "well, here's how to get everything working under Win98", I'm going to
>>> say "upgrade to a better OS".
>>>
>>> If that's hostile, I am not sorry to be hostile. At some point, you
>>> have to either get onto something supported, or do all the support
>>> work yourself.
>>>
>>> ChrisA
>>>
>> Hey Chris; only some folks were overtly hostile.  :)
>>
>> Yet look at your answer; "upgrade". For a person working on a server there's
>> usually no economic choice to do. The OS python must stay in place and the
>> newly installed upgrade must be personally maintained, updated, and tested
>> when security patches come out. For one desktop that's not an issue. For
>> dozens, or hundreds, or thousands, its not likely to happen.
> Until you get hit by a vulnerability that was patched four years ago,
> but you didn't get the update. Now your server is down - or, worse,
> has been compromised. What's the economic cost of that?
>
> You might choose to accept that risk, but you have to at least be
> aware that you're playing with fire. Laziness is not the cheap option
> in the long run.
>
> ChrisA

Leam has done us the favor of explaining how this list feels to people
coming into it. We should take his point of view seriously.  You are
still arguing about whether software should be upgraded.  Maybe it
should be, but it wasn't was the OP was asking about. 

The OP probably also isn't saving enough for retirement, and it's good
advice to save more, but it's not what they were asking about.  How far
afield from the actual question is it OK to offer unsolicited advice
before it comes off as hostile? Apparently we crossed the line on this
question.

--Ned.

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


Re: Old Man Yells At Cloud

2017-09-17 Thread Ned Batchelder

On 9/16/17 1:38 AM, Steve D'Aprano wrote:

/rant on

So apparently everyone who disagrees that Python should be more like Javascript
is an old greybeard fuddy-duddy yelling "Get off my lawn!" to the cool kids --
and is also too stupid to know how dumb they are.

"Hi, I've been programming in Python for what seems like days now, and here's
all the things that you guys are doing wrong. I insist that you fix them
immediately, it doesn't matter how much code it will break, that's not
important. What is important is that Javascript programmers like me shouldn't
be expected to learn anything new or different when they program with Python."

/rant off

And no, for once it wasn't Ranting Rick.


The thing that struck me about the interaction (on Python-Ideas, btw) 
was that Javascript actually is adding new language features at an 
impressive pace, and many of them seem very Pythonic.  But they 
sometimes choose different syntax.


For example, their "spread" operator is ..., where Python uses *:

    new_list = [new_start, *old_list, new_end]

vs:

    new_array = [new_start, ...old_array, new_end]

Making Python more like Javascript (in this case) would have required 
breaking existing Python programs. Javascript could have use * as the 
spread operator without breaking anyone. But they didn't, and I wonder 
if anyone petitioned them to keep compatibility with Python to easy the 
plight of the multi-lingual programmer.


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


Re: How to get Nose to run doctests from my Markdown documentation?

2017-09-20 Thread Ned Batchelder

On 9/20/17 10:07 AM, Skip Montanaro wrote:

I routinely include doctests as a source of test cases in my nose runs, but
I want to also coax it to check the examples in my Markdown files. Is there
a way to do this? If I explicitly give a Markdown file on the command line,
nose complains:

Unable to load tests from file ...

Am I perhaps missing some sort of nose-markdown plugin which would
magically make this work?

Thx,

Skip


There are tools for getting doctests out of .rst files.  Is it an option 
to use .rst instead of .md?


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


Re: How to get Nose to run doctests from my Markdown documentation?

2017-09-20 Thread Ned Batchelder

On 9/20/17 11:17 AM, Skip Montanaro wrote:

There are tools for getting doctests out of .rst files.  Is it an option to
use .rst instead of .md?

Given the existence proof of md working as an extension (see my
previous follow-up), my guess is that it more-or-less supports just
about any nearly-plain-text format. I could use .rst, I suppose, but
then I'd have to add a magic token to my files to tell Emacs they are
really in Markdown format.



I didn't mean, "Can you name your Markdown files with an .rst 
extension," I meant, "Can you use ReST instead of Markdown?"


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


Re: errors with json.loads

2017-09-20 Thread Ned Batchelder


On 9/20/17 8:22 PM, Bill wrote:
Apparenty an \xa0 byte corresponds to a "non-breaking space". What 
sort of white space characters are allowed in a json file ( tabs and 
newlines?)?  Just curious. 


These things can be looked up.  From RFC 7159 
(https://tools.ietf.org/html/rfc7159):


   Insignificant whitespace is allowed before or after any of the six
   structural characters.

  ws = *(
  %x20 /  ; Space
  %x09 /  ; Horizontal tab
  %x0A /  ; Line feed or New line
  %x0D )  ; Carriage return

--Ned.

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


Re: errors with json.loads

2017-09-21 Thread Ned Batchelder

On 9/20/17 10:35 PM, Bill wrote:

Ned Batchelder wrote:


On 9/20/17 8:22 PM, Bill wrote:
Apparenty an \xa0 byte corresponds to a "non-breaking space". What 
sort of white space characters are allowed in a json file ( tabs and 
newlines?)?  Just curious. 


These things can be looked up.  From RFC 7159 
(https://tools.ietf.org/html/rfc7159):




Thank you.  So what is most likely the root cause of the original 
poster's problem (assuming he typed out the text with a text editor)?


I can only assume that the actual data being read is different than the 
data they put into the message here.


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


Re: errors with json.loads

2017-09-21 Thread Ned Batchelder

On 9/21/17 12:18 PM, john polo wrote:

Bill,
Thanks for the reply. I wasn't sure how to get Python 2 through the 
cmd or IPython, so I went through ArcGIS, but it's mostly the same 
result:


>>> file = open('books.json','r')
>>> text = file.read()
>>> text = json.loads(text)


After the file.read() line, put this:  print(repr(text))  or 
print(ascii(text)) if you are on Python 3.  Show us that output. That 
will make clear what is wrong with the data.


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


Re: Assertions

2017-09-21 Thread Ned Batchelder

On 9/21/17 12:29 PM, Tobiah wrote:

Are these completely equivalent?

def foo(thing):

 assert(thing > 0), "Thing must be greater than zero"


def foo(thing):

 if not (thing > 0): raise AssertionError("Thing must be greater than 
zero")


Other than the fact that the assertion can be turned off
with -O?



Let's see:

    Python 3.6.2 (default, Jul 17 2017, 07:05:09)
    [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo1(thing):
    ...   assert(thing > 0), "Thing must be greater than zero"
    ...
    >>> def foo2(thing):
    ...   if not (thing > 0): raise AssertionError("Thing must be 
greater than zero")

    ...
    >>> import dis
    >>> dis.dis(foo1)
  2   0 LOAD_FAST    0 (thing)
  2 LOAD_CONST   1 (0)
  4 COMPARE_OP   4 (>)
  6 POP_JUMP_IF_TRUE    16
  8 LOAD_GLOBAL  0 (AssertionError)
 10 LOAD_CONST   2 ('Thing must be greater 
than zero')

 12 CALL_FUNCTION    1
 14 RAISE_VARARGS    1
    >>   16 LOAD_CONST   0 (None)
 18 RETURN_VALUE
    >>> dis.dis(foo2)
  2   0 LOAD_FAST    0 (thing)
  2 LOAD_CONST   1 (0)
  4 COMPARE_OP   4 (>)
  6 POP_JUMP_IF_TRUE    16
  8 LOAD_GLOBAL  0 (AssertionError)
 10 LOAD_CONST   2 ('Thing must be greater 
than zero')

 12 CALL_FUNCTION    1
 14 RAISE_VARARGS    1
    >>   16 LOAD_CONST   0 (None)
 18 RETURN_VALUE
    >>>

Yes, they are completely equivalent, compiling to precisely the same 
bytecode.


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


Re: Beginners and experts (Batchelder blog post)

2017-09-23 Thread Ned Batchelder

On 9/23/17 2:52 PM, Leam Hall wrote:

On 09/23/2017 02:40 PM, Terry Reedy wrote:

https://nedbatchelder.com//blog/201709/beginners_and_experts.html

Great post.


Yup. Thanks for the link. I often have that "I bet Fred> doesn't get frustrated." thing going. Nice to know Ned bangs his 
head now and again.  :P




"Ow!" --me


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


Re: [Tutor] beginning to code

2017-09-25 Thread Ned Batchelder

On 9/25/17 8:24 AM, Steve D'Aprano wrote:

On Mon, 25 Sep 2017 08:05 pm, Antoon Pardon wrote:


Pass by reference doesn't imply being able to
write a swap function.

Really. Do you have a counter-example?



A swap function as possible in pascal requires two conditions.

1) Pass by reference
2) Copy-over assignment.

I don't know what you think "copy-over assignment" means, but none of
DuckDuckGo, Google, Bing or Yahoo finds that term except in your post.






Would we be able to end these interminable debates if we just agree that 
we all know how it works, and it isn't important to come up with a 
simple name for what it is? It seems clear to me that "value" and 
"reference" are wildly vague terms, used slightly differently by each 
language, and by different people even in the same language if they have 
different perspectives.


Can't we just stop? :)

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


Re: [Tutor] beginning to code

2017-09-25 Thread Ned Batchelder

On 9/25/17 9:15 AM, Antoon Pardon wrote:

Op 25-09-17 om 14:53 schreef Ned Batchelder:

On 9/25/17 8:24 AM, Steve D'Aprano wrote:

On Mon, 25 Sep 2017 08:05 pm, Antoon Pardon wrote:


Pass by reference doesn't imply being able to
write a swap function.

Really. Do you have a counter-example?



A swap function as possible in pascal requires two conditions.

1) Pass by reference
2) Copy-over assignment.

I don't know what you think "copy-over assignment" means, but none of
DuckDuckGo, Google, Bing or Yahoo finds that term except in your post.





Would we be able to end these interminable debates if we just agree
that we all know how it works, and it isn't important to come up with
a simple name for what it is?

I'm not sure that Steve knows how it works. When he denies that the assignment 
is
an alias operation in Python that casts an important doubt.


I can assure you that Steve knows how it works. Again, the disagreement 
is almost certainly over the semantics of the word "alias."



It seems clear to me that "value" and "reference" are wildly vague
terms, used slightly differently by each language, and by different
people even in the same language if they have different perspectives.

Well in that case and considering your remark above, maybe the residents
shouldn't be so eager to deny to newbees that python has call by reference.


You're still trying to get people to agree to a label like "call by 
reference."  This is where the disagreement comes from.


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


Re: Grumpy-pants spoil-sport [was Re: [Tutor] beginning to code]

2017-09-25 Thread Ned Batchelder

On 9/25/17 12:29 PM, Steve D'Aprano wrote:

Regardless of whether I'm using Python, Swift, Java, C, Pascal or Scheme, if I
write something like:

x = Parrot(name="Polly")

(using Python syntax for simplicity) and somebody tries to tell me that the
value of x is anything but a Parrot instance named "Polly", I have no time for
that sort of nonsense. They might as well tell me that I'm typing this response
on an elephant.


But in this line:

    x = 2 + 2

You can say,

    the value of x is 4

or,

    the value of x is an int object with a value of 4

or,

    the value of x is a reference to an int object with a value of 4,

and in some ways, each of those is a correct statement. They are 
different perspectives on the same complicated abstract relationships 
inside your program.  Most of the disagreements in this thread stem from 
someone picking one of those three statements and insisting that it is 
*the* right statement, or from differing interpretations of words like 
value, reference, pointer, alias, etc.


Software gets complicated because it involves multiple levels of 
abstraction layered on top of each other.  We might as well be arguing 
like this:


    A: "The gas pedal makes the car go"

    B: "Nonsense! The gas pedal supplies fuel to the engine, it's the 
engine that makes the car go"


    C: "None of you know what you are talking about! The engine merely 
turns the axle. It's the wheels that make the car go!"


    D: "The wheels only work because of the friction between rubber and 
asphalt!"


etc etc etc.

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


Re: TypeError with map with no len()

2017-09-25 Thread Ned Batchelder

On 9/25/17 12:44 PM, john polo wrote:

Python List,

I am trying to make practice data for plotting purposes. I am using 
Python 3.6. The instructions I have are


import matplotlib.pyplot as plt
import math
import numpy as np
t = np.arange(0, 2.5, 0.1)
y1 = map(math.sin, math.pi*t)
plt.plot(t,y1)

However, at this point, I get a TypeError that says

object of type 'map' has no len()

In [6]: t
Out[6]:
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9, 1. ,
    1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. , 2.1,
    2.2,  2.3,  2.4])
In [7]: y1
Out[7]: 
In [8]: math.pi*t
Out[8]:
array([ 0.    ,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
    1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
    3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
    4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
    6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])

At the start of creating y1, it appears there is an array to iterate 
through for the math.sin function used in map(), but y1 doesn't appear 
to be saving any values. I expected y1 to hold a math.sin() output for 
each item in math.pi*t, but it appears to be empty. Am I 
misunderstanding map()? Is there something else I should be doing 
instead to populate y1?


In Python 2, map() produced a list. In Python 3, it returns a lazy 
iterator instead.  You can run the iterator with list():


    y1 = list(map(math.sin, math.pi*t))

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


Re: [Tutor] beginning to code

2017-09-25 Thread Ned Batchelder

On 9/25/17 5:32 AM, Antoon Pardon wrote:

Can you explain, what you mean by "Pass-By-Reference" as far a I understand,
pass by reference means that the parameter of the function becomes an alias
of the argument, so that if the entity is mutated through one name that
mutation is visible through the other name.


function(x, y)  # allowed
function(namespace.x, module.y)  # allowed
function(x + 1, 2)  # FORBIDDEN: can't pass expressions or constants

Pass by reference, doesn't imply the above is forbidden. A language can
define, that the "x + 1" will produce an new entity and that a reference
to that entity will be passed.



Wikipedia has the right definition of call by reference 
(https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference):


   /Call by reference/ (also referred to as /pass by reference/) is an
   evaluation strategy where a function receives an implicit reference
    to
   a variable used as argument, rather than a copy of its value. This
   typically means that the function can modify (i.e. assign to
   )
   the variable used as argument—something that will be seen by its caller.

The key idea here is that it is a reference to a *variable* that is 
passed, not a reference to a value.  Python has no references to 
variables, so it cannot support call by reference.   Because Python 
passes references to values, it is easy to call it "call by reference," 
but that is not what the term means.


The Wikipedia definition unfortunately includes "rather than a copy of 
its value," as if those are the only two options (a common 
misunderstanding).


Elsewhere in this thread, someone asserted that to be call by reference, 
you have to be able to write a swap(x,y) function.  True 
call-by-reference would make this possible.  Python cannot do it.


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


Re: Grumpy-pants spoil-sport [was Re: [Tutor] beginning to code]

2017-09-25 Thread Ned Batchelder

On 9/25/17 10:20 PM, Steve D'Aprano wrote:

On Tue, 26 Sep 2017 02:54 am, Ned Batchelder wrote:
[...]




We've been asked nicely by the list mod to stop :)

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


Re: Real Programmers Write Docs

2017-09-27 Thread Ned Batchelder

On 9/27/17 6:55 PM, Rob Gaddi wrote:
Anyone have any good references on using Sphinx to generate a mix of 
autogenerated API docs and hand-written "Yeah, but this is what you DO 
with it" docs?  Free is good but I'm happy to drop money on books if 
they're worthwhile.




I can offer you an example: the coverage.py docs are in Sphinx, and use 
both auto-generated and hand-written pages: 
https://github.com/nedbat/coveragepy/tree/master/doc   I'm not sure what 
information you are looking for, maybe this will help?


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


Re: newb question about @property

2017-09-30 Thread Ned Batchelder

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance methods 
__get__(), __set__(), and possibly __del__(), as desired, as I could 
easily provide them with "ideal" customization. Am I overlooking 
something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


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


Re: newb question about @property

2017-09-30 Thread Ned Batchelder

On 9/30/17 7:18 PM, Bill wrote:

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it 
seems like it would be preferable to just define (override) instance 
methods __get__(), __set__(), and possibly __del__(), as desired, as 
I could easily provide them with "ideal" customization. Am I 
overlooking something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property


Can you show us the code you are using it to mimic that?

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


Re: The "loop and a half"

2017-10-04 Thread Ned Batchelder

On 10/4/17 7:37 AM, Stefan Ram wrote:

bartc  writes:

Note that your reverse-indentation style is confusing!

   In Python, indentation can be significant.

   Sometimes, some lines in Python must be indented by 0.

   This dictates that Python code cannot be indented
   in posts to differentiate it from the natural-language
   body of the post. Therefore, it's rather the
   natural-language body that has to be indented.



FWIW, I also find your posts hard to read because of the inverted 
indentation.  We don't have difficulty understanding the meaning of 
block-indented chunks of Python code.


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


Re: "comprehend" into a single value

2017-10-08 Thread Ned Batchelder

On 10/8/17 1:00 AM, Andrew Z wrote:

and how about adding "IF" into the mix ?

as in :

a=0

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}

for i in dict:

  p+= 10 if dict[i][1] in [1,2,3,4,5] else 0


can i "squish" "for" and "if" together ? or will it be too perl-ish ?


    sum(10 for v in dict.values() if v[1] in [1,2,3,4,5])

or:

    sum((10 if v[1] in [1,2,3,4,5] else 0) for v in dict.values())

(in case you actually need something other than 0.)

Also, note that if your list of five values is actually much longer than 
five, then you want a set:


    sum((10 if v[1] in {1,2,3,4,5} else 0) for v in dict.values())

--Ned.






On Sun, Oct 8, 2017 at 12:37 AM, Andrew Z  wrote:


Nathan, Bob - on the money. Thank you !

On Sat, Oct 7, 2017 at 11:30 PM, bob gailer  wrote:


On 10/7/2017 11:17 PM, Nathan Hilterbrand wrote:


dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = sum([dict[i][1] for i in dict])

Something like that?


Ah, but that's 2 lines.

sum(val[1] for val in  {10: ['a',1,'c'], 20: ['d',2,'f']}.values())

On Sat, Oct 7, 2017 at 11:07 PM, Andrew Z  wrote:

Hello,

   i wonder how  can i accomplish the following as a one liner:

dict= {10: ['a',1,'c'], 20: ['d',2,'f']}
p = 0
for i in dict:
  p += dict[i][1]


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



--
Image and video hosting by TinyPic





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


Re: Is there a way to globally set the print function separator?

2017-10-09 Thread Ned Batchelder

On 10/9/17 12:22 PM, John Black wrote:

I want sep="" to be the default without having to specify it every time I
call print.  Is that possible?




There isn't a way to change the default for print(sep="") globally. 
Generally when you want better control over the output, you use string 
formatting.  Instead of:


    print("X is ", x, " and y is ", y, sep="")

use:

    print("X is {} and y is {}".format(x, y))

If you show us your actual print lines, we can give more concrete advice.

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


Re: about 'setattr(o, name, value)' and 'inspect.signature(f)'

2017-10-10 Thread Ned Batchelder

On 10/10/17 11:00 AM, Stefan Ram wrote:

xieyuheng  writes:

1. 'setattr(o, name, value)' can be used for what kind of objects ?

   It takes three objects as arguments.

   The first object should have an attribute named by the value
   of »name« that should allow this attribute to be set to
   »value« as if by

o.=value

   where  is the value of »name« (which should be a string).



One tweak to this: the object doesn't need to have the attribute 
initially.  setattr() can create new attributes that don't already exist.


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


Re: An endless loop

2017-10-15 Thread Ned Batchelder

On 10/15/17 9:59 AM, bartc wrote:

On 15/10/2017 12:20, Chris Angelico wrote:

On Sun, Oct 15, 2017 at 9:15 PM, bartc  wrote:



I assume you're talking about the while-loop (because on my machine, it
hangs just using 'from turtle...' or 'import turtle').


(Machine was screwed up I think, as I had to restart it shortly after 
for other reasons. When the turtle graphics worked.)


That looks to be a repeat-N-times loop. There isn't a dedicated 
statement
for that, the closest Python feature would be 'for i in range(n)' 
with i a

dummy loop variable.


You can use that or "for _ in range(n)" as a pretty effective form of
that loop. I've never had a problem with it. Python doesn't need
another type of loop.


I could understand that sentiment if there were already dozens. But I 
believe there's only, what, two loop types? To implement a number of 
basic looping requirements which, if not that numerous, are somewhat 
more than two.


Not exactly taxing the grey matter which already has those extra loop 
types in mind, and has to find a way to express them in terms of only 
two.




We've covered this before.  A challenge for the group: let's not create 
yet another 100-reply thread rehashing the design of Python looping... 
Please? :)


--Ned.

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


Re: how to read in the newsreader

2017-10-16 Thread Ned Batchelder

On 10/16/17 12:31 AM, Andrew Z wrote:

i'm typing without thinking. Sorry. Let me try again.

I subscribed to python-list@python.org. That has 0 spam ( as far as i can
see), but i can only get a digest.


You can choose to get individual messages from Python-List.

--Ned.

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


Re: why del is not a function or method?

2017-10-16 Thread Ned Batchelder

On 10/16/17 12:16 PM, Oren Ben-Kiki wrote:

That doesn't explain why `del` isn't a method though. Intuitively,
`my_dict.delete(some_key)` makes sense as a method. Of course, you could
also make the same case for `len` being a method... and personally I think
it would have been cleaner that way in both cases. But it is a minor issue,
if at all.

I guess the answer is a combination of "historical reasons" and "Guido's
preferences"?


It would still need to be a statement to allow for:

    del x

since "x.del()" wouldn't affect the name x, it would affect the value x 
refers to.


--Ned.




On Mon, Oct 16, 2017 at 6:58 PM, Stefan Ram  wrote:


Xue Feng  writes:

I wonder why 'del' is not a function or method.

   Assume,

x = 2.

   When a function »f« is called with the argument »x«,
   this is written as

f( x )

   . The function never gets to see the name »x«, just
   its boundee (value) »2«. So, it cannot delete the
   name »x«.

   Also, the function has no access to the scope of »x«,
   and even more so, it cannot make any changes in it.

   Therefore, even a call such as

f( 'x' )

   will not help much.

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



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


Re: Strange behavior in string interpolation of constants

2017-10-16 Thread Ned Batchelder

On 10/16/17 7:39 PM, מיקי מונין wrote:

Hello, I am working on an article on python string formatting. As a part of
the article I am researching the different forms of python string
formatting.

While researching string interpolation(i.e. the % operator) I noticed
something weird with string lengths.

Given two following two functions:

def simple_interpolation_constant_short_string():
 return "Hello %s" % "World!"

def simple_interpolation_constant_long_string():
 return "Hello %s. I am a very long string used for research" % "World!"


Lets look at the bytecode generated by them using the dis module

The first example produces the following bytecode:
   9   0 LOAD_CONST   3 ('Hello World!')
   2 RETURN_VALUE

It seems very normal, it appears that the python compiler optimizes the
constant and removes the need for the string interpolation

However the output of the second function caught my eye:

  12  0 LOAD_CONST   1 ('Hello %s. I am a very long
string used for research')
   2 LOAD_CONST2 ('World!')
   4 BINARY_MODULO
   6 RETURN_VALUE

This was not optimized by the compiler! Normal string interpolation was
used!

Based on some more testing it appears that for strings that would result in
more than 20 characters no optimization is done, as evident by these
examples:

def expected_result():
 return "abcdefghijklmnopqrs%s" % "t"

Bytecode:
  15  0 LOAD_CONST   3 ('abcdefghijklmnopqrst')
   2 RETURN_VALUE

def abnormal_result():
 return "abcdefghijklmnopqrst%s" % "u"

Bytecode:

  18  0 LOAD_CONST   1 ('abcdefghijklmnopqrst%s')
   2 LOAD_CONST 2 ('u')
   4 BINARY_MODULO
   6 RETURN_VALUE

I am using Python 3.6.3
I am curios as to why this happens. Can anyone shed further light on this
behaviour?


Optimizers have plenty of heuristics.  This one seems to avoid the 
constant folding if the string is larger than 20.  The code seems to 
bear this out 
(https://github.com/python/cpython/blob/master/Python/peephole.c#L305):


    } else if (size > 20) {
    Py_DECREF(newconst);
    return -1;
    }

As to why they chose 20?  There's no clue in the code, and I don't know.

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


Re: why del is not a function or method?

2017-10-16 Thread Ned Batchelder

On 10/16/17 9:06 PM, bartc wrote:

On 17/10/2017 01:53, Steve D'Aprano wrote:

On Tue, 17 Oct 2017 03:16 am, Oren Ben-Kiki wrote:


That doesn't explain why `del` isn't a method though.



`del` cannot be a method or a function, because the argument to `del` 
is the

name of the variable, not the contents of the variable.

If we write:

 x = 123
 del x

then `del` needs to delete the *name* "x", not the value of x, namely 
123. If
del were a function or method, it would only see the value, 123, and 
have no

idea what the name is.

`del` is kind of like an "anti-assignment" in that the argument to 
`del` must
be exactly the same sort of expression that can appear on the left 
hand side

of assignment:


 123 = 1+1  # illegal
 del 123  # also illegal


Yet in Stefan Ram's example with del applied to a local 'x', it raised 
an error on:


    del x    # x not yet assigned to

but an assignment to x would have been fine.


Steve meant that syntactically it had to be valid on the left-hand 
side.  "x" is a syntactically valid LHS, "1+1" is not.


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


Re: [RELEASE] Python 3.7.0a2 is now available for testing

2017-10-17 Thread Ned Batchelder

On 10/17/17 3:35 PM, Ned Deily wrote:

Python 3.7.0a2 is the second of four planned alpha previews of Python 3.7,
the next feature release of Python.  During the alpha phase, Python 3.7
remains under heavy development: additional features will be added
and existing features may be modified or deleted.  Please keep in mind
that this is a preview release and its use is not recommended for
production environments.  The next preview, 3.7.0a3, is planned for
2017-11-27.  You can find Python 3.7.0a2 and more information here:

https://www.python.org/downloads/release/python-370a2/



The coverage.py test suite passes. Keep up the good work! :)

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


Re: Let's talk about debuggers!

2017-10-25 Thread Ned Batchelder

On 10/25/17 9:07 AM, Thomas Jollans wrote:

Hi,

I just wanted to know what tools everyone used for debugging Python
applications - scripts / backend / desktop apps / notebooks / whatever.
Apart from the usual dance with log files and strategically inserted
print() calls, that is.

Of course we all know and mildly dislike pdb.

Personally, in practice, I'm most likely to need a debugger when
prototyping a function in a Jupyter notebook. There, ipdb, summoned with
the %%debug magic incantation, does the trick.

Sometimes, though, I miss having a visual debugger. You know, the kind
that Visual Basic has had for decades. There's one in Chrome dev tools
if you ever have the misfortune of writing JavaScript.

What options are there for Python (that work)? What text editors (and
IDEs) have a decent integrated debugger or debugging plugin? (Is there
anything for Sublime?) Does anyone use them? (How do YOU debug?)

I vaguely remember WinPDB, but that hasn't seen a release in more than
seven years...




pudb is a visual terminal debugger: https://pypi.python.org/pypi/pudb

It uses the same commands as pdb, so it's easy to get started, but it 
gives you a variables pane, with customizable presentation, and so on.


One of my favorite features: you can add a set_trace line in your 
program, and then if during the debugging session you realize you don't 
want to stop there every time, you can disable that breakpoint even 
though it's an explicit line of code telling the debugger to stop.


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


Re: Just a quick question about main()

2017-10-27 Thread Ned Batchelder

On 10/27/17 2:05 PM, ROGER GRAYDON CHRISTMAN wrote:

While teaching my introductory course in Python, I occasionally see
submissions containing the following two program lines, even before
I teach about functions and modules:

if __name__ = '__main__':
...  main()

When I ask about it, I hear things like they got these from other instructors,
or from other students who learned it from their instructors, or maybe
from some on-line programming tutorial site.

I'm all on board with the first of these two lines -- and I teach it myself
as soon as I get to modules.

My question is more about the second.

Do "real" Pythonista's actually define a new function main() instead
of putting the unit test right there inside the if?

Or am I correct in assuming that this main() is just an artifact from
people who have programmed in C, C++, or Java for so long that
they cannot imagine a program without a function named "main"?


There's no need for "if __name__ == '__main__':" for unit tests. You can 
let unittest or pytest discover the tests themselves, and run them.


I often write this clause:

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

Then I can write tests that call main() to be sure it does what I think 
it does.


Or, I can let setuptools entry_points handle that clause for me:

    entry_points={
    'console_scripts': [
    'coverage = coverage.cmdline:main',
    ],
    },


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


Re: Coding style in CPython implementation

2017-10-28 Thread Ned Batchelder

On 10/28/17 3:00 PM, Stefan Ram wrote:

=?UTF-8?B?zqPPhM6tz4bOsc69zr/PgiDOo8+Jz4bPgc6/zr3Or86/z4U=?= 
 writes:

What I wanted to ask is, is there a particular reason for not choosing

   I am not a CPython developer, but here are my 2 cents about
   the possibilities:


if (variable == NULL) { ... }
if (!variable) { ... }

   »!variable« is clearer, because it does not depend on the
   definition of »NULL«. »NULL« is not part of the C language proper.
Especially if NULL is not part of the standard, then you need to write 
"variable == NULL", since "!variable" may not have the same effect after 
"return NULL;" depending on how NULL is defined.


   (I sometimes like to write »if( variable ); else { ... }«.)

Ick.

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


Re: Coding style in CPython implementation

2017-10-28 Thread Ned Batchelder

On 10/28/17 4:26 PM, Stefan Ram wrote:

Ned Batchelder  writes:

On 10/28/17 3:00 PM, Stefan Ram wrote:

=?UTF-8?B?zqPPhM6tz4bOsc69zr/PgiDOo8+Jz4bPgc6/zr3Or86/z4U=?= 
 writes:

What I wanted to ask is, is there a particular reason for not choosing

definition of »NULL«. »NULL« is not part of the C language proper.

Especially if NULL is not part of the standard,

   »NULL« is defined in the standard, but it is an identifier
   from the library and, therefore, needs an »#include«.

   The language proper is the language core without any
   library added.

   The expression »NULL« AFAIK has only the meaning that
   usually is intended if one of the headers needed for
   it has been »#include«d.

   The operator »!« and the if-statement do not require
   any »#include«.



I certainly wouldn't adjust my coding style to avoid #include'ing the 
definition of NULL.


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


Re: Invoking return through a function?

2017-10-29 Thread Ned Batchelder

On 10/29/17 10:18 AM, Alberto Riva wrote:

Hello,

I'm wondering if there is a way of writing a function that causes a 
return from the function that called it. To explain with an example, 
let's say that I want to exit my function if a dict does not contain a 
given key. I could write:


def testFun():
  ...
  if key not in dict:
    return
  ...

But if this is a test I need to do a lot of times, I'd like to replace 
it with something shorter and more explicit:


def testFun():
  ...
  checkKey(dict, key)
  ...

and I'd like checkKey to cause a return *from testFun*. In a language 
like Lisp this would be accomplished by defining checkKey as a macro 
that expands into the code shown in my first example, so that the 
return would be inside testFun and not insted checkKey. Is there a way 
of doing something like this in Python?


Another way of phrasing my question is: is there a way to cause a 
return from a function that is higher up in the call stack, rather 
than the currently active one, without using try/except?




No, there isn't.

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


Re: Invoking return through a function?

2017-10-29 Thread Ned Batchelder

On 10/29/17 3:09 PM, Alberto Riva wrote:

On 10/29/2017 02:13 PM, Rick Johnson wrote:

Alberto Riva wrote:

Rick Johnson wrote:

Alberto Riva wrote:


[...]

In a language like Lisp


Python is nothing like Lisp, and for good reason!


I would disagree with this. Actually, it's the most Lisp-
like language I've encountered in my 25 years of writing
software.


Really? I'm sorry that you have only encountered a few
"academic languages". Do some googling, there are literally
thousands of them in the wilds.


I'm sorry, I'm not sure I understand what you mean. I've been exposed 
to quite a few programming languages over the years, and my personal 
assessment (based on the features I consider important from my own 
personal point of view) is that Python is the closest to Lisp of the 
ones that I would consider using. It's definitely closer to Lisp than 
C, or Java, wouldn't you agree? I don't see where you get the idea 
that I was only exposed to "academic languages".


You don't have to respond to Rick.  He specializes in sarcasm and 
sneering.  He usually goes by "Ranting Rick."  This has been fairly tame 
for his postings, but it still doesn't require a response :)


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


Re: How to join elements at the beginning and end of the list

2017-10-31 Thread Ned Batchelder

On 10/31/17 11:29 AM, Neil Cerutti wrote:

On 2017-10-31, Ganesh Pal  wrote:

Here is my solution


values = '||' + '||'.join(map(str, value_list)) + '||'
values

'||1||2||3||4||56||s||'

I am joining the elements at the beginning and end of the list
using '+' operator any other solution, this is not looking
neater

I am a Linux user using python 2.7

You can use the % operator instead of +, and a generator
expression instead of map. It's a pretty small improvement,
though.

values = '||%s||' % ('||'.join(str(s) for s in value_list))

At least... I THINK you can use that generator expression in 2.7.



However you solve it, do yourself a favor and write a function to 
encapsulate it:


    def wrapped_join(values, sep):
    """Join values with sep, and also include sep at the ends."""
    return "{sep}{vals}{sep}".format(sep=sep, vals=sep.join(str(v) 
for v in values))


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


Re: How to join elements at the beginning and end of the list

2017-10-31 Thread Ned Batchelder

On 10/31/17 12:29 PM, Stefan Ram wrote:

Ned Batchelder  writes:

However you solve it, do yourself a favor and write a function to
encapsulate it:

   It is always a good solution to encapsulate a pattern into
   a function. So I agree that this is a good suggestion. But
   just for the sole sake of information, I'd like to add that
   this is also the slowest solution so far (about 10.76 usec).

   This might be a case where macros would be fine. As readable
   as a function call, but no runtime-overhead. One can write

value_list =  [1, 2, 3, 4, 56, 's']

#define JOIN_WRAPPED(list,string) \
string + string.join(map(str,list)) + string

values = JOIN_WRAPPED(value_list,'||')

print( values )

   and save it as »source.c« and execute it using

gcc -E source.c -o source.py
python source.py

   . This is also not intended to be a recommendation.



I try to avoid micro-optimization.  My guess is that right after calling 
wrapped_join(), the result will be written to an I/O device of some 
kind.  If that is so, the time spent in wrapped_join will be irrelevant.


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


Re: The syntax of replacement fields in format strings

2017-11-01 Thread Ned Batchelder

On 10/31/17 12:45 PM, John Smith wrote:

If we keep the current implementation as is, perhaps the documentation
should at least be altered ?


John, it looks like you are responding to a Python-Dev message, but on 
this list, somehow...


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


Re: Code Snippets

2017-11-01 Thread Ned Batchelder

On 11/1/17 1:25 PM, Stefan Ram wrote:

   I started to collect some code snippets:

   Sleep one second

__import__( "time" ).sleep( 1 )

   Get current directory

__import__( "os" ).getcwd()

   Get a random number

__import__( "random" ).random()

   And so on. You get the idea.

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

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

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

   Sleep one second

import time
...
time.sleep( 1 )

   Get current directory

import os
...
os.getcwd()

   Get a random number

import random
...
random.random()

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



You should not optimize for the shortest time to paste a line of code.  
You should take time and care writing your code, so that it reads best 
and runs best.  If you needed another os function, would you have two 
__import__("os") in your code? Ugh.


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


Re: Report on non-breaking spaces in posts

2017-11-01 Thread Ned Batchelder

On 10/31/17 1:23 PM, Stefan Ram wrote:

   Ok, here's a report on me seing non-breaking spaces in
   posts in this NG. I have written this report so that you
   can see that it's not my newsreader that is converting
   something, because there is no newsreader involved.


You've worded this as if 1) non-breaking spaces are a problem, 2) you've 
reported them before, and 3) someone has claimed that it is your 
newsreader at fault.  Have I missed a previous discussion?


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


String changing size on failure?

2017-11-01 Thread Ned Batchelder

From David Beazley (https://twitter.com/dabeaz/status/925787482515533830):

>>> a = 'n'
>>> b = 'ñ'
>>> sys.getsizeof(a)
   50
>>> sys.getsizeof(b)
   74
>>> float(b)
   Traceback (most recent call last):
  File "", line 1, in 
   ValueError: could not convert string to float: 'ñ'
>>> sys.getsizeof(b)
   77

Huh?

--Ned.

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


Re: String changing size on failure?

2017-11-01 Thread Ned Batchelder

On 11/1/17 4:17 PM, MRAB wrote:

On 2017-11-01 19:26, Ned Batchelder wrote:
  From David Beazley 
(https://twitter.com/dabeaz/status/925787482515533830):


  >>> a = 'n'
  >>> b = 'ñ'
  >>> sys.getsizeof(a)
 50
  >>> sys.getsizeof(b)
 74
  >>> float(b)
 Traceback (most recent call last):
    File "", line 1, in 
 ValueError: could not convert string to float: 'ñ'
  >>> sys.getsizeof(b)
 77

Huh?


It's all explained in PEP 393.

It's creating an additional representation (UTF-8 + zero-byte 
terminator) of the value and is caching that, so there'll then be the 
bytes for 'ñ' and the bytes for the UTF-8 (0xC3 0xB1 0x00).


When the string is ASCII, the bytes of the UTF-8 representation is 
identical to those or the original string, so it can share them.


That explains why b is larger than a to begin with, but it doesn't 
explain why float(b) is changing the size of b.


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


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

2017-11-01 Thread Ned Batchelder

On 11/1/17 5:12 PM, Alexey Muranov wrote:

Hello,

what do you think about the idea of replacing "`else`" with "`then`" 
in the contexts of `for` and `try`?


It seems clear that it should be rather "then" than "else." Compare 
also "try ... then ... finally" with "try ... else ... finally".


Currently, with "else", it is almost impossible to guess the meaning 
without looking into the documentation.


Off course, it should not be changed in Python 3, maybe in Python 4 or 
5, but in Python 3 `then` could be an alias of `else` in these contexts.


Alexey.



Apart from the questions of backward compatibility etc (Python is 
unlikely to ever go through another shift like the 2/3 breakage), are 
you sure "then" is what you mean?  This won't print "end":


    for i in range(10):
    print(i)
    else:
    print(end)

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


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

2017-11-01 Thread Ned Batchelder

On 11/1/17 5:29 PM, Chris Angelico wrote:

On Thu, Nov 2, 2017 at 8:23 AM, Ned Batchelder  wrote:

On 11/1/17 5:12 PM, Alexey Muranov wrote:

Hello,

what do you think about the idea of replacing "`else`" with "`then`" in
the contexts of `for` and `try`?

It seems clear that it should be rather "then" than "else." Compare also
"try ... then ... finally" with "try ... else ... finally".

Currently, with "else", it is almost impossible to guess the meaning
without looking into the documentation.

Off course, it should not be changed in Python 3, maybe in Python 4 or 5,
but in Python 3 `then` could be an alias of `else` in these contexts.

Alexey.


Apart from the questions of backward compatibility etc (Python is unlikely
to ever go through another shift like the 2/3 breakage), are you sure "then"
is what you mean?  This won't print "end":

 for i in range(10):
 print(i)
 else:
 print(end)

Well, it'll bomb with NameError when it tries to look up the *name*
end. But it will run that line of code - if you quote it, it will
work.

ChrisA


Naturally, I messed up on both a shallow and deep level! :) Or should I 
say derp level... :)


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


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

2017-11-06 Thread Ned Batchelder

On 11/6/17 8:05 AM, Jon Ribbens wrote:

On 2017-11-06, Chris Angelico  wrote:

If you start with the assumption that "intuitively obvious" doesn't
actually mean "intuitively obvious" but actually means something
completely different, then your statement definitely means something
non-contradictory. But if you start with the assumption that
"intuitively obvious" really does mean that the purpose and meaning of
for-else can be understood easily without external information, then
your statement contradicts itself.

I didn't say that 'for...else' was inherently "intutively obvious".
In fact I said the opposite of that. I said that *if* you start from
the right premise then it *becomes* intuitively obvious.


This is comp.lang.python, not alt.english.remedial, so we expect you
to use English competently, or at least accept correction when you
misuse words.

I'm glad your expectations are being met then. You might want to work
on also reading English competently, and then everyone will be happy!


As I said, I've provided a solution to the problem, what more
do you want? This feels very much like you're arguing for
argument's sake, which is a game I'm not willing to play along
with for much longer.

Except that you haven't. Your proposed solution is incorrect and false.

Yes, your logical argument there as to why is undeniable. I must admit
that your little gang's assertion that I'm foolish and mistaken because
I find Python's syntax simple to understand and you find it hard to
understand seems a little contradictory.


Ugh, can't we all just give each other the benefit of the doubt, and use 
the principle of charity?  It's easy to miscommunicate in a purely 
textual medium.   Everyone just take your foot off the "i'm right and 
you're wrong" gas pedal for moment.


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


Re: Ideas about how software should behave

2017-11-07 Thread Ned Batchelder

On 11/7/17 5:48 PM, Ben Finney wrote:

Ian Kelly  writes:


Nowadays I realize and accept that this is preposterous. You cannot
criticize an idea without also criticizing the people who are attached
to that idea.

Maybe so. Does that mean we must not criticise ideas? Later in your
message you say no, but everything leading up to it argues you think so.

In the thread which spawned this one, an idea was criticised, *because*
someone expressed attachment to the idea.

The idea was expressly one about software behaviour. Should that idea
not be criticised in this forum, because someone expressed attachment to
the idea?

Does this forum allow ideas to be criticised only if no-one is attached
to them?


Even if no personal slight is intended, it is received that way. If
your idea is bad, then by implication you are a person with bad ideas.

Yes. And people with bad ideas rarely abandon bad ideas if those ideas
are not shown to be bad.


Now, I'm not saying that we can't criticize ideas. We can, however,
choose to be polite or not in how we go about it.

Certainly. It is incivil to make personal attacks. The criticism which
started this sub-thread made no personal attack.

Yet you've already pointed out that criticism of an idea – an idea
specifically about how software should behave – is *perceived as* an
attack, by people who are attached to the idea.

You called such criticism “incivility”; presumably on the basis that the
person was attached to the idea that was criticised.

By responding, in this forum, to criticism of ideas with the
admonishment of “incivility”, you effectively imply that it is incivil
to criticise ideas strongly held — even when those ideas are about the
behaviour of Python software, in a forum whose purpose is discussion of
Python software.

This is the condescension of low expectation: that someone who is
attached to an idea deserves *less respect*, that they should not be
exposed to criticism of ideas they hold lest they perceive it as an
attack. That treats people as too fragile to examine an idea as separate
from their person.

I thoroughly reject that condescending attitude, and choose instead to
promote respect that people *can* examine ideas when those ideas are
criticised.

Ideas, whether lightly or strongly held, are never immune from
criticism. Indeed, for the purpose of reducing the amount of bad ideas
held by people, those ideas must be criticised.

Ideas about software behaviour, in this forum, are surely not an
exception to that.



All of this could have been avoided.  Steve called an idea arrogant. Jon 
felt that Steve was calling him arrogant. If Steve had simply said, "I'm 
sorry, I didn't mean that to apply to you," we wouldn't be here now. Why 
is it so hard to treat people as if they mattered?


People are so caught up in proving others wrong and themselves right, 
that just saying, "Sorry, I wasn't clear" feels like giving ground.


We need more civil discussion, and less sniping.  We're better than this.

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


Re: Ideas about how software should behave

2017-11-08 Thread Ned Batchelder

On 11/8/17 5:22 PM, Ben Finney wrote:

Jon Ribbens  writes:


On 2017-11-08, Ben Finney  wrote:

I also think Jon had cause to bristle somewhat at the characterisation.
I don't think Jon was attacked by Steve's remark, but I do sympathise
with the instinct to feel a criticism as an attack.

Steve called me arrogant, that's an attack

To say that someone is being arrogant simply is not an attack, and I
really want you to see that.

Ben, this idea is really stupid!

Be honest: when you read what I just wrote, did you feel a dispassionate 
discussion starting, or did you feel a bit attacked?


I think it is unrealistic to expect people to be completely dissociated 
from the ideas they hold.


Second, now you want us to agree that calling someone arrogant isn't an 
attack?  Perhaps you are able to discuss your own behavior this way, but 
I assure you, most people are not.  You are holding up this kind of 
distance from yourself as an ideal we should all strive for.  To me it 
seems like a Dr.-Spock-like separation from feelings.  People don't work 
this way.


How many paragraphs of close parsing are we going to twist ourselves 
through, just to avoid saying, "Yeah, sorry, that went a bit far.  I 
didn't want to alienate you in the pursuit of a demonstration of my own 
correctness."


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


Re: Ideas about how software should behave

2017-11-10 Thread Ned Batchelder

On 11/8/17 3:05 PM, Marko Rauhamaa wrote:

Jon Ribbens :

It is my experience of this group/list that if one disagrees with any
of you, Steve and Chris, you all rally round and gang up on that
person to insult and belittle them. This makes the atmosphere quite
hostile, and it would be quite remarkable if it isn't hurting the
community by driving people away. Please stop doing it.

This forum is about a dead thing, a programming language. I wouldn't
make too big a deal about "the community."

If someone's postings constantly frustrate you, simply place them in
your killfile. I've done that to people. People have done that to me.




Tolerating bad behavior and advising people to cope by kill-filing is 
terrible advice. It means the bad behavior continues, unseen by 
regulars, and newcomers find a place rife with muck, unaddressed. Use a 
kill file if you like, but that is not the way the group as a whole is 
going to deal with it.


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


Re: Ideas about how software should behave

2017-11-10 Thread Ned Batchelder

On 11/8/17 10:18 PM, Ben Finney wrote:

How many paragraphs of close parsing are we going to twist ourselves
through, just to avoid saying, "Yeah, sorry, that went a bit far.  I
didn't want to alienate you in the pursuit of a demonstration of my
own correctness."

I don't have any aim of avoiding that. If I need to apologise for
something, that hasn't been made clear to me. If you're seeking an
apology from someone else, I can't do it for them.


You have nothing to apologize for.  This started because of an exchange 
between Steve and Jon.  Steve has been notably silent during the ensuing 
discussion.


What has been made clear to me is that we have a long way to go in
pursuit of allowing ideas to be held at arm's length, discussed and
criticised, with respect and compassion for one another.


Indeed.  Beyond just respect and compassion, this discussion has 
mentioned "changing people's minds" a few times.  How's that going? 
Calling an idea "arrogant" may or may not be reasonable (I'm divided on 
this question myself).  But is it an effective way to change the 
person's mind?  It's a great term to use if you want to smack someone 
down, and convince everyone else that you are right.  But it's going to 
put the other person on the defensive, and you've lost your chance to 
change their mind.


Both of the terms that have been brought up recently ("arrogant" and 
"moronic") seem ineffective to me.  If the goal truly is to engage in a 
discussion that will bring everyone to a point of agreement, then we 
have to choose words more wisely.  These words seem to me to have been 
chosen with a different goal.


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


Re: Ideas about how software should behave

2017-11-10 Thread Ned Batchelder

On 11/10/17 6:03 PM, Ben Finney wrote:

Ned Batchelder  writes:


On 11/8/17 10:18 PM, Ben Finney wrote:

What has been made clear to me is that we have a long way to go in
pursuit of allowing ideas to be held at arm's length, discussed and
criticised, with respect and compassion for one another.

Indeed.  Beyond just respect and compassion, this discussion has
mentioned "changing people's minds" a few times.  How's that going?

Impressively well, in my opinion.


It seems to me that Steve has not changed Jon's mind at all. Abrasive 
words don't change people's minds.


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


Re: How to modify this from Python 2.x to v3.4?

2017-11-11 Thread Ned Batchelder

On 11/11/17 6:56 AM, jf...@ms4.hinet.net wrote:

I learned python start from using v3.4 and never has any v2.x experience. There is a Pypi 
project "ctypesgen" I like to use, but it seems is for v2.x. (un)Fortunately I 
found one of its branch on github which announced is for Python3, but strangely it still 
use some v2.x words, for example, print. Its last update was at July 2009, maybe at the 
early age of v3? The one below which I can't figure out how to modify. Can someone show 
me the answer? (I don't want to spend time on learning the old history:-)

-
# Available instance types.  This is used when lexers are defined by a class.
# It's a little funky because I want to preserve backwards compatibility
# with Python 2.0 where types.ObjectType is undefined.

try:
_INSTANCETYPE = (types.InstanceType, types.ObjectType)
except AttributeError:
_INSTANCETYPE = types.InstanceType
class object: pass   # Note: needed if no new-style classes present
...
...
...
 if module:
 # User supplied a module object.
 if isinstance(module, types.ModuleType):
 ldict = module.__dict__
 elif isinstance(module, _INSTANCETYPE):
 _items = [(k,getattr(module,k)) for k in dir(module)]



This looks like fairly advanced code.  It will be difficult to port to 
Python 3 *without* understanding some of the old history.  There seem to 
be forks on GitHub, including one with a pull request about Python 3 
made in the last few days: 
https://github.com/davidjamesca/ctypesgen/pull/58 .  I'd recommend 
working with others on this.


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


Re: from xx import yy

2017-11-12 Thread Ned Batchelder

On 11/12/17 9:17 PM, bvdp wrote:

I'm having a conceptual mind-fart today. I just modified a bunch of code to use 
"from xx import variable" when variable is a global in xx.py. But, when I 
change/read 'variable' it doesn't appear to change. I've written a bit of code to show 
the problem:

mod1.py
myvar = 99
def setvar(x):
 global myvar
 myvar = x

test1.py
import mod1
mod1.myvar = 44
print (mod1.myvar)
mod1.setvar(33)
print (mod1.myvar)


In this case "mod1" is a name in test1 that refers to the mod1 module.  
You can access and assign attributes on that module. Anyone else 
referencing that module (including the module itself) will see those 
changed attributes.

If this test1.py is run myvar is fine. But, if I run:

test2.py
from mod1 import myvar, setvar
myvar = 44
print (myvar)
setvar(33)
print (myvar)

It doesn't print the '33'.


In this case, "myvar" is a name that references the same value as 
mod1.myvar.  Now both myvar and mod1.myvar refer to the same value. 
There is no direct connection between the myvar name and the mod1.myvar 
name.  When you reassign myvar, it now refers to some other value. 
mod1.myvar is unaffected.


--Ned.

I thought (apparently incorrectly) that import as would import the name myvar 
into the current module's namespace where it could be read by functions in the 
module



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


Re: Should constants be introduced to Python?

2017-11-16 Thread Ned Batchelder

On 11/16/17 1:16 AM, Saeed Baig wrote:

Hey guys I am thinking of perhaps writing a PEP to introduce constants to 
Python. Something along the lines of Swift’s “let” syntax (e.g. “let pi = 
3.14”).

Since I’m sort of new to this, I just wanted to ask:
- Has a PEP for this already been written? If so, where can I find the 
link/info to it?
- Do you guys think it would be a good idea? Why or why not? Do you think 
there’s a better way to do it? I’d like to know what others think about this 
idea before making any formal submission.


I don't know if a PEP like this has been attempted before.  They are all 
in one place (https://github.com/python/peps/), so it's not hard to find 
out.


But talking about it here first will be a good way to flesh out your 
ideas, hear the most likely objections, and so forth.


Start by telling us: Why should Python have constants?  Be specific: 
what current problems would it solve?


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


Re: How to Generate dynamic HTML Report using Python

2017-11-19 Thread Ned Batchelder

On 11/19/17 8:40 PM, Stefan Ram wrote:

mradul dhakad  writes:

I am new to python . I am trying to generate Dynamic HTML report using
Pyhton based on number of rows selected from query .Do any one can suggest
some thing for it.

   main.py

import sqlite3
conn = sqlite3.connect( ':memory:' )
c = conn.cursor()
c.execute( "CREATE TABLE T ( A TEXT )" )
c.execute( "INSERT INTO T ( A ) VALUES ( '1' ), ( '2' )" )
conn.commit()
c.execute( "SELECT * FROM T WHERE A = '1'" )
number_of_rows_selected_from_query = len( c.fetchall() )
conn.close()
del c
del conn
del sqlite3


I'm curious what superstition compels you to delete these names? There's 
no need to.


Also, why set headers that prevent the Python-List mailing list from 
archiving your messages?


--Ned.


def HTML( x ):
 return f'''
 http://www.w3.org/1999/xhtml"; lang="de" xml:lang="de">
 
 Number Of Rows Selected From Query
 Number Of Rows Selected From Query
 The number of rows selected from query is {x}.'''

print( HTML( number_of_rows_selected_from_query ))

   transcript

 
 http://www.w3.org/1999/xhtml"; lang="de" xml:lang="de">
 
 Number Of Rows Selected From Query
 Number Of Rows Selected From Query
 The number of rows selected from query is 1.



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


Re: How to Generate dynamic HTML Report using Python

2017-11-21 Thread Ned Batchelder

On 11/20/17 9:50 AM, Stefan Ram wrote:

Ned Batchelder  writes:

Also, why set headers that prevent the Python-List mailing list from
archiving your messages?

   I am posting to a Usenet newsgroup. I am not aware of any
   "Python-List mailing list".

   I am posting specifically to the Usenet, because I am aware
   of it's rules and I like it and wish to support it.

   I do not post to a "mailing list" because I do not know which
   rules apply for mailing lists and whether mailing lists in
   general or any specific mailing list is an environment that I
   like or wish to support.



The dual nature of this online community has long been confusing and 
complicated.  It's both a newsgroup and a mailing list.  Add in Google 
Groups, and you really have three different faces of the same content.


The fact is, posting to comp.lang.python means that your words are also 
being distributed as a mailing list. Because of your messages' headers, 
they are not in the archive of that list 
(https://mail.python.org/pipermail/python-list/2017-November/thread.html), 
or in Google Groups 
(https://groups.google.com/forum/#!topic/comp.lang.python/0ejrtZ6ET9g). 
It makes for odd reading via those channels.


I don't understand the motivation for limiting how words are 
distributed, but others on this list also do it. For example, Dennis Lee 
Bieber's messages are not in the Python-List archives either. If 
something is worth saying, why not let people find it later?


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


Re: Benefits of unicode identifiers (was: Allow additional separator in identifiers)

2017-11-24 Thread Ned Batchelder

On 11/24/17 5:26 PM, Richard Damon wrote:

Have you tried using U+2010 (HYPHEN) ‐. It is in the class 
XID_CONTINUE (in fact it is in XID_START) so should be available.


U+2010 isn't allowed in Python 3 identifiers.

The rules for identifiers are here: 
https://docs.python.org/3/reference/lexical_analysis.html#identifiers 
.   U+2010 is in category Pd 
(http://www.fileformat.info/info/unicode/char/2010), which isn't one of 
the categories allowed in identifiers.  Category Pc 
(http://www.fileformat.info/info/unicode/category/Pc/list.htm) is 
allowed, but it doesn't include anything that would look like a hyphen.


--Ned.


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


Re: Compile Python 3 interpreter to force 2-byte unicode

2017-11-25 Thread Ned Batchelder

On 11/25/17 5:05 PM, wojtek.m...@gmail.com wrote:

Hi, my goal is to obtain an interpreter that internally
uses UCS-2. Such a simple code should print 65535:

   import sys
   print sys.maxunicode

This is enabled in Windows, but I want the same in Linux.
What options have I pass to the configure script?



You say you want Python 3, but you also say you have maxunicode == 65535 
on Windows.  That must be Python 2.  Python 3 always has maxunicode == 
1114111.


Can you say more about what you need to do?

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


Re: I have framework on python with pyunit, facing below issue while executing test case

2017-11-27 Thread Ned Batchelder

On 11/27/17 8:13 AM, jaya.bir...@gmail.com wrote:

Please let me know anyone aware about the issue


Traceback (most recent call last):
File "testrunner.py", line 447, in 
testrunner_obj.main()
File "testrunner.py", line 433, in main
self.result()
File "testrunner.py", line 310, in result
result = runner.run(self.suite)
File "/auto/PyUnit/PyUnit-0.3/utils/framework/HTMLTestRunner.py", line 720, in 
run
test(result)
File "/usr/lib/python2.7/unittest/suite.py", line 70, in __call__
return self.run(*args, **kwds)
File "/usr/lib/python2.7/unittest/suite.py", line 108, in run
test(result)
File "/usr/lib/python2.7/unittest/suite.py", line 70, in __call__
return self.run(*args, **kwds)
File "/usr/lib/python2.7/unittest/suite.py", line 108, in run
test(result)
File "/usr/lib/python2.7/unittest/suite.py", line 70, in __call__
return self.run(*args, **kwds)
File "/usr/lib/python2.7/unittest/suite.py", line 100, in run
self._handleClassSetUp(test, result)
File "/usr/lib/python2.7/unittest/suite.py", line 153, in _handleClassSetUp
self._addClassOrModuleLevelException(result, e, errorName)
File "/usr/lib/python2.7/unittest/suite.py", line 198, in 
_addClassOrModuleLevelException
result.addError(error, sys.exc_info())
File “/auto/PyUnit/PyUnit-0.3/utils/framework/HTMLTestRunner.py", line 633, in 
addError
output = self.complete_output()
File “/autoPyUnit/PyUnit-0.3/utils/framework/HTMLTestRunner.py", line 591, in 
complete_output
return self.outputBuffer.getvalue()
AttributeError: '_TestResult' object has no attribute 'outputBuffer'


It's hard to say without seeing all your code, but I notice PyUnit 0.3 
in your traceback.  If that's the PyUnit I think it is, PyUnit 1.4.1 was 
released 16(!) years ago, and has been in the standard library as 
unittest since version 2.1.  Are you running ancient versions of your 
test infrastructure?


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


Re: While, If, Count Statements

2017-11-27 Thread Ned Batchelder

On 11/27/17 7:54 AM, Cai Gengyang wrote:

Input :

count = 0

if count < 5:
   print "Hello, I am an if statement and count is", count

while count < 10:
   print "Hello, I am a while and count is", count
   count += 1

Output :

Hello, I am an if statement and count is 0
Hello, I am a while and count is 0
Hello, I am a while and count is 1
Hello, I am a while and count is 2
Hello, I am a while and count is 3
Hello, I am a while and count is 4
Hello, I am a while and count is 5
Hello, I am a while and count is 6
Hello, I am a while and count is 7
Hello, I am a while and count is 8
Hello, I am a while and count is 9

The above input gives the output below. Why isn't the output instead :

Hello, I am an if statement and count is 0
Hello, I am a while and count is 0
Hello, I am an if statement and count is 1
Hello, I am a while and count is 1
Hello, I am an if statement and count is 2
Hello, I am a while and count is 2
Hello, I am an if statement and count is 3
Hello, I am a while and count is 3
Hello, I am an if statement and count is 4
Hello, I am a while and count is 4
Hello, I am a while and count is 5
Hello, I am a while and count is 6
Hello, I am a while and count is 7
Hello, I am a while and count is 8
Hello, I am a while and count is 9


It's easy to imagine that this sets up a rule that remains in effect for 
the rest of the program:


    if count < 5:
    print "Hello, I am an if statement and count is", count

But that's not how Python (and most other programming languages) works.  
Python reads statements one after another, and executes them as it 
encounters them.  When it finds the if-statement, it evaluates the 
condition, and if it is true *at that moment*, it executes the contained 
statements.  Then it forgets all about that if-statement, and moves on 
to the next statement.


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


Re: connect four (game)

2017-11-27 Thread Ned Batchelder

On 11/27/17 1:57 PM, bartc wrote:

On 27/11/2017 17:41, Chris Angelico wrote:

On Tue, Nov 28, 2017 at 2:14 AM, bartc  wrote:

JPEG uses lossy compression. The resulting recovered data is an
approximation of the original.


Ah but it is a perfect representation of the JPEG stream. Any given
compressed stream must always decode to the same output. The lossiness
is on the ENcoding, not the DEcoding.


You make it sound as bad as currency calculations where different 
software must produce results that always match to the nearest cent.


We're talking about perhaps +1 or -1 difference in the least 
significant bit of one channel of one pixels. If the calculation is 
consistent, then you will not know anything is amiss.


By +1 or -1, I mean compared with the same jpeg converted by 
independent means.


I also passed the same jpeg through another C program (not mine) using 
its own algorithms. There some pixels varied by up to +/- 9 from the 
others (looking at the first 512 bytes of the conversion to ppm).


Here's my test image: 
https://github.com/bartg/langs/blob/master/card2.jpg (nothing naughty).


Tell me what the definitive values of the pixels in this part of the 
image should be (I believe this corresponds to roughly the leftmost 
180 pixels of the top line; there are two million pixels in all). And 
tell me WHY you think those are the definitive ones.


Bear in mind also that this is not intended to be the world's most 
perfect software. But it does do a good enough job. And the other two 
Python versions I have, at the minute don't work at all.





Surely the details of JPEG decompression, and the possible presence of 
flaws in certain decoders, is beyond the scope of this thread?


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


Re: How to use a regexp here

2017-12-04 Thread Ned Batchelder

On 12/4/17 4:36 AM, Cecil Westerhof wrote:

I have a script that was running perfectly for some time. It uses:
 array = [elem for elem in output if 'CPU_TEMP' in elem]

But because output has changed, I have to check for CPU_TEMP at the
beginning of the line. What would be the best way to implement this?



No need for a regex just yet:

    array = [elem for elem in output if elem.startswith('CPU_TEMP')]

(btw, note that the result of this expression is a list, not an array, 
for future Googling.)


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


Re: How to use a regexp here

2017-12-04 Thread Ned Batchelder

On 12/4/17 9:13 AM, Rick Johnson wrote:

Perhaps it's not politically correct for me to say this, but
i've never been one who cared much about political
correctness, so i'm just going to say it...


Cecil, feel free to ignore the rest of Rick's message.  His messages are 
famous for their outrageous and/or abrasive tone, something he seems to 
revel in.  Luckily, it's not typical of the Python community.


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


Re: why won't slicing lists raise IndexError?

2017-12-04 Thread Ned Batchelder

On 12/4/17 8:03 PM, Rick Johnson wrote:

On Monday, December 4, 2017 at 6:13:19 PM UTC-6, Chris Angelico wrote:

[...]
 

Ahhh, I see how it is. You didn't run the code, ergo you
don't understand it. Makes perfect sense. :)

Being that Terry didn't offer any declarations or defintions
for his variables or functions, i assumed, i suppose, like
any other rational person, that it was all just pseudo code.

But, in any event, i don't see how running the code and then
watching helplessly as a volley of NameErrors come rip-
roaring down a stdout stream like a half naked, middle-aged
drunk feller bobbing precariously along a river rapid --
hey, look out for that rock! -- is going to help shed any
light on any of this.

But i suppose it's possible i missed an esoteric joke
somewhere...


Here are details filled in:

   $ python3.6
   Python 3.6.3 (default, Oct  4 2017, 06:03:25)
   [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
   Type "help", "copyright", "credits" or "license" for more information.
>>> def do_the_thing(seq, n):
   ... item = seq[n:n+1]
   ... if item:
   ... print(f"process({item})")
   ... else:
   ... print("do_without_item()")
   ...
>>> do_the_thing([1, 2, 3], 2)
   process([3])
>>> do_the_thing([1, 2, 3], 5)
   do_without_item()
>>>

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


Re: why won't slicing lists raise IndexError?

2017-12-04 Thread Ned Batchelder

On 12/4/17 9:31 PM, Rick Johnson wrote:

On Monday, December 4, 2017 at 7:47:20 PM UTC-6, Ned Batchelder wrote:

[...]
 

Here are details filled in:

 $ python3.6
 Python 3.6.3 (default, Oct  4 2017, 06:03:25)
 [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
 Type "help", "copyright", "credits" or "license" for more information.
  >>> def do_the_thing(seq, n):
 ... item = seq[n:n+1]
 ... if item:
 ... print(f"process({item})")
 ... else:
 ... print("do_without_item()")
 ...
  >>> do_the_thing([1, 2, 3], 2)
 process([3])
  >>> do_the_thing([1, 2, 3], 5)
 do_without_item()
  >>>

Thanks for filling in the blanks. However, my objection to
this else-clause stems from a perspective based in
pragmatics. Specifically, i see no benefit here in logging
the "non-action". Sure, perhaps logging a non-action may serve a
useful purpose during debugging sessions, but i find them to
be nothing but useless noise in production code.

Do you agree or disagree with my assessment?

If you disagree, please explain why.


The point of the example was to demonstrate what happens when slicing 
beyond the bounds of the list.  It's beyond the scope of the thread to 
debate whether you might want to perform an action in that case.  I 
think we've demonstrated the slicing semantics well.


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


Re: why won't slicing lists raise IndexError?

2017-12-05 Thread Ned Batchelder

On 12/4/17 10:41 PM, Rick Johnson wrote:

I think we've demonstrated the slicing semantics well.

Indeed. And i never questioned this aspect. I merely wanted
to inform the lurkers that the else-clause was handling a
non-action, and therefore, could be omitted.


Your original statement sounded like, "The else clause can never be 
executed," which would have been in direct opposition to the point, that 
slicing outside the limits would produce an empty list, not an 
exception.  I'm not sure why you are certain that there's never a reason 
to execute code in that case.


Perhaps I have a simulation on a conceptually infinite line, but only 
store the actual points needed.  The "non action" would be to extend the 
line.


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


Re: f-string

2017-12-05 Thread Ned Batchelder

On 12/5/17 7:16 PM, Steve D'Aprano wrote:

compile('f"{spam} {eggs}"', '', 'single')


   $ python3.6
   Python 3.6.3 (default, Oct  4 2017, 06:03:25)
   [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
   Type "help", "copyright", "credits" or "license" for more information.
>>> compile('f"{spam} {eggs}"', '', 'single')
at 0x105e79660, file "", line 1>
>>> co = _
>>> spam = 17
>>> eggs = 34
>>> eval(co)
   '17 34'
>>> dis.dis(co)
  1   0 LOAD_NAME    0 (spam)
  2 FORMAT_VALUE 0
  4 LOAD_CONST   0 (' ')
  6 LOAD_NAME    1 (eggs)
  8 FORMAT_VALUE 0
 10 BUILD_STRING 3
 12 PRINT_EXPR
 14 LOAD_CONST   1 (None)
 16 RETURN_VALUE


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


Re: why won't slicing lists raise IndexError?

2017-12-06 Thread Ned Batchelder
After a certain point, the only thing you can do with a troll is ignore 
them.


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


Re: Stackoverflow question: Is there a built-in identity function in Python?

2017-12-07 Thread Ned Batchelder

On 12/7/17 1:28 PM, Ethan Furman wrote:

The simple answer is No, and all the answers agree on that point.

It does beg the question of what an identity function is, though.

My contention is that an identity function is a do-nothing function 
that simply returns what it was given:


--> identity(1)
1

--> identity('spam')
'spam'

--> identity('spam', 'eggs', 7)
('spam', 'eggs', 7)


I don't see why this last case should hold.  Why does the function take 
more than one argument?  And if it does, then why doesn't it work like this?


    --> identity('spam')
    ('spam',)

(because then it wouldn't be an identity function!)  Trying to handle 
the multi-argument case seems like it adds an unneeded special case to 
the function.


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


Re: Stackoverflow question: Is there a built-in identity function in Python?

2017-12-07 Thread Ned Batchelder

On 12/7/17 2:41 PM, Ethan Furman wrote:

On 12/07/2017 11:23 AM, Ned Batchelder wrote:

On 12/7/17 1:28 PM, Ethan Furman wrote:



--> identity('spam', 'eggs', 7)
('spam', 'eggs', 7)


I don't see why this last case should hold.  Why does the function 
take more than one argument?  And if it does, then

why doesn't it work like this?

 --> identity('spam')
 ('spam',)

(because then it wouldn't be an identity function!)  Trying to handle 
the multi-argument case seems like it adds an

unneeded special case to the function.


--> a = 'spam'
--> a == neds_identity(a)
False



Right, but why does one argument return the argument, but n>1 returns a 
tuple of the args?


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


Re: why won't slicing lists raise IndexError?

2017-12-08 Thread Ned Batchelder

On 12/7/17 9:02 PM, Python wrote:

Can you please explain to me 


Really, you just have to ignore him.

--Ned.

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


Re: How to use a regexp here

2017-12-08 Thread Ned Batchelder
On 12/4/17 4:36 AM, Cecil Westerhof wrote:
> I have a script that was running perfectly for some time. It uses:
>  array = [elem for elem in output if 'CPU_TEMP' in elem]
>
> But because output has changed, I have to check for CPU_TEMP at the
> beginning of the line. What would be the best way to implement this?
>

No need for a regex just yet:

 â â â  array = [elem for elem in output if elem.startswith('CPU_TEMP')]

(btw, note that the result of this expression is a list, not an array, for
future Googling.)

--Ned.

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


Re: How to use a regexp here

2017-12-08 Thread Ned Batchelder
On 12/4/17 9:13 AM, Rick Johnson wrote:
> Perhaps it's not politically correct for me to say this, but
> i've never been one who cared much about political
> correctness, so i'm just going to say it...

Cecil, feel free to ignore the rest of Rick's message.â  His messages are
famous for their outrageous and/or abrasive tone, something he seems to revel
in.â  Luckily, it's not typical of the Python community.

--Ned.

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


Re: f-string

2017-12-08 Thread Ned Batchelder
On 12/5/17 7:16 PM, Steve D'Aprano wrote:
> compile('f"{spam} {eggs}"', '', 'single')

$ python3.6
Python 3.6.3 (default, Octâ  4 2017, 06:03:25)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> compile('f"{spam} {eggs}"', '', 'single')
 at 0x105e79660, file "", line 1>
 >>> co = _
 >>> spam = 17
 >>> eggs = 34
 >>> eval(co)
'17 34'
 >>> dis.dis(co)
 â  1â â â â â â â â â â  0 LOAD_NAMEâ â â â â â â â â â â â â â â  0
(spam)
 â â â â â â â â â â â â â  2 FORMAT_VALUEâ â â â â â â â â â â â  0
 â â â â â â â â â â â â â  4 LOAD_CONSTâ â â â â â â â â â â â â â  0 ('
')
 â â â â â â â â â â â â â  6 LOAD_NAMEâ â â â â â â â â â â â â â â  1
(eggs)
 â â â â â â â â â â â â â  8 FORMAT_VALUEâ â â â â â â â â â â â  0
 â â â â â â â â â â â â  10 BUILD_STRINGâ â â â â â â â â â â â  3
 â â â â â â â â â â â â  12 PRINT_EXPR
 â â â â â â â â â â â â  14 LOAD_CONSTâ â â â â â â â â â â â â â  1
(None)
 â â â â â â â â â â â â  16 RETURN_VALUE


--Ned.

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


Re: Automated distribution building tools to support SpamBayes

2017-12-15 Thread Ned Batchelder

On 12/15/17 2:03 PM, Skip Montanaro wrote:

SpamBayes (http://www.spambayes.org/) has languished for quite awhile,
in part because nobody is around who can put together a Windows
installer. Unfortunately, most users are on Windows and have to work
around problems caused by the march of time and consequent beefing up
of Windows security.

I don't do Windows, but I wonder... Can one of the various continuous
integration tools out there be enlisted to build Windows installers?
The SB code is written in Python, uses the Win32 extension, and is
hosted on GitHub (https://github.com/smontanaro/spambayes), so
something which plays nice with that environment would be a plus. I'm
slowly gaining familiarity at work with Bamboo (very, very slowly), so
the general idea of what CI tools can do is starting to sink in. Since
I'm a captive Atlassian customer at work, though, I don't know what
limitations I might encounter trying to use it in an open source
environment.

Any feedback appreciated. As this is only Python-related in the sense
that SpamBayes is written in Python, feel free to reply off-list.

Skip


I use AppVeyor CI to build Windows installers for coverage.py.  It's not 
straightforward though, there are Powershell scripts, etc. The config 
file is here: 
https://github.com/nedbat/coveragepy/blob/master/appveyor.yml with other 
necessities in the ci folder.


Hope that helps,

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


  1   2   3   4   5   6   7   8   9   >