Re: Compression of random binary data

2017-10-29 Thread Ian Kelly
On Oct 28, 2017 5:53 PM, "Chris Angelico"  wrote:
> One bit. It might send the message, or it might NOT send the message.

Not sending the message is equivalent to having a second possible message.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Compression of random binary data

2017-10-29 Thread Chris Angelico
On Sun, Oct 29, 2017 at 6:00 PM, Ian Kelly  wrote:
> On Oct 28, 2017 5:53 PM, "Chris Angelico"  wrote:
>> One bit. It might send the message, or it might NOT send the message.
>
> Not sending the message is equivalent to having a second possible message.

Okay, now we're getting seriously existential. Is a non-message a message?

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


Re: Problem with subprocess.Popen and EINTR

2017-10-29 Thread Piet van Oostrum
Cameron Simpson  writes:

[...]
>  What if you did this:
>
>  os.signal(SIGINT, SIG_IGN)
>  ... code code code, including the Popen/wait ...
>  old_handler = os.signal(SIGINT, do_nothing_handler)
>  sleep(...)
>  os.signal(SIGINT, old_handler)
>
> SIG_IGN is different from a do-nothing handler; it prevents the process
> seeing the signal at all, and therefore prevents the signal interrupting
> system calls.
>
> So you activate your dummy-quit-sleeping function only around the sleep 
> itself.

Thanks. That is a good idea. I'll try that out.
Or I could first try to switch to Python 3, as Chris suggested, to see if that 
makes the problem disappear.
-- 
Piet van Oostrum 
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Compression of random binary data

2017-10-29 Thread Gregory Ewing

Chris Angelico wrote:

One bit. It might send the message, or it might NOT send the message.


The entropy formula assumes that you are definitely
going to send one of the possible messages. If not
sending a message is a possibility, then you need
to include an empty message in the set of messages.

Another way to think about it: The receiver can be
in one of N possible states, and you want to ensure
that it's in a particular state. To do that, there
must be N possible messages that you can send.
If N = 1, the receiver is already in the right
state, so you don't need to send it a message at
all.

Example: If the message is "I love you", and your
SO already knows that, you don't need to tell
them. (Not according to information theory, at
least.)

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


Re: Coding style in CPython implementation

2017-10-29 Thread Στέφανος Σωφρονίου
On Sunday, October 29, 2017 at 4:18:38 AM UTC+2, Dan Sommers wrote:
> On Sat, 28 Oct 2017 16:20:54 -0700, Στέφανος Σωφρονίου wrote:
> 
> > I do believe though that if (!d) is a lot clearer than if (d == NULL)
> > as it is safer than falsely assigning NULL in d, by pure mistake.
> 
> Having made my living writing C code for a very long time, I always
> found if (!d) *harder* to read, especially if it happened to be written
> if(!d) without the space, because it was never a single character name
> the ! disappeared into the noise.

Indeed it gets harder to distinguish it after a lot of time staring at your 
source code.

I guess the following parts from "Zen of Python" apply to this case:

 - Beautiful is better than ugly.
 - Explicit is better than implicit.
 - Simple is better than complex.
 - Readability counts.

> OTOH, = vs. == always stuck out like
> a sore thumb.  Then again, I grew up with monochrome terminals
> vs. unusably slow syntax highlighting, and grayscale printers (and we
> had to live in a small shoebox in the middle of the road).
> 
> YMMV.  Obviously.
> 
> Dan

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


Re: Compression of random binary data

2017-10-29 Thread Steve D'Aprano
On Sun, 29 Oct 2017 02:31 pm, Gregory Ewing wrote:

> Steve D'Aprano wrote:
>> I don't think that's right. The entropy of a single message is a
>> well-defined quantity, formally called the self-information.
>> 
>> https://en.wikipedia.org/wiki/Self-information
> 
> True, but it still depends on knowing (or assuming) the
> probability of getting that particular message out of
> the set of all possible messages.

Indeed.


> This is *not* what danceswithnumbers did when he
> calculated the "entropy" of his example bit sequences.
> He didn't define the set they were drawn from or
> what their probabilities were.

I'm not defending or supporting Danceswithnumbers in his confusion. I'm just
pointing out that an entropy-like measure of information for individual
messages does exist, and people do often call it "entropy".



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Compression of random binary data

2017-10-29 Thread Steve D'Aprano
On Sun, 29 Oct 2017 06:03 pm, Chris Angelico wrote:

> On Sun, Oct 29, 2017 at 6:00 PM, Ian Kelly  wrote:
>> On Oct 28, 2017 5:53 PM, "Chris Angelico"  wrote:
>>> One bit. It might send the message, or it might NOT send the message.
>>
>> Not sending the message is equivalent to having a second possible message.
> 
> Okay, now we're getting seriously existential. Is a non-message a message?

Is zero a number?

Is bald a hair colour?

Is atheism a religion?

Aristotle seriously argued that the smallest whole number was two. Zero was
clearly nothing at all, and one wasn't a *number*, it was *unity*. A number
is, by definition, a multitude of units.

https://philosophy.stackexchange.com/questions/19533/why-does-aristotle-suggest-one-is-not-a-number

http://classics.mit.edu/Aristotle/metaphysics.14.xiv.html

No message can be a message. British nuclear submarines during the Cold War
had orders that if they failed to receive any transmissions from London
within a certain time period, they were to crack open the secret orders from
the Prime Minister. Nobody knows what is in the orders, as they were
destroyed when the PM left office, but they are popularly supposed to have
included:

- fire your missiles at Russia;

- surrender to whoever won the war;

- try to flee to Australia or New Zealand and join up with whatever remnants
  of the British Empire still exist;

- do whatever you want.

It makes a good, but ultimately futile, exercise to try to guess what the
various PMs would have said.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Repairing Python installation?

2017-10-29 Thread Martin Schöön
Den 2017-10-28 skrev Karsten Hilbert :
> On Sat, Oct 28, 2017 at 08:41:34PM +, Martin Schöön wrote:
>
>> It seems something is amiss with my Python 2.7 installation. Revisiting
>> Nikola (static web site generator written in Python) for the first time
>> in several years the other day I experience some unexpected problems. I
>> got some help form the Nikola people and the conclusion is something
>> is broken with my Python 2.7. Pip list throws exceptions at me
> ...
>> All this is happening on a Debian machine.
>
> Exceptions or crashes of the python interpreter ?
>
> Karsten

Exceptions. (Disclaimer: I am not a Python expert).

Today I tried pip --version and got the following:
/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py:1892:
UserWarning: /usr/lib/pymodules/python2.7/rpl-1.5.5.egg-info could not
be properly decoded in UTF-8
  warnings.warn(msg)

Reinstalling Python and pip makes no difference. pip3 --version throws
no warnings.

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


Re: Repairing Python installation?

2017-10-29 Thread Martin Schöön
Den 2017-10-28 skrev Percival John Hackworth :
> On 28-Oct-2017, Martin Schöön wrote
> (in article ):
>
>> It seems something is amiss with my Python 2.7 installation. Revisiting
>> Nikola (static web site generator written in Python) for the first time
>> in several years the other day I experience some unexpected problems. I
>> got some help form the Nikola people and the conclusion is something
>> is broken with my Python 2.7. Pip list throws exceptions at me while
>> pip3 list works the way I expect it to do.
>>

> If this site is accessible from the internet, have you looked around other 
> parts of the system? Like date/timestamps for /bin/*. I recently was asked to 
> look at a friends web site and found they were doing several things that I 
> consider a security no-no, like running the tomcat server as root to serve 
> their web site. It had been root-kitted. I helped them setup a new system 
> that ran tomcat under a non-priv user.
>


No web server is involved in this. Programs like Nikola takes pictures,
text files (Markdown, ReStructuredText...) + templates as input and
spits out html, css and sometimes javascript. Then it is up to you to
copy that result to a web server.

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


Re: sys.path[] question

2017-10-29 Thread Thomas Jollans
On 28/10/17 19:24, ElChino wrote:
> From the Python2.7 snippet in [1], Python2.7 reports that my
> sys.path[] contains:
>   f:\ProgramFiler\Python27\lib\site-packages\pyreadline-2.0-py2.7-win32.egg
> 
> (a .zip-file)
> 
> But I have also a 'f:\ProgramFiler\Python27\lib\site-packages\pyreadline'
> directory. With the complete package AFAICS.
> 
> So my question is where will Python import a 'import pyreadline' from?

Paths are searched in the order they're listed in sys.path.

You can find out where a module is loaded from by checking its __file__
attribute. Run python (in interactive mode) and execute

>>> import pyreadline
>>> pyreadline.__file__

> E.f. if I do a:
>   python -vv
> f:\ProgramFiler\Python27\lib\site-packages\pyreadline\test\test_lineeditor.py
> 
> 
> it shows a:
>   # zipimport: found 89 names in
> F:\ProgramFiler\Python27\lib\site-packages\pyreadline-2.0-py2.7-win32.egg
> But no other references to pyreadline-2.0-py2.7-win32.egg.
> 
> Does that mean that only this .egg is where python imports all pyreadline
> files from? And if so, can I delete
>   'f:\ProgramFiler\Python27\lib\site-packages\pyreadline' ?

This sounds like a fairly high risk of breaking something (presumably
there is some reason the files are where they are) for absolutely no
gain. It's not like it takes up any meaningful amount of space, is it?
Why would you want to?


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


Re: Repairing Python installation?

2017-10-29 Thread Chris Warrick
On 28 October 2017 at 22:41, Martin Schöön  wrote:
> It seems something is amiss with my Python 2.7 installation. Revisiting
> Nikola (static web site generator written in Python) for the first time
> in several years the other day I experience some unexpected problems. I
> got some help form the Nikola people and the conclusion is something
> is broken with my Python 2.7. Pip list throws exceptions at me while
> pip3 list works the way I expect it to do.
>
> All this is happening on a Debian machine.
>
> Questions:
>
> Should I try to pinpoint what is broken (and how is that done) or should
> I just remove everything Python 2.7 and re-install?
>
> Could mixing pip installs with Debian distro installs of Python
> packages lead to conflicts or other problems?

Yes, it does, you should avoid that at all cost. The best way to do it
is by using virtualenv.

> Today I tried pip --version and got the following:
> /usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py:1892:
> UserWarning: /usr/lib/pymodules/python2.7/rpl-1.5.5.egg-info could not
> be properly decoded in UTF-8
>   warnings.warn(msg)

That’s a warning, and it happens to be caused by the `rpl` apt
package. Remove it from your system and try `pip --version` again:
https://github.com/certbot/certbot/issues/3795

Now, onto fixing Nikola issues:

As discussed on IRC, Nikola recommends (and will soon require) Python
3. And you’ll be better off with a virtualenv: install `virtualenv`
from apt and follow the Getting started guide for Nikola:
https://getnikola.com/getting-started.html

If you still get unicode issues when compiling posts, make sure
they’re saved as UTF-8, and that your locale is configured properly:
https://chriswarrick.com/blog/2017/06/18/unix-locales-vs-unicode/

(Nikola’s co-maintainer over here.)

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sys.path[] question

2017-10-29 Thread ElChino

Thomas Jollans wrote:


You can find out where a module is loaded from by checking its __file__
attribute. Run python (in interactive mode) and execute


import pyreadline
pyreadline.__file__


Thanks for that tip.


Does that mean that only this .egg is where python imports all pyreadline
files from? And if so, can I delete
   'f:\ProgramFiler\Python27\lib\site-packages\pyreadline' ?


This sounds like a fairly high risk of breaking something (presumably
there is some reason the files are where they are) for absolutely no
gain. It's not like it takes up any meaningful amount of space, is it?
Why would you want to?


True, disk space is a few cents per Gigabyte. But maybe to reduce the
clutter on my disk and to keep things neat and simple.
I feel as a Python newbie, the file-structure / residue from various
package-installs clutters the 'Lib/site-packages' a great deal.
There is probably a tool to analyse "dead" Python package installs?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Compression of random binary data

2017-10-29 Thread Steve D'Aprano
On Sun, 29 Oct 2017 01:56 pm, Stefan Ram wrote:

>   If the entropy of an individual message is not defined,
>   than it is still available to be defined. I define it
>   to be log2(1/p), where p is the probability of this
>   message. I also choose a unit for it, which I call "bit".

That is exactly the definition of self-information:

https://en.wikipedia.org/wiki/Self-information

See also:

https://en.wikipedia.org/wiki/Entropy_(information_theory)

which lists several forms of related measures of information:

- the self-information of an individual message or symbol taken from a 
  given probability distribution;

- the entropy of a given probability distribution of messages or symbols;

- the entropy rate of a stochastic process.


It also suggests a connection between information entropy and thermodynamic
entropy, namely that the information entropy of a system is the amount of
additional information needed to determine the microstate of a system (the
states of all its particles), given the macrostate (identified by the bulk
thermodynamic parameters such as temperature, volume, energy).

More here: 

https://physics.stackexchange.com/questions/263197/is-information-entropy-the-same-as-thermodynamic-entropy




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Invoking return through a function?

2017-10-29 Thread Alberto Riva

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?


Thanks,

Alberto
--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
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 Steve D'Aprano
On Mon, 30 Oct 2017 01: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)
>...

You mean *less* explicit. "checkKey" gives absolutely no hint that it causes
the current function to return.


> 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?

Fortunately not.


> 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.

You really should re-think your strategy. Your suggestion, if possible, would
lead to difficult to maintain code where you couldn't easily tell where the
exit points of a function where. Imagine reading code like:


def foo(x):
a = sin(x)
b = cos(x)
print(a, b)
return a + b

There's one return, right? No. If Python could do what you are asking for,
*every function call* could be a hidden, secret return. What a nightmare that
would be.

It is bad enough that any function could raise an exception, but at least
exceptions halt the normal execution of code (unless explicitly caught). They
don't silently continue normal execution.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Coding style in CPython implementation

2017-10-29 Thread Rick Johnson
On Sunday, October 29, 2017 at 4:00:59 AM UTC-5, Στέφανος Σωφρονίου wrote:
[...]
> I guess the following parts from "Zen of Python" apply to this case:
> 
>  - Beautiful is better than ugly.
>  - Explicit is better than implicit.
>  - Simple is better than complex.
>  - Readability counts.

Now go acquaint yourself with the syntactical abomination
otherwise known as Type-hints, and you will understand that
all of the aforementioned "zens" are forgotten parts of
GvR's old testament. Design guidelines born of the ideals
enshrined in a governmental contract baiting scheme slickly
marketed as "cp4e" -- which were originally encoded on punch
cards and passed to Tim Peters during secret ceremony atop
the roof of CNRI building in Reston, Virgina, on the night
of the winter solstice. Now-a-days, Python's design
philosophy is less concerned with readability and focuses
itself primarily with corporate knob-gobbling.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread bartc

On 29/10/2017 14:35, Steve D'Aprano wrote:

On Mon, 30 Oct 2017 01:18 am, Alberto Riva wrote:



I'm wondering if there is a way of writing a function that causes a
return from the function that called it.



You really should re-think your strategy. Your suggestion, if possible, would
lead to difficult to maintain code where you couldn't easily tell where the
exit points of a function where. Imagine reading code like:


def foo(x):
 a = sin(x)
 b = cos(x)
 print(a, b)
 return a + b

There's one return, right? No. If Python could do what you are asking for,
*every function call* could be a hidden, secret return. What a nightmare that
would be.

It is bad enough that any function could raise an exception,


Don't exceptions do exactly the same thing as what the OP is proposing? 
Worse, actually.


That is, it could stop executing during any of the first three lines of 
foo(), and end up continuing execution in the caller, or in the caller's 
caller, and so on.



but at least
exceptions halt the normal execution of code (unless explicitly caught). They
don't silently continue normal execution.


I'm having trouble seeing the difference. If F calls G calls H, then H 
can arrange an exception to be picked up by F, bypassing normal return 
paths back to G and back to F.


And there's nothing G can do about it. At least, not without a lot of 
trouble, like wrapping try/except around every statement and 
sub-statement in G.


(What the OP wants was also proposed a few weeks back in comp.lang.c. 
But that was only within nested functions, so if H is inside G, and G is 
inside F, then a 'returnall' from H would return directly directly from 
F. Apparently Lisp allows this...)


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


Re: Compression of random binary data

2017-10-29 Thread Ben Bacarisse
Gregory Ewing  writes:

> Ben Bacarisse wrote:
>> But that has to be about the process that gives rise to the data, not
>> the data themselves.
>
>> If I say: "here is some random data..." you can't tell if it is or is
>> not from a random source.  I can, as a parlour trick, compress and
>> recover this "random data" because I chose it.
>
> Indeed. Another way to say it is that you can't conclude
> anything about the source from a sample size of one.
>
> If you have a large enough sample, then you can estimate
> a probability distribution, and calculate an entropy.
>
>> I think the argument that you can't compress arbitrary data is simpler
>> ...  it's obvious that it includes the results of previous
>> compressions.
>
> What? I don't see how "results of previous compressions" comes
> into it. The source has an entropy even if you're not doing
> compression at all.

Maybe we are taking at cross purposes.  A claim to be able to compress
arbitrary data leads immediately to the problem that iterating the
compression will yield zero-size results.  That, to me, is a simpler
argument that talking about data from a random source.

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


Re: Invoking return through a function?

2017-10-29 Thread Rick Johnson
On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, 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*. 

But under what exact _circumstances_? 

So, you'd like a call to `checkKey(...)` to cause a return
in `testFunc` when:

(1) the key exists?

(2) the key doesn't exist?

(3) the dict is actually a list?

(3) The call raises an exception?

(4) a seg fault occurs?

(5) GvR regains his sanity, self-respect and dignity by
86'ing type-hints?

Be more specific please. And _always_ refer to a named
function by _name_. Never use random or implicit aliases
(aka: "the function", "my function", etc...) in your prose.
Both functions *ARE* functions, dontchaknow?

> In a language like Lisp

Python is nothing like Lisp, and for good reason! Sure, we
have a few lispers and functional fanboys who hang around
here, and sometimes Rustom can get a little preachy about
FP, but mostly, we tolerate the fanboyism -- so long as it's
not rabid fanboyism.

> 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?

Thankfully, no. But i wouldn't underestimate the rebellious
nature of this generation of Py-dev'ers, and the propensity
of these folks to entertain feature creep.

> 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?

Possibly. But you've already poo-pooed the easy and obvious
solution of using conditional logic.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread Alberto Riva

On 10/29/2017 10:35 AM, Steve D'Aprano wrote:

On Mon, 30 Oct 2017 01: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)
...


You mean *less* explicit. "checkKey" gives absolutely no hint that it causes
the current function to return.


That's just because I used a name that was too generic in my example. I 
can call it "returnIfKeyMissing", and then it would be clear.



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?


Fortunately not.



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.

You really should re-think your strategy. Your suggestion, if possible, would
lead to difficult to maintain code where you couldn't easily tell where the
exit points of a function where. 


But again, it's just a naming problem. Something like returnIfKeyMissing 
would make it easy to tell where the exit points are. And as Bartc 
pointed out, we already have this situation with exceptions, so it would 
be nothing new. Indeed, what I'm asking for could be accomplished by 
wrapping the body of each function in a try/catch block for an ad-hoc 
exception type. But again, since the language doesn't have macros, this 
would have to be done manually in each function. I was just asking for a 
more convenient way to do it, being a lazy programmer :)



Imagine reading code like:

def foo(x):
 a = sin(x)
 b = cos(x)
 print(a, b)
 return a + b

There's one return, right? No. If Python could do what you are asking for,
*every function call* could be a hidden, secret return. What a nightmare that
would be.

It is bad enough that any function could raise an exception, but at least
exceptions halt the normal execution of code (unless explicitly caught). They
don't silently continue normal execution.


See above :)

Thanks,

Alberto


--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread Alberto Riva

On 10/29/2017 11:13 AM, bartc wrote:


(What the OP wants was also proposed a few weeks back in comp.lang.c. 
But that was only within nested functions, so if H is inside G, and G is 
inside F, then a 'returnall' from H would return directly directly from 
F. Apparently Lisp allows this...)


Well, not directly, but it can be simulated with the condition system 
(equivalent to try/except) or with throw/catch, which is similar but 
doesn't use exceptions.


But my point was that in Lisp you don't need to do this, because you can 
write a macro that expands into a return *in place*, without calling a 
separate function, and this eliminates the problem entirely. Since 
Python doesn't have macros I was looking for the next-best solution, but 
there doesn't seem to be one. Oh, well...


Thanks,

Alberto

--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread Alberto Riva

On 10/29/2017 12:21 PM, Rick Johnson wrote:

On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, 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*.


But under what exact _circumstances_?

So, you'd like a call to `checkKey(...)` to cause a return
in `testFunc` when:
 
 (1) the key exists?
 
 (2) the key doesn't exist?
 
 (3) the dict is actually a list?
 
 (3) The call raises an exception?
 
 (4) a seg fault occurs?
 
 (5) GvR regains his sanity, self-respect and dignity by

 86'ing type-hints?


In this specific case, I wanted to invoke a return if the key doesn't 
exist (as I wrote in my post). But this is not strictly relevant, my 
question was more general. To phrase it in yet another way: is there 
*any other way* to invoke return on a function, except by explicitly 
writing "return" in its body?



Be more specific please. And _always_ refer to a named
function by _name_. Never use random or implicit aliases
(aka: "the function", "my function", etc...) in your prose.
Both functions *ARE* functions, dontchaknow?


I do, but apparently everybody else was able to understand what I was 
asking... :)



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. It has closures, 
functions are first-class objects, it's interactive, highly reflective, 
variables are not strongly typed... The only big thing missing is 
macros, which are a direct result of the code-is-data feature of Lisp.



Sure, we
have a few lispers and functional fanboys who hang around
here, and sometimes Rustom can get a little preachy about
FP, but mostly, we tolerate the fanboyism -- so long as it's
not rabid fanboyism.


I don't consider myself a fanboy - I've used Lisp for most of my career, 
and now I happily use Python for 80% of what I do, even if it means 
putting up with the occasional limitation, as in this case.



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?


Thankfully, no.


Why "thankfully"? Having macros in Python would be great. Of course it's 
not possible because of the syntax, but it would be great nevertheless :)



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?


Possibly. But you've already poo-pooed the easy and obvious
solution of using conditional logic.


Not really. It's obvious that I'm going to use a conditional, I was just 
asking for a way to avoid having to type the same conditional over and 
over. Computers are meant to do work for you, after all, aren't they? :)


Alberto

--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list


Aw: Re: Invoking return through a function?

2017-10-29 Thread Karsten Hilbert
> In this specific case, I wanted to invoke a return if the key doesn't 
> exist (as I wrote in my post). But this is not strictly relevant, my 
> question was more general. To phrase it in yet another way: is there 
> *any other way* to invoke return on a function, except by explicitly 
> writing "return" in its body?

Sure: fall off the end of the function. But that's not what
you are after.

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


Re: Repairing Python installation?

2017-10-29 Thread Martin Schöön
Den 2017-10-29 skrev Chris Warrick :
> On 28 October 2017 at 22:41, Martin Schöön  wrote:

>>
>> Could mixing pip installs with Debian distro installs of Python
>> packages lead to conflicts or other problems?
>
> Yes, it does, you should avoid that at all cost. The best way to do it
> is by using virtualenv.
>
OK. Python virtualenv is new to me.
>
> Now, onto fixing Nikola issues:
>
> As discussed on IRC, Nikola recommends (and will soon require) Python
> 3. And you’ll be better off with a virtualenv: install `virtualenv`
> from apt and follow the Getting started guide for Nikola:
> https://getnikola.com/getting-started.html
>
I have installed Python 3 virtualenv and Nikola according to those
instructions. I now have a working Nikola but I sure don't know what
I am doing :-) How do I get back into that nikola python environment
next time?

I guess I need to do some reading.

> If you still get unicode issues when compiling posts, make sure
> they’re saved as UTF-8, and that your locale is configured properly:
> https://chriswarrick.com/blog/2017/06/18/unix-locales-vs-unicode/
>
The problem with locale went away when I changed DEFAULT_LANG from en to
sv in conf.py. 

pip list still throws exceptions at me but I have a plan. My secondary
computer has a very similar Debian installation. There are no Python
issues on that machine so I will do some comparative research.

Most gratefully,

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


Re: Repairing Python installation?

2017-10-29 Thread Chris Warrick
On 29 October 2017 at 18:11, Martin Schöön  wrote:
> I have installed Python 3 virtualenv and Nikola according to those
> instructions. I now have a working Nikola but I sure don't know what
> I am doing :-) How do I get back into that nikola python environment
> next time?

cd into your virtualenv directory and run `source bin/activate`.

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


django celery delay function dont exetute

2017-10-29 Thread Xristos Xristoou
hello I want to use celery tasks in my Django project and I try to follow this 
very good tutorial from Mr.Vitor Freitas.

but in my case and if try to run it that tutorial project i don't get results 
back the functions don't execute and in my case and in tutorial(i take message 
to wait and refresh and nothing after refresh).

Any idea Why ?

I think so the problem maybe is in RABBITQM server ?some configuration ?

Just install Erlang(otp_win64_20.1.exe) and after 
RabbitMQ(rabbitmq-server-3.6.12.exe)

here example code :

settings.py

CELERY_BROKER_URL = 'amqp://localhost'
celery.py

from __future__ import absolute_import
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

app = Celery('mysite')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
tasks.py

import string

from django.contrib.auth.models import User
from django.utils.crypto import get_random_string

from celery import shared_task


@shared_task
def create_random_user_accounts(total):
for i in range(total):
username = 'user_{}'.format(get_random_string(10, string.ascii_letters))
email = '{}@example.com'.format(username)
password = get_random_string(50)
User.objects.create_user(username=username, email=email, 
password=password)
return '{} random users created with success!'.format(total)
_ _init_ _.py

from .celery import app as celery_app

__all__ = ['celery_app']
views.py

from django.contrib.auth.models import User
from django.contrib import messages
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from django.views.generic.edit import FormView
from django.shortcuts import redirect

from .forms import GenerateRandomUserForm
from .tasks import create_random_user_accounts


class UsersListView(ListView):
template_name = 'core/users_list.html'
model = User


class GenerateRandomUserView(FormView):
template_name = 'core/generate_random_users.html'
form_class = GenerateRandomUserForm

def form_valid(self, form):
total = form.cleaned_data.get('total')
create_random_user_accounts.delay(total)
messages.success(self.request, 'We are generating your random users! 
Wait a moment and refresh this page.')
return redirect('users_list')
here details after cd my project path > celery -A mysite worker -l info :

C:\Windows\System32>cd C:\Users\username\Desktop\django-celery-example-master

C:\Users\username\Desktop\django-celery-example-master>celery -A mysite worker 
-l info

 -- celery@pc name v4.1.0 (latentcall)
  -
--- * ***  * -- Windows-8-6.2.9200 2017-10-29 18:10:24
-- * -  ---
- ** -- [config]
- ** -- .> app: mysite:0x404e5c0
- ** -- .> transport:   amqp://guest:**@localhost:5672//
- ** -- .> results: disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ***  .> task events: OFF (enable -E to monitor tasks in this worker)
--- * -
 -- [queues]
.> celery   exchange=celery(direct) key=celery


[tasks]
  . mysite.core.tasks.create_random_user_accounts

[2017-10-29 18:10:24,596: CRITICAL/MainProcess] Unrecoverable error: 
TypeError('must be integer, not _subprocess_handle',)
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\celery\worker\worker.py", line 203, in 
start
self.blueprint.start(self)
  File "C:\Python27\lib\site-packages\celery\bootsteps.py", line 119, in start
step.start(parent)
  File "C:\Python27\lib\site-packages\celery\bootsteps.py", line 370, in start
return self.obj.start()
  File "C:\Python27\lib\site-packages\celery\concurrency\base.py", line 131, in 
start
self.on_start()
  File "C:\Python27\lib\site-packages\celery\concurrency\prefork.py", line 112, 
in on_start
**self.options)
  File "C:\Python27\lib\site-packages\billiard\pool.py", line 1007, in __init__
self._create_worker_process(i)
  File "C:\Python27\lib\site-packages\billiard\pool.py", line 1116, in 
_create_worker_process
w.start()
  File "C:\Python27\lib\site-packages\billiard\process.py", line 124, in start
self._popen = self._Popen(self)
  File "C:\Python27\lib\site-packages\billiard\context.py", line 383, in _Popen
return Popen(process_obj)
  File "C:\Python27\lib\site-packages\billiard\popen_spawn_win32.py", line 64, 
in __init__
_winapi.CloseHandle(ht)
TypeError: must be integer, not _subprocess_handle
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\billiard\spawn.py", line 159, in 
spawn_main
new_handle = steal_handle(parent_pid, pipe_handle)
  File "C:\Python27\lib\site-packages\billiard\reduction.py", line 126, in 
steal_handle
_winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
WindowsError: [Error 6]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread Rick Johnson
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.

> It has closures, functions are first-class objects, it's
> interactive, highly reflective, variables are not strongly
> typed...

Congratulations. You've just described Ruby. And an apple-
cart full of other languages as well.

> I don't consider myself a fanboy - I've used Lisp for most
> of my career, and now I happily use Python for 80% of what
> I do, even if it means putting up with the occasional
> limitation, as in this case.

(not that i'm defending Python here...) but how do you know
that this so-called missing "feature" is a limitation? How
many other languages use this "feature"? And how many
programmers swear they could not live without it? We need
stats; hyperlinks; and eye witness testimonials. Heck, even
a random YouTube vid would be helpful.

> Why "thankfully"? Having macros in Python would be great.
> Of course it's not possible because of the syntax, but it
> would be great nevertheless :)

To me, macros would seem to violate Python's "explicit is
better than implicit" philosophy. But i admit, i'm something
of a zen purist on these matters. O:-) However, if you can
find a way to make macros Pythonic, hmm, i might be
interested...

> > Possibly. But you've already poo-pooed the easy and
> > obvious solution of using conditional logic.
> 
> Not really. It's obvious that I'm going to use a
> conditional, I was just asking for a way to avoid having to
> type the same conditional over and over. Computers are
> meant to do work for you, after all, aren't they? :)

A reasonable argument, i admit. But again, here in the
peaceful fields of "Pythonia", most of us feel that
"explicit is better than implicit". And why? Well, because
code is read more often than it is written, and as such,
explicit code will be of enormous help during the debugging
process. Sure, you may save yourself a few key-strokes with
features like macros, but at what cost? No action is without
consequences, dontchaknow?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Coding style in CPython implementation

2017-10-29 Thread Chris Angelico
On Mon, Oct 30, 2017 at 12:47 AM, Stefan Ram  wrote:
> =?UTF-8?B?zqPPhM6tz4bOsc69zr/PgiDOo8+Jz4bPgc6/zr3Or86/z4U=?= 
>  writes:
>>I guess the following parts from "Zen of Python" apply to this case:
>
>   If we would agree to apply Python rules to C,
>   then we could also use this excerpt from PEP 8:
>
> |o Don't compare boolean values to True or False using ==.
> |
> |Yes:   if greeting:
> |No:if greeting == True:
> |Worse: if greeting is True:

Or if we could agree to read PEP 7, there might be an example in
there. Granted, it might not be an explicit recommendation, merely a
tangential reference in a paragraph about braces, but it could be
indicative.

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


Re: Invoking return through a function?

2017-10-29 Thread Alberto Riva

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".



It has closures, functions are first-class objects, it's
interactive, highly reflective, variables are not strongly
typed...


Congratulations. You've just described Ruby. And an apple-
cart full of other languages as well.


OK, so? Does that invalidate my statement? And even if it did, that has 
almost nothing to do with my original question.



I don't consider myself a fanboy - I've used Lisp for most
of my career, and now I happily use Python for 80% of what
I do, even if it means putting up with the occasional
limitation, as in this case.


(not that i'm defending Python here...) but how do you know
that this so-called missing "feature" is a limitation? 


Because (again in my own personal opinion) Lisp macros are wonderful, 
they increase programmer productivity enormously, and not having them 
when I'm programming in other languages is a limitation from my point of 
view, since I enjoy using them so much.



How many other languages use this "feature"?


Almost none, unfortunately. So?


And how many
programmers swear they could not live without it? We need
stats; hyperlinks; and eye witness testimonials. Heck, even
a random YouTube vid would be helpful.


I don't see why. I'm just talking about something that I personally feel 
the need for, I'm not trying to convert anyone.



Why "thankfully"? Having macros in Python would be great.
Of course it's not possible because of the syntax, but it
would be great nevertheless :)


To me, macros would seem to violate Python's "explicit is
better than implicit" philosophy.


But that's exactly why I would like to be able to use macros. I think 
that being able to write "return if this happens" is much more explicit 
than having to write the full if statement, every time. The idea is that 
you abstract a pattern giving it a name, so every time you see that name 
you know immediately what's going to happen, without having to decode 
the conditional in your mind.



Possibly. But you've already poo-pooed the easy and
obvious solution of using conditional logic.


Not really. It's obvious that I'm going to use a
conditional, I was just asking for a way to avoid having to
type the same conditional over and over. Computers are
meant to do work for you, after all, aren't they? :)


A reasonable argument, i admit. But again, here in the
peaceful fields of "Pythonia", most of us feel that
"explicit is better than implicit". And why? Well, because
code is read more often than it is written, and as such,
explicit code will be of enormous help during the debugging
process. Sure, you may save yourself a few key-strokes with
features like macros, but at what cost? No action is without
consequences, dontchaknow?


I agree completely. Maybe we're using two different definitions of the 
word macro (I'm not sure how familiar you are with Lisp macros), but in 
my view their biggest advantage is that they make the code more readable 
and more explicit. And the issue of debugging is an orthogonal one, good 
development environments allow you to work on the original and the 
macro-expanded code equally easily.


Alberto

--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
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: Invoking return through a function?

2017-10-29 Thread bartc

On 29/10/2017 17:02, Alberto Riva wrote:

On 10/29/2017 12:21 PM, Rick Johnson wrote:


In this specific case, I wanted to invoke a return if the key doesn't 
exist (as I wrote in my post). But this is not strictly relevant, my 
question was more general. To phrase it in yet another way: is there 
*any other way* to invoke return on a function, except by explicitly 
writing "return" in its body?


The proposal seems flawed.

Suppose function F() calls G(), and G invokes a double return, not only 
from G but from F too.


That suggests that G knows something about how it's going to be called, 
and knows that doing so isn't going to cause a problem because F was in 
the middle of something that needs to be completed before it returns.


In general, a function like G() could be invoked from 100 different 
call-sites all in different circumstances. Furthermore, those call-sites 
may be in code called from yet 100 other locations.


(It may also be necessary to consider what happens when G() isn't called 
from a function. Or G calls itself recursively. Or G() appears in a 
'return' expression. Or deep within a nested expression. Or when F() is 
itself called from within an expression, and is expected to have a 
certain return value.)


This may be why the other proposal I mentioned used it within nested 
functions so at least adding some constraints.


It is true that Python has exceptions that can do similar things, but 
the clue there is in the word 'exception'. It does seem that a lot of 
code uses exceptions which are routinely triggered.


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


Re: Invoking return through a function?

2017-10-29 Thread Rick Johnson
Alberto Riva wrote:
> 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?

It depends on what metrics you use. Once you remove all the
type declarations from C and Java source, all three look very
similar, with Python being the "cleanest" syntax of all.
OTOH, when i look at Lisp, all i see is a language that was
designed for easy machine parsing, not for the human. But
that's just a syntactical comparison. Digging deeper, Python
and Java are both strongly typed. And with Python's
multi-paradigm nature, it is both equally useful in OOP (aka: Java)
or imperative (aka: C) style. Aside from static type checking and
some low level distractions, Python is very much like both of
these languages. In fact, i was familiar with both Java and
C before i ever became aware of Python. And the transition
felt very natural to me.

> I don't see where you get the idea that I was only exposed
> to "academic languages".

Just a lucky guess, i suppose.

> > > It has closures, functions are first-class objects, it's
> > > interactive, highly reflective, variables are not
> > > strongly typed...
> > 
> > Congratulations. You've just described Ruby. And an apple-
> > cart full of other languages as well.
> 
> OK, so? Does that invalidate my statement? And even if it
> did, that has almost nothing to do with my original
> question. 

But since your assertion of: "Python, like Lisp, has X,Y and
Z features in common" and furthermore that: "I cannot find
another language that has exactly these X, Y and Z
features", was used by you as a justification for this
feature request. That's why i had to attack it. Because it
was false.

> > > I don't consider myself a fanboy - I've used Lisp for
> > > most of my career, and now I happily use Python for 80%
> > > of what I do, even if it means putting up with the
> > > occasional limitation, as in this case.
> > 
> > (not that i'm defending Python here...) but how do you
> > know that this so-called missing "feature" is a
> > limitation?
> 
> Because (again in my own personal opinion) Lisp macros are
> wonderful, they increase programmer productivity
> enormously, and not having them when I'm programming in
> other languages is a limitation from my point of view,
> since I enjoy using them so much.

Well, i can understand your enthusiasm, i myself become
highly animated about certain topics (just ask my CO-EDs!).
But you also need to understand that i am person of
_reasoned_ principles. And i try not to violate my
principles just because some random peddler shows-up one day
on my front porch with a slick sales pitch for the next
generation of vacuum cleaners. My vacuum cleaner works just
fine, thank you very much, and until it stops working, or
until you convince me that purchasing a new vacuum will
bring me a good return on my investment, and, furthermore,
will not violate my beloved principles, then i will consider
your product. However, so far, your sales pitch and
demonstrasion have left much to be desired. And i i'm not
mistaken, i believe you machine missed a few Doritos crumbs
under that coffee table over there. Hmm...

> > How many other languages use this "feature"?
> 
> Almost none, unfortunately. So?

Which raises a red flag for me. If this feature is as great
as you say, then why has no other language adopted it? Are
macros a recent addition to Lisp? As in: "Yesterday"?

> > And how many programmers swear they could not live without
> > it? We need stats; hyperlinks; and eye witness
> > testimonials. Heck, even a random YouTube vid would be
> > helpful.
> 
> I don't see why. I'm just talking about something that I
> personally feel the need for, I'm not trying to convert
> anyone.

It would help us decide if the feature is worth adding. If
only one person, or a handful of people use a feature, then
what is the benefit of spending multiple hours writing,
debugging and maintaining it? Adding feature to a language
is a very risky process that should never be done
hastefully. Only after careful consideration, and majority
support from the community, should new feature be added.
Would you agree?

> > > Why "thankfully"? Having m

Re: Python-list Digest, Vol 169, Issue 44

2017-10-29 Thread Deught Chilapondwa
Sir, You have been sending me alot of messages but hardly can I understand.
Offcourse I registered with you, but I can't understand the messages
reharding what I should do.
Can you come back to me with clarification? Impatienly waiting to hear from
you.
Deught Chilapondwa.

On 25 Oct 2017 6:01 pm,  wrote:

> Send Python-list mailing list submissions to
> [email protected]
>
> To subscribe or unsubscribe via the World Wide Web, visit
> https://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
> [email protected]
>
> You can reach the person managing the list at
> [email protected]
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Python-list digest..."
>
> Today's Topics:
>
>1. Re: right list for SIGABRT python binary question ?
>   (M.-A. Lemburg)
>2. Re: Compression of random binary data (Stefan Ram)
>3. Re: Compression of random binary data (Peter J. Holzer)
>4. Re: Compression of random binary data (Peter Pearson)
>5. Re: Compression of random binary data (Ian Kelly)
>6. Re: Compression of random binary data (Steve D'Aprano)
>7. Re: Compression of random binary data (Steve D'Aprano)
>8. Re: Compression of random binary data (Chris Angelico)
>9. Re: Compression of random binary data (Richard Damon)
>   10. h5py.File() gives error message (C W)
>   11. Re: h5py.File() gives error message (Rob Gaddi)
>   12. Re: h5py.File() gives error message (Dennis Lee Bieber)
>   13. Re: h5py.File() gives error message (Dennis Lee Bieber)
>   14. Objects with __name__ attribute (ast)
>   15. Re: Objects with __name__ attribute (Peter Otten)
>   16. Re: h5py.File() gives error message (C W)
>   17. Re: Compression of random binary data (Gregory Ewing)
>   18. Re: Compression of random binary data (Gregory Ewing)
>   19. Re: Compression of random binary data (Gregory Ewing)
>   20. Re: Sockets but calling from different programs (Cameron Simpson)
>   21. Re: h5py.File() gives error message (Peter Otten)
>   22. Re: right list for SIGABRT python binary question ?
>   (Karsten Hilbert)
>   23. Let's talk about debuggers! (Thomas Jollans)
>   24. Re: Compression of random binary data (Ian Kelly)
>   25. Re: Let's talk about debuggers! (Fabien)
>   26. Re: h5py.File() gives error message (C W)
>   27. Re: Let's talk about debuggers! (Rustom Mody)
>   28. Re: Let's talk about debuggers! (Ned Batchelder)
>   29. Re: Let's talk about debuggers! (Michele Simionato)
>   30. Re: Let's talk about debuggers! (Bill)
>   31. Re: Compression of random binary data
>   ([email protected])
>   32. Re: Let's talk about debuggers! (William Ray Wing)
>   33. Test Bank for Campbell Biology 11th Edition by Urry, Cain
>   ([email protected])
>
>
> -- Forwarded message --
> From: "M.-A. Lemburg" 
> To: Karsten Hilbert , [email protected]
> Cc:
> Bcc:
> Date: Tue, 24 Oct 2017 20:47:58 +0200
> Subject: Re: right list for SIGABRT python binary question ?
>
>
> On 22.10.2017 22:15, Karsten Hilbert wrote:
> > On Sat, Oct 21, 2017 at 07:10:31PM +0200, M.-A. Lemburg wrote:
> >
> >>> Running a debug build of py27 gave me a first lead: this
> >>> Debian system (Testing, upgraded all the way from various
> >>> releases ago) carries an incompatible mxDateTime which I'll
> >>> take care of.
> >>>
> >>> *** You don't have the (right) mxDateTime binaries installed !
> >>> Traceback (most recent call last):
> >>>   File "./bootstrap_gm_db_system.py", line 87, in 
> >>> from Gnumed.pycommon import gmCfg2, gmPsql, gmPG2, gmTools,
> gmI18N
> >>>   File 
> >>> "/home/ncq/Projekte/gm-git/gnumed/gnumed/Gnumed/pycommon/gmPG2.py",
> line 34, in 
> >>> from Gnumed.pycommon import gmDateTime
> >>>   File 
> >>> "/home/ncq/Projekte/gm-git/gnumed/gnumed/Gnumed/pycommon/gmDateTime.py",
> line 52, in 
> >>> import mx.DateTime as mxDT
> >>>   File "/usr/lib/python2.7/dist-packages/mx/DateTime/__init__.py",
> line 8, in 
> >>> from DateTime import *
> >>>   File "/usr/lib/python2.7/dist-packages/mx/DateTime/DateTime.py",
> line 9, in 
> >>> from mxDateTime import *
> >>>   File 
> >>> "/usr/lib/python2.7/dist-packages/mx/DateTime/mxDateTime/__init__.py",
> line 13, in 
> >>> raise ImportError, why
> >>> ImportError: 
> >>> /usr/lib/python2.7/dist-packages/mx/DateTime/mxDateTime/mxDateTime.so:
> undefined symbol: Py_InitModule4
> >>
> >> This error suggests that you have 32- and 64-bit versions of
> >> Python and mxDateTime mixed in your installation.
> >>
> >> Py_InitModule4 is only available in the 32-bit build of
> >> Python. With the 64-bit build, it's called Py_InitModule4_64.
> >>
> >> Since you're getting the same error from faulthandler,
> >> this is where I'd start to investigate.
> >>
> >> "nm" will list all exported and required symbols. A

Listing link urls

2017-10-29 Thread Kishore Kumar Alajangi
Hi,

I am facing an issue with listing specific urls inside web page,

https://economictimes.indiatimes.com/archive.cms

Page contains link urls by year and month vise,
Ex: /archive/year-2001,month-1.cms

I am able to list all required urls using the below code,

from bs4 import BeautifulSoup
import re, csv
import urllib.request
import scrapy
req = urllib.request.Request('http://economictimes.indiatimes.com/archive.cms',
headers={'User-Agent': 'Mozilla/5.0'})


links = []
totalPosts = []
url = "http://economictimes.indiatimes.com";
data = urllib.request.urlopen(req).read()
page = BeautifulSoup(data,'html.parser')

for link in page.findAll('a', href = re.compile('^/archive/')):
//retrieving urls starts with "archive"
l = link.get('href')
links.append(url+l)


with open("output.txt", "a") as f:
 for post in links:
 post = post + '\n'
 f.write(post)

*sample result in text file:*

http://economictimes.indiatimes.com/archive/year-2001,month-1.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-2.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-3.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-4.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-5.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-6.cms


List of urls I am storing in a text file, From the month urls I want
to retrieve day urls starts with "/archivelist", I am using

the below code, but I am not getting any result, If I check with
inspect element the urls are available starting with /archivelist,



Kindly help me where I am doing wrong.

from bs4 import BeautifulSoup
import re, csv
import urllib.request
import scrapy

file = open("output.txt", "r")


for i in file:

urls = urllib.request.Request(i, headers={'User-Agent': 'Mozilla/5.0'})

data1 = urllib.request.urlopen(urls).read()

page1 = BeautifulSoup(data1, 'html.parser')

for link1 in page1.findAll(href = re.compile('^/archivelist/')):

l1 = link1.get('href')

print(l1)


Thanks,

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


Re: Listing link urls

2017-10-29 Thread Kishore Kumar Alajangi
+ tutor

On Sun, Oct 29, 2017 at 6:57 AM, Kishore Kumar Alajangi <
[email protected]> wrote:

> Hi,
>
> I am facing an issue with listing specific urls inside web page,
>
> https://economictimes.indiatimes.com/archive.cms
>
> Page contains link urls by year and month vise,
> Ex: /archive/year-2001,month-1.cms
>
> I am able to list all required urls using the below code,
>
> from bs4 import BeautifulSoup
> import re, csv
> import urllib.request
> import scrapy
> req = 
> urllib.request.Request('http://economictimes.indiatimes.com/archive.cms', 
> headers={'User-Agent': 'Mozilla/5.0'})
>
>
> links = []
> totalPosts = []
> url = "http://economictimes.indiatimes.com";
> data = urllib.request.urlopen(req).read()
> page = BeautifulSoup(data,'html.parser')
>
> for link in page.findAll('a', href = re.compile('^/archive/')): //retrieving 
> urls starts with "archive"
> l = link.get('href')
> links.append(url+l)
>
>
> with open("output.txt", "a") as f:
>  for post in links:
>  post = post + '\n'
>  f.write(post)
>
> *sample result in text file:*
>
> http://economictimes.indiatimes.com/archive/year-2001,month-1.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-2.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-3.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-4.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-5.cmshttp://economictimes.indiatimes.com/archive/year-2001,month-6.cms
>
>
> List of urls I am storing in a text file, From the month urls I want to 
> retrieve day urls starts with "/archivelist", I am using
>
> the below code, but I am not getting any result, If I check with inspect 
> element the urls are available starting with /archivelist,
>
> 
>
> Kindly help me where I am doing wrong.
>
> from bs4 import BeautifulSoup
> import re, csv
> import urllib.request
> import scrapy
>
> file = open("output.txt", "r")
>
>
> for i in file:
>
> urls = urllib.request.Request(i, headers={'User-Agent': 'Mozilla/5.0'})
>
> data1 = urllib.request.urlopen(urls).read()
>
> page1 = BeautifulSoup(data1, 'html.parser')
>
> for link1 in page1.findAll(href = re.compile('^/archivelist/')):
>
> l1 = link1.get('href')
>
> print(l1)
>
>
> Thanks,
>
> Kishore.
>
>
>
>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Repairing Python installation?

2017-10-29 Thread Martin Schöön
Den 2017-10-29 skrev Chris Warrick :
> On 29 October 2017 at 18:11, Martin Schöön  wrote:
>> I have installed Python 3 virtualenv and Nikola according to those
>> instructions. I now have a working Nikola but I sure don't know what
>> I am doing :-) How do I get back into that nikola python environment
>> next time?
>
> cd into your virtualenv directory and run `source bin/activate`.
>
Thanks

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


Re: Sandsifter software finds hidden instructions inside processors.

2017-10-29 Thread skybuck2000
I am going to issue a warning about all of this software:

SandSifter, Linux Mint 18.2 and install-apt and for windows: git

For now I suspect running two instances of SandSifter at same time on Linux 
Mint 18.2 caused file system corruption as can be seen on these three 
screenshots also checkdisk log file is included in web folder:

http://www.skybuck.org/SandSifter/unzipped/risks/

Possible causes of file system corruptions:

1. Running two instances of SandSifter + Linux Mint 18.2
2. Git on Windows
3. Perhaps a problem was already with file system.
4. BIOS Corruption in recent past.
5. Spark when other person connected laptop to power output... there was a 
spark.
6. FireFox corruption while browsing or extracting files !
Google detected cooky corruption... so FireFox is also a prime suspect !
7. Capstone disassembler

Be carefull !

I still have to investigate checkdisk log further though ! ;)

Bye,
  Skybuck.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-29 Thread Alberto Riva
As suggested by Ned I'm going to stop replying after pointing out just a 
couple of things. The most important one is the following:


> But since your assertion of: "Python, like Lisp, has X,Y and
> Z features in common" and furthermore that: "I cannot find
> another language that has exactly these X, Y and Z
> features", was used by you as a justification for this
> feature request.

I was not requesting any feature. I was just asking this group (that I 
assume includes people who are more experienced in Python than I am) if 
there was a way of doing something using the tools currently provided by 
Python. That was all.


Then I mentioned the fact that I'm used to a language in which this 
"something" is not necessary because you can get the same effect in a 
cleaner and more readable way using macros, but I was absolutely NOT 
advocating for the addition of Lisp-like macros to Lisp. I know 
perfectly well that it would be impossible, because they can only work 
in a language that has Lisp-like syntax (which, incidentally, I find 
much easier to read than Java syntax, for example; these things are 
highly subjective). And indeed, the fact that you thought I was asking 
for this shows that you don't really know what Lisp macros are, 
otherwise you would know that they're impossible to reproduce in Python.


So I apologize for any misunderstandings; I was not trying to sell 
anything to anyone, least of all vacuum cleaners. I was just asking for 
information.


Thanks,

Alberto

On 10/29/2017 04:35 PM, Rick Johnson wrote:

Alberto Riva wrote:

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?


It depends on what metrics you use. Once you remove all the
type declarations from C and Java source, all three look very
similar, with Python being the "cleanest" syntax of all.
OTOH, when i look at Lisp, all i see is a language that was
designed for easy machine parsing, not for the human. But
that's just a syntactical comparison. Digging deeper, Python
and Java are both strongly typed. And with Python's
multi-paradigm nature, it is both equally useful in OOP (aka: Java)
or imperative (aka: C) style. Aside from static type checking and
some low level distractions, Python is very much like both of
these languages. In fact, i was familiar with both Java and
C before i ever became aware of Python. And the transition
felt very natural to me.


I don't see where you get the idea that I was only exposed
to "academic languages".


Just a lucky guess, i suppose.


It has closures, functions are first-class objects, it's
interactive, highly reflective, variables are not
strongly typed...


Congratulations. You've just described Ruby. And an apple-
cart full of other languages as well.


OK, so? Does that invalidate my statement? And even if it
did, that has almost nothing to do with my original
question.


But since your assertion of: "Python, like Lisp, has X,Y and
Z features in common" and furthermore that: "I cannot find
another language that has exactly these X, Y and Z
features", was used by you as a justification for this
feature request. That's why i had to attack it. Because it
was false.


I don't consider myself a fanboy - I've used Lisp for
most of my career, and now I happily use Python for 80%
of what I do, even if it means putting up with the
occasional limitation, as in this case.


(not that i'm defending Python here...) but how do you
know that this so-called missing "feature" is a
limitation?


Because (again in my own personal opinion) Lisp macros are
wonderful, they increase programmer productivity
enormously, and not having them when I'm programming in
other languages is a limitation from my point of view,
since I enjoy using them so much.


Well, i can understand your enthusiasm, i myself become
highly animated about certain topics (just ask my CO-EDs!).
But you also need to understand that i am person of
_reasoned_ principles. And i try not to violate my
principles just because some random peddler shows-up one day
on my front porch with a slick sales pitch for the next
generation of vacuum cleaners. My vacuum cleaner works just
fine, thank you very much, and until it stops working, or
until you convince me that purchasing a new vacuum wil

Re: Sandsifter software finds hidden instructions inside processors.

2017-10-29 Thread skybuck2000
I do remember a very rare and extreme Windows 7 system hang not so long ago.

It was probably caused by having to many FireFox tabs open... and somehow a 
website/FireFox managed to "hang windows 7".

Windows 7 might have been busy trying to write data to the harddisk and somehow 
during that process it hang.

After waiting a bit I had no choice but to press the "reset" button.

I think this is what might have caused this file system corruption.

A combination of "FireFox memory hogging" and "Windows 7 writing to disk", 
possibly FireFox cache or cookie related.

Bye,
  Skybuck.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Coding style in CPython implementation

2017-10-29 Thread ROGER GRAYDON CHRISTMAN
NOTE:   The case in question was never comparing to True;  it was comparing to
NULL.

There is no "No: if x == None" below, because None is not Boolean.
Similarly comparing a pointer to NULL is not the same as comparing it to a
Boolean.

So I would favor the "Explicit is better than Implicit" in the example cited.

Roger Christman
Pennsylvania State University

On Sun, Oct 29, 2017, Setfan Ram wrote: >
=?UTF-8?B?zqPPhM6tz4bOsc69zr/PgiDOo8+Jz4bPgc6/zr3Or86/z4U=?=
 writes:
>>I guess the following parts from "Zen of Python" apply to this case:
>
>  If we would agree to apply Python rules to C,
>  then we could also use this excerpt from PEP 8:
>
>|o Don't compare boolean values to True or False using ==.
>|
>|Yes:   if greeting:
>|No:if greeting == True:
>|Worse: if greeting is True:
>
>

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


Re: Invoking return through a function?

2017-10-29 Thread Steve D'Aprano
On Mon, 30 Oct 2017 03:35 am, Alberto Riva wrote:

> On 10/29/2017 10:35 AM, Steve D'Aprano wrote:

[...]
>> You mean *less* explicit. "checkKey" gives absolutely no hint that it
>> causes the current function to return.
> 
> That's just because I used a name that was too generic in my example. I
> can call it "returnIfKeyMissing", and then it would be clear.

No it wouldn't. That sounds like it is the "returnIfKeyMissing" function that
returns if the key is missing, and presumably pauses forever, never
returning, if the key exists.

Of course we can *learn* that this is not the case, by reading the docs (if it
has any) or the source code (if it is available). But what of every other
function, any one of which might have been named like your first example:

checkKey

We cannot rely on naming conventions, because people won't always follow it.
*Any* function could potentially return early from the caller.

But honestly, if you're prepared to write:

returnIfKeyMissing(dict, key)

that's LONGER than:

if key not in dict: return

Since your motive appears to be the wish to save typing at the expense of
readability and maintainability, then I expect that *in practice* you
wouldn't use "returnIfKeyMissing" but would prefer a less explicit, shorter
name like "checkKey".


[...]
>> You really should re-think your strategy. Your suggestion, if possible,
>> would lead to difficult to maintain code where you couldn't easily tell
>> where the exit points of a function where.
> 
> But again, it's just a naming problem. 

It *really isn't* a naming problem. Being able to force the caller to return
is a kind of GOTO, and it violates both the letter and the spirit of the
principle that functions should have "one entry, one exit".

Of course we already violate the second part of that, by allowing multiple
returns. But that doesn't mean that any other violation should be acceptable.

Allowing functions to force their caller to exit allows them to violate the
caller's post-condition contracts.

But even if it were just a naming problem, you under-estimate its magnitude.
The word "just" is not justified here: even treated as a naming problem, it
is a big problem. Not an end-of-the-world problem, but still big enough.


> Something like returnIfKeyMissing 
> would make it easy to tell where the exit points are.

No it wouldn't, because not everyone is going to use such a clumsy, long
naming convention, either out of ignorance or for some other reason. Maybe
you're using a library where everything is named in Dutch, or Russian. Maybe
the function was named "foo()" long ago, and has only subsequently gained the
ability to force the caller to return but the name was never changed.


> And as Bartc 
> pointed out, we already have this situation with exceptions, so it would
> be nothing new.

Pardon me, but it was *me* who pointed out the analogy with exceptions, not
Bart. But this is different from an exception.

The similarity is quite weak:

- any function can raise an exception;

- your hoped for feature would allow any function to cause the 
  caller to return;

But the differences are profound:

- exceptions are an alternative to normal execution flow, they don't
  silently continue unless explicitly caught and silenced;

- if you don't explicitly catch the exception, it is obvious when 
  one occurs, because your program halts and you get an obvious 
  stacktrace;

- your suggested force-caller-to-return would silently alter the
  control flow of the caller, without warning or signal that it
  had happened.

That's a very significant difference.



> Indeed, what I'm asking for could be accomplished by 
> wrapping the body of each function in a try/catch block for an ad-hoc
> exception type.

A terrible idea. Why not just write a "validate input" function that checks
your input and returns True for valid and False for invalid, then:

if not valid(args):
return

That's little harder to type than

returnIfNotValid(args)

and much more comprehensible.


> But again, since the language doesn't have macros

And this is the sort of misfeature why Guido is dead-set against Python ever
getting them.

Yes, we get it that Lisp macros are really, really powerful. But there are two
bottle-necks in coding:

- writing the code in the first place;

- maintaining the code afterwards.

Macros are aimed at simplifying the first, at the cost of the second. That's
not a strategy Python follows.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-29 Thread Steve D'Aprano
On Mon, 30 Oct 2017 02:35 am, Stefan Ram wrote:

>   So, I guess, we then must accept that sometimes - under
>   extraordinary circumstances - it should be tolerated to
>   write a function that is as long as six lines.

An entire six lines... you cowboy!

*wink*



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-29 Thread Steve D'Aprano
On Mon, 30 Oct 2017 06:09 am, Alberto Riva wrote:

> But that's exactly why I would like to be able to use macros. I think
> that being able to write "return if this happens" is much more explicit
> than having to write the full if statement, every time.

There have been proposals in the past for syntax similar to

return value if condition

as a short-hand for

if condition: return value

but since the only thing actually saved is a colon (or, at worst, a colon, a
newline and an indent) they went nowhere.

Sometimes the (hypothetical) gain in readability is outweighed by the increase
in unwanted language/syntactic complexity.


> The idea is that 
> you abstract a pattern giving it a name, so every time you see that name
> you know immediately what's going to happen, without having to decode
> the conditional in your mind.

Too much of a good thing... 

That's fine for when you are writing the code the first time. You see a
pattern, you give it a name, and you use that name over and over again.

But when you come back to maintain the code in five years time, you have
forgotten the name and the pattern. You see the name, not the pattern,
because you're only focusing on a small part of the code.[1] What does the
mystery name do? Unless you are very lucky and the function is very well
named[2], you have to dig back through a chain of functions and macros to
work it out.

If the pattern was small and simple enough (like the example in this
thread, "if key not in dict: return") having to dig back through its chain of
functions and macros is more costly and difficult.

Having too many named concepts to understand is as big a cognitive burden as
having too few.







[1] Software maintenance is harder, less rewarding and simply less fun than
writing code in the first place.

[2] There are only two hard problems in computer science: cache invalidation,
and naming things.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


why it append one more letter after decode?

2017-10-29 Thread Ho Yeung Lee
def leftrotate(l, n):
return l[n:] + l[:n]

def rightrotate(l, n):
return l[-n:] + l[:-n]

def encode(s, k, kk):
l = [ord(i) for i in s]
return leftrotate(''.join([chr(i + k) for i in l]), kk)

def decode(s, k, kk):
l = [ord(i) for i in rightrotate(s, kk)]
return ''.join([chr(i - k) for i in l])


yesterday i add above code and run it with batch file 
it can decode a correct password

then i install cx_freeze to produce executable file

but today when i run it, i see the source of encrypted password is correct
but the decode one, it append one more letter Y at the end of string

why?
is cx_freeze change the source python 2.7?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why it append one more letter after decode?

2017-10-29 Thread Ho Yeung Lee

if run these function to decode in python interactive console,
it can decode correct, 

but when run with a big project, it append a letter Y


On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
> def leftrotate(l, n):
> return l[n:] + l[:n]
> 
> def rightrotate(l, n):
> return l[-n:] + l[:-n]
> 
> def encode(s, k, kk):
> l = [ord(i) for i in s]
> return leftrotate(''.join([chr(i + k) for i in l]), kk)
> 
> def decode(s, k, kk):
> l = [ord(i) for i in rightrotate(s, kk)]
> return ''.join([chr(i - k) for i in l])
> 
> 
> yesterday i add above code and run it with batch file 
> it can decode a correct password
> 
> then i install cx_freeze to produce executable file
> 
> but today when i run it, i see the source of encrypted password is correct
> but the decode one, it append one more letter Y at the end of string
> 
> why?
> is cx_freeze change the source python 2.7?

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


ValueError: Error 3 while encrypting in ECB mode

2017-10-29 Thread Ho Yeung Lee
>>> from Crypto.Cipher import AES
>>>
>>> key = 'mysecretpassword'
>>> plaintext = 'Secret Message A'
>>> encobj = AES.new(key, AES.MODE_ECB)
>>> ciphertext = encobj.encrypt("hello")
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 124, in 
encrypt
raise ValueError("Error %d while encrypting in ECB mode" % result)
ValueError: Error 3 while encrypting in ECB mode
>>> ciphertext = encobj.encrypt("hellojalsdjflkdsjflds")
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 124, in 
encrypt
raise ValueError("Error %d while encrypting in ECB mode" % result)
ValueError: Error 3 while encrypting in ECB mode
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Coding style in CPython implementation

2017-10-29 Thread Στέφανος Σωφρονίου
On Monday, October 30, 2017 at 2:35:13 AM UTC+2, ROGER GRAYDON CHRISTMAN wrote:
> NOTE:   The case in question was never comparing to True;  it was comparing to
> NULL.
> 
> There is no "No: if x == None" below, because None is not Boolean.
> Similarly comparing a pointer to NULL is not the same as comparing it to a
> Boolean.
> 
> So I would favor the "Explicit is better than Implicit" in the example cited.

Thus, my 4 Zen points are accurately interconnected:

Being simple and explicit with your code leads to elegant results that are 
indeed quite pleasant to read.


> 
> Roger Christman
> Pennsylvania State University
> 
> On Sun, Oct 29, 2017, Setfan Ram wrote: >
> =?UTF-8?B?zqPPhM6tz4bOsc69zr/PgiDOo8+Jz4bPgc6/zr3Or86/z4U=?=

> >>I guess the following parts from "Zen of Python" apply to this case:
> >
> >  If we would agree to apply Python rules to C,
> >  then we could also use this excerpt from PEP 8:
> >
> >|o Don't compare boolean values to True or False using ==.
> >|
> >|Yes:   if greeting:
> >|No:if greeting == True:
> >|Worse: if greeting is True:
> >
> >

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


Re: why it append one more letter after decode?

2017-10-29 Thread Ho Yeung Lee
i discover when 
it 
decode("\\",1,2)
in interactive console
is [

but decode in big project
it see as
decode(r"\\",1,2)
[[

it double

On Monday, October 30, 2017 at 9:51:01 AM UTC+8, Ho Yeung Lee wrote:
> if run these function to decode in python interactive console,
> it can decode correct, 
> 
> but when run with a big project, it append a letter Y
> 
> 
> On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
> > def leftrotate(l, n):
> > return l[n:] + l[:n]
> > 
> > def rightrotate(l, n):
> > return l[-n:] + l[:-n]
> > 
> > def encode(s, k, kk):
> > l = [ord(i) for i in s]
> > return leftrotate(''.join([chr(i + k) for i in l]), kk)
> > 
> > def decode(s, k, kk):
> > l = [ord(i) for i in rightrotate(s, kk)]
> > return ''.join([chr(i - k) for i in l])
> > 
> > 
> > yesterday i add above code and run it with batch file 
> > it can decode a correct password
> > 
> > then i install cx_freeze to produce executable file
> > 
> > but today when i run it, i see the source of encrypted password is correct
> > but the decode one, it append one more letter Y at the end of string
> > 
> > why?
> > is cx_freeze change the source python 2.7?

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


Re: why it append one more letter after decode?

2017-10-29 Thread Igor Korot
Hi,

On Sun, Oct 29, 2017 at 8:50 PM, Ho Yeung Lee  wrote:
>
> if run these function to decode in python interactive console,
> it can decode correct,

You probably changed the code somewhere...
You just need to debug it and see what is happening...


Thank you.

>
> but when run with a big project, it append a letter Y
>
>
> On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
>> def leftrotate(l, n):
>> return l[n:] + l[:n]
>>
>> def rightrotate(l, n):
>> return l[-n:] + l[:-n]
>>
>> def encode(s, k, kk):
>> l = [ord(i) for i in s]
>> return leftrotate(''.join([chr(i + k) for i in l]), kk)
>>
>> def decode(s, k, kk):
>> l = [ord(i) for i in rightrotate(s, kk)]
>> return ''.join([chr(i - k) for i in l])
>>
>>
>> yesterday i add above code and run it with batch file
>> it can decode a correct password
>>
>> then i install cx_freeze to produce executable file
>>
>> but today when i run it, i see the source of encrypted password is correct
>> but the decode one, it append one more letter Y at the end of string
>>
>> why?
>> is cx_freeze change the source python 2.7?
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why it append one more letter after decode?

2017-10-29 Thread Ho Yeung Lee
it seems that it read csv file
from "\\" to ""

On Monday, October 30, 2017 at 11:03:57 AM UTC+8, Ho Yeung Lee wrote:
> i discover when 
> it 
> decode("\\",1,2)
> in interactive console
> is [
> 
> but decode in big project
> it see as
> decode(r"\\",1,2)
> [[
> 
> it double
> 
> On Monday, October 30, 2017 at 9:51:01 AM UTC+8, Ho Yeung Lee wrote:
> > if run these function to decode in python interactive console,
> > it can decode correct, 
> > 
> > but when run with a big project, it append a letter Y
> > 
> > 
> > On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
> > > def leftrotate(l, n):
> > > return l[n:] + l[:n]
> > > 
> > > def rightrotate(l, n):
> > > return l[-n:] + l[:-n]
> > > 
> > > def encode(s, k, kk):
> > > l = [ord(i) for i in s]
> > > return leftrotate(''.join([chr(i + k) for i in l]), kk)
> > > 
> > > def decode(s, k, kk):
> > > l = [ord(i) for i in rightrotate(s, kk)]
> > > return ''.join([chr(i - k) for i in l])
> > > 
> > > 
> > > yesterday i add above code and run it with batch file 
> > > it can decode a correct password
> > > 
> > > then i install cx_freeze to produce executable file
> > > 
> > > but today when i run it, i see the source of encrypted password is correct
> > > but the decode one, it append one more letter Y at the end of string
> > > 
> > > why?
> > > is cx_freeze change the source python 2.7?

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


Re: why it append one more letter after decode?

2017-10-29 Thread Igor Korot
Hi,

On Sun, Oct 29, 2017 at 10:03 PM, Ho Yeung Lee  wrote:
> i discover when
> it
> decode("\\",1,2)
> in interactive console
> is [
>
> but decode in big project
> it see as
> decode(r"\\",1,2)
> [[
>
> it double

Those 2 lines are different.

Thank you.

>
> On Monday, October 30, 2017 at 9:51:01 AM UTC+8, Ho Yeung Lee wrote:
>> if run these function to decode in python interactive console,
>> it can decode correct,
>>
>> but when run with a big project, it append a letter Y
>>
>>
>> On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
>> > def leftrotate(l, n):
>> > return l[n:] + l[:n]
>> >
>> > def rightrotate(l, n):
>> > return l[-n:] + l[:-n]
>> >
>> > def encode(s, k, kk):
>> > l = [ord(i) for i in s]
>> > return leftrotate(''.join([chr(i + k) for i in l]), kk)
>> >
>> > def decode(s, k, kk):
>> > l = [ord(i) for i in rightrotate(s, kk)]
>> > return ''.join([chr(i - k) for i in l])
>> >
>> >
>> > yesterday i add above code and run it with batch file
>> > it can decode a correct password
>> >
>> > then i install cx_freeze to produce executable file
>> >
>> > but today when i run it, i see the source of encrypted password is correct
>> > but the decode one, it append one more letter Y at the end of string
>> >
>> > why?
>> > is cx_freeze change the source python 2.7?
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why it append one more letter after decode?

2017-10-29 Thread Ho Yeung Lee

i fixed by replace("","\\")


On Monday, October 30, 2017 at 11:16:02 AM UTC+8, Igor Korot wrote:
> Hi,
> 
> On Sun, Oct 29, 2017 at 10:03 PM, Ho Yeung Lee  wrote:
> > i discover when
> > it
> > decode("\\",1,2)
> > in interactive console
> > is [
> >
> > but decode in big project
> > it see as
> > decode(r"\\",1,2)
> > [[
> >
> > it double
> 
> Those 2 lines are different.
> 
> Thank you.
> 
> >
> > On Monday, October 30, 2017 at 9:51:01 AM UTC+8, Ho Yeung Lee wrote:
> >> if run these function to decode in python interactive console,
> >> it can decode correct,
> >>
> >> but when run with a big project, it append a letter Y
> >>
> >>
> >> On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
> >> > def leftrotate(l, n):
> >> > return l[n:] + l[:n]
> >> >
> >> > def rightrotate(l, n):
> >> > return l[-n:] + l[:-n]
> >> >
> >> > def encode(s, k, kk):
> >> > l = [ord(i) for i in s]
> >> > return leftrotate(''.join([chr(i + k) for i in l]), kk)
> >> >
> >> > def decode(s, k, kk):
> >> > l = [ord(i) for i in rightrotate(s, kk)]
> >> > return ''.join([chr(i - k) for i in l])
> >> >
> >> >
> >> > yesterday i add above code and run it with batch file
> >> > it can decode a correct password
> >> >
> >> > then i install cx_freeze to produce executable file
> >> >
> >> > but today when i run it, i see the source of encrypted password is 
> >> > correct
> >> > but the decode one, it append one more letter Y at the end of string
> >> >
> >> > why?
> >> > is cx_freeze change the source python 2.7?
> >
> > --
> > https://mail.python.org/mailman/listinfo/python-list

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


Re: Invoking return through a function?

2017-10-29 Thread Rustom Mody
On Sunday, October 29, 2017 at 9:52:01 PM UTC+5:30, Rick Johnson wrote:
> On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, Alberto Riva wrote:

> > In a language like Lisp
> 
> Python is nothing like Lisp, and for good reason! Sure, we
> have a few lispers and functional fanboys who hang around
> here, and sometimes Rustom can get a little preachy about
> FP, but mostly, we tolerate the fanboyism -- so long as it's
> not rabid fanboyism.

Rick's personal comments are one of the standard entertainments of this list. 
Enjoy!

The comments on FP are more problematic:

- These misconceptions are more widespread than just Rick
- They are right enough to be hard to refute
- And wrong enough to cause confusion and misdirection
- And irrelevant to (threads like) this one

My super-short rejoiner to the FP-irrelevancy is:
«If there is one key takeaway from functional programming maybe it should be: 
"Truth is a function of time" »

In more detail:
- Lisp (1960)  was the second functional language; its predecessor was 
something called Formula Translator — usually shortened to Fortran (c. 1957)
- By the late 80s, many FPers had begun regard Lisp as a setback for functional 
programming. [Dont get me wrong: Ive enjoyed Scheme more than any other 
programming language. Its just that conflating Lisp and FP is an error (in 
2017)]

More historical details at http://blog.languager.org/2015/04/cs-history-1.html 
and sequel

At a more conceptual level, people dont get that there are two dimensions
- the apply-lambda axis — usually called functional programming
- the eval-quote axis — which has precious little to do with FP (and is more 
relevant to your question)

These two dimensions of power uniquely coincide in Lisp (Scheme).

As you correctly (almost) point out
- Python is very much a lisp… its semantic under-belly
- However, syntactically its more like C/Java etc in the sense of having a 
rigid 
fixed-at-language-design-time syntax

More at http://blog.languager.org/2013/08/applying-si-on-sicp.html

For a question like macros (syntax-extensions) that sits between the two your
question is interesting and I am not sure I know how to do it…
I remember seeing something about this recently but my google-foo is failing me 
at the moment

However I would look at
- PEP 263 https://www.python.org/dev/peps/pep-0263/ — Source Code Encodings…
- Hooking into the codec module https://docs.python.org/3/library/codecs.html
- hooking into ast module https://docs.python.org/3/library/ast.html

An old attempt in this direction: http://code.activestate.com/recipes/546539/

You've already got the moral-hi-horse guys giving you the dope of why this is 
evil. Swallow if you like. My own lightweight
suggestion would be that the natural pythonic way of unstructured exit is 
exceptions. Not as succinct as a tailormade syntax extension. But good enough 
IMHO

PS I personally would be interested if you get this (syntax extension) running
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ValueError: Error 3 while encrypting in ECB mode

2017-10-29 Thread Steve D'Aprano
On Mon, 30 Oct 2017 01:20 pm, Ho Yeung Lee wrote:

 from Crypto.Cipher import AES

 key = 'mysecretpassword'
 plaintext = 'Secret Message A'
 encobj = AES.new(key, AES.MODE_ECB)
 ciphertext = encobj.encrypt("hello")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python27\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 124,
>   in encrypt
> raise ValueError("Error %d while encrypting in ECB mode" % result)
> ValueError: Error 3 while encrypting in ECB mode

What does the documentation for the Crypto.Cipher.AES object say?

Did you try googling for the error message?

https://duckduckgo.com/?q=Error+3+while+encrypting+in+ECB+mode

https://www.google.com.au/search?q=Error+3+while+encrypting+in+ECB+mode


which gives me this:

https://stackoverflow.com/questions/14179784/python-encrypting-with-pycrypto-aes

among other possible answers.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-29 Thread Lele Gaifax
[email protected] (Stefan Ram) writes:

>   There are many macro processors available, like the C macro
>   preprocessor, gpp, M4, or funnelweb. You can always use them
>   for your Python source (which, in this case, isn't exactly Python
>   source anymore).

Even more to the point, MacroPy! See https://github.com/azazel75/macropy for a
3.5+ version.

ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  | -- Fortunato Depero, 1929.

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