Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Frank Millman

"Chris Angelico"  wrote in message 
news:captjjmp4y5zowwn5yftjutko4h5jvtqlantwqepa6b35xnd...@mail.gmail.com...
>
> Entirely possible. I never did track down the actual cause of the
> SQLite3 issues my students were having; though I suspect it's not
> purely a Python API issue. I tried to demonstrate the concept of
> foreign keys using the sqlite3 command line tool, and did a sequence
> of commands which ought to have failed, but didn't.

The default is for sqlite3 to ignore foreign key contraints.

To enable them, add the following -

pragma foreign_keys = on;

It works for me.

Unfortunately it has a limitation, which they acknowledge but they say is 
unlikely to be addressed. You can access more than one database concurrently 
by using the 'attach' command, and qualifying a remote tablename as 
{database} dot {tablename}. You can then include the remote table in any sql 
command. However, it will not enforce foreign key constraints across 
databases.

Frank Millman



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


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Chris Angelico
On Sun, Nov 23, 2014 at 7:21 PM, Frank Millman  wrote:
> "Chris Angelico"  wrote in message
> news:captjjmp4y5zowwn5yftjutko4h5jvtqlantwqepa6b35xnd...@mail.gmail.com...
>>
>> Entirely possible. I never did track down the actual cause of the
>> SQLite3 issues my students were having; though I suspect it's not
>> purely a Python API issue. I tried to demonstrate the concept of
>> foreign keys using the sqlite3 command line tool, and did a sequence
>> of commands which ought to have failed, but didn't.
>
> The default is for sqlite3 to ignore foreign key contraints.
>
> To enable them, add the following -
>
> pragma foreign_keys = on;
>
> It works for me.

Thanks, I went poking around briefly but didn't find that pragma. I
still stand by my view, though, that constraint checking should be
active by default; you have to explicitly create them anyway, so it's
not like you'd unexpectedly lose heaps of performance. And even if it
is costly, the default settings should be for reliability, more than
performance; if you want to cut corners to speed things up, that's
your decision, but that should be something you have to explicitly ask
for.

It'd be nice to have a warning or at least informational: "Foreign key
constraint created, but constraint checking is inactive". Would mean
folks like me, who grew up on IBM's DB2 and now use PostgreSQL,
wouldn't be so confused by "why did that not throw an error".

> Unfortunately it has a limitation, which they acknowledge but they say is
> unlikely to be addressed. You can access more than one database concurrently
> by using the 'attach' command, and qualifying a remote tablename as
> {database} dot {tablename}. You can then include the remote table in any sql
> command. However, it will not enforce foreign key constraints across
> databases.

That's more of an edge case; I wouldn't be too bothered by that.

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


Embedded python 'scripting engine' inside Python app

2014-11-23 Thread Patrick Stinson
I am writing a python app (using PyQt, but that’s not important here), and want 
my users to be able to write their own scripts to automate the app’s 
functioning using an engine API hat I expose. I have extensive experience doing 
this in a C++ app with the CPython api, but have no idea how to do this outside 
of calling exec() from with in Python :)

Ideally their script would compile when the source changes and retain it’s 
state and respond to callbacks from the api object. It appears this won’t work 
with exec() because the script’s definitions and state disappear as soon as the 
exec() call is complete, and the script doesn’t seem to be able to access it’s 
own defined functions and classes.

Thoughts? Fun stuff!

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


Re: Python IDE.

2014-11-23 Thread Ricardo Aráoz


Spyder

El 20/11/14 a las 18:47, TP escibió:
On Thu, Nov 20, 2014 at 11:29 AM, Irmen de Jong 
mailto:irmen.nos...@xs4all.nl>> wrote:


PyCharm *is* free, if you fall in one of several categories.
See http://www.jetbrains.com/pycharm/buy/license-matrix.jsp

Even when you have to buy it, it is cheap (IMO) for what it offers.


"PyCharm Editions Comparison" [1] is a better comparison between the 
differences of the always free Community Edition and the Pro Edition 
of PyCharm.


[1] 
https://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html 







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


unloading a module created with imp.new_module

2014-11-23 Thread Patrick Stinson
If I create a module with imp.new_module(name), how can I unload it so that all 
the references contained in it are set to zero and the module is deleted? 
deleting the reference that is returned doesn’t seem to do the job, and it’s 
not in sys.modules, so where is the dangling reference?

Thanks!

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


Re: Challenge: optimizing isqrt

2014-11-23 Thread Stephen Tucker
Serhiy,

This looks very good indeed. As a matter of interest, is there any
particular reason you have used 2*b instead of b+b? Might b+b be faster
than b*2?

Also, in various lines, you use //2. Would >>1 be quicker? On reflection,
perhaps you have had to use //2 because >>1 cannot be used in those
situations.

Stephen Tucker.




On Thu, Nov 20, 2014 at 6:00 PM, Serhiy Storchaka 
wrote:

> On 01.11.14 03:29, Steven D'Aprano wrote:
>
>> There is an algorithm for calculating the integer square root of any
>> positive integer using only integer operations:
>>
>
> Here is my optimized implementation inspired by Christian's ideas.
>
> import math, sys
>
> C1 = sys.float_info.radix ** sys.float_info.mant_dig
> C2 = int(sys.float_info.max)
> C3 = C2.bit_length() - 2
>
> def isqrt(n):
> if n < 0:
> raise ValueError
> if n == 0:
> return 0
> if n <= C1:
> return int(math.sqrt(n))
> if n <= C2:
> x = int(math.sqrt(n))
> else:
> b = (n.bit_length() - C3) // 2
> x = int(math.sqrt(n >> (2 * b))) << b
> y = (x + n // x) // 2
> if y == x:
> return x
> while True:
> x = y
> y = (x + n // x) // 2
> if y >= x:
> return x
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Embedded python 'scripting engine' inside Python app

2014-11-23 Thread Chris Angelico
On Sun, Nov 23, 2014 at 4:48 PM, Patrick Stinson  wrote:
> I am writing a python app (using PyQt, but that’s not important here), and 
> want my users to be able to write their own scripts to automate the app’s 
> functioning using an engine API hat I expose. I have extensive experience 
> doing this in a C++ app with the CPython api, but have no idea how to do this 
> outside of calling exec() from with in Python :)
>
> Ideally their script would compile when the source changes and retain it’s 
> state and respond to callbacks from the api object. It appears this won’t 
> work with exec() because the script’s definitions and state disappear as soon 
> as the exec() call is complete, and the script doesn’t seem to be able to 
> access it’s own defined functions and classes.
>
> Thoughts? Fun stuff!

First off, a cautionary note: Security-wise, this is absolutely
equivalent to your users editing your source code. Be aware that
you're giving them complete control.

What you should be able to do is exec the script in a specific global
dictionary. Here's some example code (Python 3.4):

>>> script = """
def init():
print("Initializing")

def on_some_event(status):
trigger_some_action("Status is now "+status)
"""
>>> def trigger_some_action(msg):
print("Action triggered.",msg)
>>> globl = {"trigger_some_action":trigger_some_action}
>>> exec(script,globl)
>>> globl["init"]()
Initializing
>>> globl["on_some_event"]("Something happened")
Action triggered. Status is now Something happened

You can provide globals like this, or you can create an importable
module for the scripts to call on. (Or both. Create a module, and
pre-import it automatically.) The script defines functions with
specific names and/or calls your functions to register hooks; you can
reach into the globals to trigger functions.

One way to handle updates to the code would be to exec it in the same
globals dictionary. That has its complexities (for instance, if you
rename a function, the old version will still exist under the old name
unless you explicitly del it), but it can be very convenient.
Alternatively, you could have the new version run in a new dictionary,
but important state can be kept in separate dictionaries. That's how I
manage things with a Pike program - all code gets reloaded cleanly,
but retained state is stored separately in a mutable object that gets
passed around.

There are several ways this sort of thing can be done. It's reasonably
easy, as long as you take a bit of care across the reload boundaries.

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


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Jussi Piitulainen
Chris Angelico writes:
> On Sun, Nov 23, 2014 at 7:21 PM, Frank Millman wrote:
>
> > To enable them, add the following -
> >
> > pragma foreign_keys = on;
> >
> > It works for me.
> 
> Thanks, I went poking around briefly but didn't find that pragma.

I didn't notice a pointer to the relevant documentation in this thread
yet. So here, and in the rest of that page:


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


Re: unloading a module created with imp.new_module

2014-11-23 Thread Ian Kelly
On Sat, Nov 22, 2014 at 11:49 PM, Patrick Stinson  wrote:
> If I create a module with imp.new_module(name), how can I unload it so that 
> all the references contained in it are set to zero and the module is deleted? 
> deleting the reference that is returned doesn’t seem to do the job, and it’s 
> not in sys.modules, so where is the dangling reference?

How are you determining that the module is not deleted?
-- 
https://mail.python.org/mailman/listinfo/python-list


[ANN] Pylint 1.4 released

2014-11-23 Thread Claudiu Popa
Hello!

On behalf of the Pylint development team, I'm happy to announce that
Pylint 1.4 has been released.

This release has a lot of improvements over the last one. One of the
main differences is that support for Python versions < 2.7 has been
droped, which allows us to support Python 2.7 and 3.3+ from a single
codebase.


Other important changes:

 * A Python 3 porting checker, activated by the new flag '--py3k'.
   This mode will disable all other checkers and will emit warnings and
   errors for constructs which are invalid or removed in Python 3.

 * New options for controlling the loading of C extensions.
   By default, only C extensions from the stdlib will be loaded
   into the active Python interpreter for inspection, because they
   can run arbitrary code on import. The option `--extension-pkg-whitelist` can
   be used to specify modules or packages that are safe to load.

 * An experimental support for using multiple workers to process files
and packages,
   activated with the new --jobs flag.

 * A new spelling checker (disabled by default).

 * New warnings: boolean-datetime, logging-format-interpolation,
inherit-non-class,
   mixed-line-endings

 * A lot of other small improvements and bug fixes.

If you find any bugs, don't hesitate to open a new issue on our issue tracker.

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


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Chris Angelico
On Sun, Nov 23, 2014 at 8:40 PM, Jussi Piitulainen
 wrote:
> Chris Angelico writes:
>> On Sun, Nov 23, 2014 at 7:21 PM, Frank Millman wrote:
>>
>> > To enable them, add the following -
>> >
>> > pragma foreign_keys = on;
>> >
>> > It works for me.
>>
>> Thanks, I went poking around briefly but didn't find that pragma.
>
> I didn't notice a pointer to the relevant documentation in this thread
> yet. So here, and in the rest of that page:
>
> 

>From that page:

"""Foreign key constraints are disabled by default (for backwards
compatibility), so must be enabled separately for each database
connection. (Note, however, that future releases of SQLite might
change so that foreign key constraints enabled by default. Careful
developers will not make any assumptions about whether or not foreign
keys are enabled by default but will instead enable or disable them as
necessary.)"""

That explains it. Putting the "backwards" into "backwards
compatibility", but understandable, at least. I'm pointing all the
people I know to this page; just enable the things and then you can
actually trust stuff.

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


Re: unloading a module created with imp.new_module

2014-11-23 Thread Ian Kelly
On Sun, Nov 23, 2014 at 2:48 AM, Ian Kelly  wrote:
> On Sat, Nov 22, 2014 at 11:49 PM, Patrick Stinson  
> wrote:
>> If I create a module with imp.new_module(name), how can I unload it so that 
>> all the references contained in it are set to zero and the module is 
>> deleted? deleting the reference that is returned doesn’t seem to do the job, 
>> and it’s not in sys.modules, so where is the dangling reference?
>
> How are you determining that the module is not deleted?

From my testing, using Python 3.4:

>>> for i in range(5): imp.new_module('spam')
...





>>> import gc, types
>>> [m for m in gc.get_objects() if isinstance(m, types.ModuleType) and 
>>> m.__name__ == 'spam']
[]
>>> 42
42
>>> [m for m in gc.get_objects() if isinstance(m, types.ModuleType) and 
>>> m.__name__ == 'spam']
[]

In this case one of the created modules was hanging around because it
was still referenced by the special "_" variable of the interactive
interpreter. Evaluating a new expression cleared that out and deleted
the module. Maybe you're seeing the same thing.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Christian Gollwitzer

Am 23.11.14 07:32, schrieb Chris Angelico:

did a sequence
of commands which ought to have failed, but didn't. Let's see if I can
recreate this:

rosuav@sikorsky:~$ sqlite3
SQLite version 3.7.13 2012-06-11 02:05:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table foo (val text primary key);
sqlite> create table bar (val text references foo on delete set null);
sqlite> insert into foo values ('asdf');
sqlite> insert into bar values ('asdf');
sqlite> insert into bar values ('qwer');
sqlite> select * from foo;
asdf
sqlite> select * from bar;
asdf
qwer
sqlite> delete from foo;
sqlite> select * from foo;
sqlite> select * from bar;
asdf
qwer

So the foreign key is being completely ignored.


SQLite does foreign keys by running a trigger. You need to activate it

https://www.sqlite.org/foreignkeys.html#fk_enable

Apfelkiste:VecTcl chris$ sqlite3
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> PRAGMA foreign_keys = ON;
sqlite> create table foo (val text primary key);
sqlite> create table bar (val text references foo on delete set null);
sqlite> insert into foo values ('asdf');
sqlite> insert into bar values ('asdf');
sqlite> insert into bar values ('qwer');
Error: foreign key constraint failed
sqlite> select * from foo;
asdf
sqlite> select * from bar;
asdf
sqlite> delete from foo;
sqlite> select * from foo;
sqlite> select * from bar;

sqlite>


Not sure, if this helps the OP, though.

Christian

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


Re: [ANN] Pylint 1.4 released

2014-11-23 Thread Marko Rauhamaa
Claudiu Popa :

> On behalf of the Pylint development team, I'm happy to announce that
> Pylint 1.4 has been released.

Out of interest, is there something Pylint does CPython shouldn't be
doing? IOW, should pylint be an integrated part of CPython?


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


Re: Embedded python 'scripting engine' inside Python app

2014-11-23 Thread Chris Angelico
On Sun, Nov 23, 2014 at 9:28 PM, Patrick Stinson  wrote:
> Thanks for your great reply. I even augmented the reloading with the same
> dict by clearing all of the non-standard symbols from the dict. This
> effectively resets the dict:

You may as well start with an empty dict and then pick up the few
things you want, I think.

> Is there a better and more secure way to do the python-within-python in
> order allow users to automate your app?

More secure? Basically no. You could push the inner script into a
separate process, but I would recommend simply acknowledging the
insecurity. Embrace the lack of security and call it a debugging
feature - make it possible to introspect, control, manipulate internal
structures. Feature, not flaw. :)

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


Re: I have no class

2014-11-23 Thread Seymore4Head
On Sun, 23 Nov 2014 17:00:08 +1100, Chris Angelico 
wrote:

>On Sun, Nov 23, 2014 at 3:15 PM, Seymore4Head
> wrote:
>> Traceback (most recent call last):
>>   File "C:\Documents and Settings\Administrator\Desktop\rps.py", line
>> 7, in 
>> a=RPS()
>>   File "C:\Documents and Settings\Administrator\Desktop\rps.py", line
>> 6, in __init__
>> self.key=key[self.throw]
>> NameError: name 'key' is not defined
>
>This information is far more helpful than "it is broke". Note how it
>says that the name 'key' is not defined? You're expecting that it
>would be defined, because you defined it a few lines earlier. So
>here's a more useful way to ask the question:
>
>-- cut --
>I'm trying to use a dictionary to translate throw numbers into
>descriptions, but even though the dictionary has been defined, Python
>is telling me it hasn't.
>
>import random
>class RPS:
>key={0:"rock", 1:"paper",2:"scissors"};
>def __init__(self):
>self.throw=random.randrange(3)
>self.key=key[self.throw]
>a=RPS()
>
>Traceback (most recent call last):
>  File "C:\Documents and Settings\Administrator\Desktop\rps.py", line
>7, in 
>a=RPS()
>  File "C:\Documents and Settings\Administrator\Desktop\rps.py", line
>6, in __init__
>self.key=key[self.throw]
>NameError: name 'key' is not defined
>
>It seems to me that 'key' is defined on line 3. Can anyone explain
>what's happening here? Thanks!
>-- cut --
>
>Note that I've posted the *entire* code of your script (it's a
>reconstruction, but I suspect it's fairly close; there might be more
>code after that, but it's not affecting anything), and included the
>traceback in the first message, rather than waiting for someone to ask
>for it.
>
>Armed with this information, someone can tell you:
>
>1) Python's namespacing rules mean that 'key' is a part of the RPS
>class, and can be referred to as 'self.key' or as 'RPS.key'
>2) Use of 'self.key' for the textual form of the throw is shadowing
>the first of those reference names (but it's a poor name anyway)
>3) A list would work just as well as a dictionary here, since your
>indices are sequential and start from zero
>4) There's another function in the random module which can do both of
>your steps at once.
>
>Thank you for helping us help you help us all!
>
>ChrisA

I wish I could explain my problems so precisely.  I will try to do
better in the future.
Thanks

I will also try this using a list instead of a dictionary.
-- 
https://mail.python.org/mailman/listinfo/python-list


ImportError: cannot import name 'Enum'

2014-11-23 Thread muhammedabuali
Hello all,

I am trying to use the python module but when I open the shell and write:

` import enum `

I get the following error

` Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/enum.py", line 3, in 
from types import MappingProxyType, DynamicClassAttribute
  File "/home/muhammed/workspace/python/unification/types.py", line 1, in 

from enum import Enum
ImportError: cannot import name 'Enum'

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


Re: ImportError: cannot import name 'Enum'

2014-11-23 Thread Chris Angelico
On Sun, Nov 23, 2014 at 11:10 PM,   wrote:
> Hello all,
>
> I am trying to use the python module but when I open the shell and write:
>
> ` import enum `
>
> I get the following error
>
> ` Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python3.4/enum.py", line 3, in 
> from types import MappingProxyType, DynamicClassAttribute
>   File "/home/muhammed/workspace/python/unification/types.py", line 1, in 
> 
> from enum import Enum
> ImportError: cannot import name 'Enum'

Thank you for making it so clear and easy! By posting the entire
traceback, plus everything you're expecting to see, you clearly show
what's going on. THANK YOU!

What's happening here is that you have a file called "types.py".
Unfortunately that name shadows the 'types' module in the standard
library, and enum calls on that. So you'll need to rename your file,
and then all should be well.

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


Re: Embedded python 'scripting engine' inside Python app

2014-11-23 Thread Stefan Behnel
Chris Angelico schrieb am 23.11.2014 um 11:35:
> On Sun, Nov 23, 2014 at 9:28 PM, Patrick Stinson wrote:
>> Is there a better and more secure way to do the python-within-python in
>> order allow users to automate your app?
> 
> More secure? Basically no. You could push the inner script into a
> separate process, but I would recommend simply acknowledging the
> insecurity. Embrace the lack of security and call it a debugging
> feature - make it possible to introspect, control, manipulate internal
> structures. Feature, not flaw. :)

As the author of Lupa, I know that some people have successfully and safely
embedded Lua in Python as a simple, small and object-oriented scripting
language in a sandbox.

https://pypi.python.org/pypi/lupa

The overall syntax isn't quite as great as that of Python, but as long as
you mostly stick to "here's a bunch of functions you can call" or "here's
an object, go and call some methods on it" kind of APIs, there isn't all
that much of a difference either.

Stefan


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


Python Signal/Slot + QThred code analysis

2014-11-23 Thread Juan Christian
This is a continuation of my other topic "How to access Qt components
loaded from file", it was getting big and the focus changed completely, the
real question there was already answered, and we were talking about
signal/slot, QThred and other things.

So, I read on the web (didn't find books talking about QThred, Signal/Slot)
and I came up with this code:

Python 3.4.2
PySide 1.2.2

from PySide.QtCore import QObject, QThread, Signal
import requests
import bs4

class Outpost(QObject, QThread):
received = Signal()

def __init__(self, uid, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = 'http://www.myurl.com/user/' + uid

def run(self):
soup = bs4.BeautifulSoup(requests.get(self.url).text)

with soup.select('div.stat_box div.value')[0].get_text().replace(',',
'') as a, soup.select('div.stat_box div.value')[1].get_text() as b:
self.info_a = a
self.info_b = b

self.received.emit(self)

Is this code good?

I'll explain what I think this code does, when I was doing this: First I
created my custom signal, 'received'. Then I made my __init__ just to set a
uid.

Then, the run func, I read that's the one that will run when working with
threads. Here I set the soup and I get the page content using requests,
that's the part that will take more time.

Then I use bs4 to set my data, and yes, I know that getting data this way
isn't the best option, but I don't have other choice, they don't give APIs
for this stuff.

Later I emit my signal when I have everything set and I pass the entire
class with it so I can call the 'var.info_a' and 'bar.info_b' wherever I
want.

Did I think correctly, can I do anything better here? Many thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Embedded python 'scripting engine' inside Python app

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 12:20 AM, Patrick Stinson  wrote:
> I think this is the way I’ll take it, and for all the same reasons. The only 
> way they can break it is if they really want to. I guess anything other 
> Franken-apps would be interesting to hear about too. And I’ll still stick it 
> on the app store.
>

(Please note, the convention on this list/newsgroup - as with most
tech lists - is to put your text underneath what you're quoting -
so-called "bottom-posting" or "interleaved" style.)

Yep. I got in some trouble for doing this at my last salaried
employment, because the boss couldn't get his head around the idea
that an XKCD 936-compliant password is secure enough for a code
executor, and that the absence of a code executor makes debugging much
harder. (In the end, I just renamed it to "calculator" so it wasn't so
obvious, and left it there. Debugging is important.) In my open-source
MUD client, Gypsum, there's a code executor built-in, which I use
regularly as a simple calculator, and also to manipulate the program's
internals. Some examples:

> /x 123+456*789
359907
> /x asin(.5)*180/3.14159
30.253399374
> /x "Test "*5 + "Haha"
"Test Test Test Test Test Haha"
> /x window.mainwindow.iconify()
GTK2.Window
(and the main window has just been minimized, aka iconified)

Basically, any expression that I type after "/x" will be parsed and
executed as code. There's no sandboxing at all; it's executed in its
own globals() and locals(), but if it wants to tinker with external
state, it's free to do that. Since all the code is there for the user
to peruse anyway, I don't distinguish between "this you may do" and
"this you may not do", but instead between "this is pledged to be
supported throughout this major version" and "this is undocumented,
use at your own risk" - on the understanding that most of the latter
category is actually pretty stable, and can happily be used anyway.

Interpreted languages tend to make this kind of thing fairly easy, and
on the day you have a weird error that you can't figure out, you will
be no end of glad you have this. No triggering a core dump and then
doing a post-mortem, just examine state live, using the language's
natural syntax.

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


Comprehension with two variables - explanation needed

2014-11-23 Thread Ivan Evstegneev
Hello guys,

 

I would like to ask you for some explanations on comprehensions. (Don't be
scared, it just some particular example ^_^)

 

I found this little "find prime number" example over the internet:

 

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

 

 

It looked  pretty clear to me, till the time I decided to make some changes
to it %)))

 

Ok this is the case: 

 

As you can see the first line's comprehension produces a list, that includes
all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i).

So  I get this pattern: noprimes  = =  [4, 6, 8...48, 6, 9,12.. ].

The change that I tried to apply to this comprehension would lead to the
following pattern: noprimes = = [[4, 6,8.48], [6, 9, 12..], ..,[some
numbers]] 

 

But despite my struggling on it for the whole day, I haven't got to the
desirable result(using comprehensions only) 

 

Please, don't get me wrong, I'm not a lazy one (just a beginner). 

 

In my case, I  made some googling, and found some patterns for matrices,
that look this one(for example):

 

Matrix = [[0 for x in range(5)] for x in range(5)]

 

But when I tried to use square brackets with my code, it yields an error
about definition of "i", for instance:

 

File "", line 1, in 

noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]

NameError: name 'i' is not defined.

 

Then I tried to apply those brackets to "j", like this: 

 

>>> noprimes = [[j] for i in range(2, 8) for j in range(i*2, 50, i)]

 

In this case I get, pretty predictable result, like this: [[num], [num],
[num],...,[num]], and  this is still not what I'm looking for..

 

So I moved further, and succeeded to solve my problem in a different manner:

 

>>> noprimes=[]

>>> for i in range(2,8):

noprimes.append(list(range(i*2,50,i)))

 

Which yields, in fact, the matrix I wanted from the beginning:

 

noprimes == [[4, 6, 8, 10, 12,.., 48], [6, 9, 12, 15, 18, ., 42, 45,
48],..,[numbers]]

Yep, this the "classical" way for me, on the other hand I have the feeling,
that this is not, the ultimate solution. ^_^

 

So my questions is still persists:

 

1)  Is it possible to realize such a thing by applying changes only to
initial comprehension? If yes, it would be nice to see the solution.

2)  How actually bad is my solution? I mean, after all, there are nested
functions call in my code,  so how much the speed is affected(if any)? 

 

Thanks a lot in advance,

 

Ivan.

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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Rustom Mody
On Sunday, November 23, 2014 8:28:16 PM UTC+5:30, Ivan Evstegneev wrote:
> Hello guys,
>  
> I would like to ask you for some explanations on comprehensions. (Don't be 
> scared, it just some particular example ^_^)
>  
> I found this little "find prime number" example over the internet:
>  
> >>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
> >>> primes = [x for x in range(2, 50) if x not in noprimes]
> >>> print primes
> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>  
>  
> It looked  pretty clear to me, till the time I decided to make some changes 
> to it %)))
>  
> Ok this is the case: 
>  
> As you can see the first line's comprehension produces a list, that includes 
> all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i).
> So  I get this pattern: noprimes  = =  [4, 6, 8.48, 6, 9,12 ].
> The change that I tried to apply to this comprehension would lead to the 
> following pattern: noprimes = = [[4, 6,8...48], [6, 9, 12], ,[some 
> numbers]] 
>  
> But despite my struggling on it for the whole day, I haven't got to the 
> desirable result(using comprehensions only) 
>  
> Please, don't get me wrong, I'm not a lazy one (just a beginner). 
>  
> In my case, I  made some googling, and found some patterns for matrices, that 
> look this one(for example):
>  
> Matrix = [[0 for x in range(5)] for x in range(5)]
>  
> But when I tried to use square brackets with my code, it yields an error 
> about definition of "i", for instance:
>  
> File "", line 1, in 
> noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]
> NameError: name 'i' is not defined.

Is this what you want?

>>> [[j for j in range(i*2, 50, i)] for i in range(2,8)]
[[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 
44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48], [8, 
12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, 15, 20, 25, 30, 35, 40, 45], [12, 
18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]]

[I am not sure what you are trying -- just making local
changes to the ZF to make it work]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I have no class

2014-11-23 Thread Dave Angel

On 11/23/2014 05:52 AM, Seymore4Head wrote:

On Sun, 23 Nov 2014 17:00:08 +1100, Chris Angelico 
wrote:



1) Python's namespacing rules mean that 'key' is a part of the RPS
class, and can be referred to as 'self.key' or as 'RPS.key'
2) Use of 'self.key' for the textual form of the throw is shadowing
the first of those reference names (but it's a poor name anyway)
3) A list would work just as well as a dictionary here, since your
indices are sequential and start from zero
4) There's another function in the random module which can do both of
your steps at once.

Thank you for helping us help you help us all!

ChrisA


I wish I could explain my problems so precisely.  I will try to do
better in the future.
Thanks

I will also try this using a list instead of a dictionary.



And please avoid the shadowing.  It's confusing whenever the same name 
is used for a class attribute and an instance attribute of the same 
class.  it can be useful for defaults and such, but not here.


 class RPS:
 KEY_TABLE={0:"rock", 1:"paper",2:"scissors"};
  or
 KEY_TABLE= ("rock", "paper", "scissors")
 def __init__(self):
 self.throw=random.randrange(3)
 self.key=RPS.KEY_TABLE[self.throw]

Note I also capitalized the tuple name, which is a convention saying we 
don't intend to modify it.


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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 1:56 AM, Ivan Evstegneev
 wrote:
>
> Hello guys,
>
> I would like to ask you for some explanations on comprehensions. (Don’t be 
> scared, it just some particular example ^_^)
>
> I found this little “find prime number” example over the internet:
>
> >>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
> >>> primes = [x for x in range(2, 50) if x not in noprimes]
> >>> print primes
>
> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Okay, this is a pretty ham-fisted way of enumerating prime numbers,
but let me walk you through it. First, let's look at the composite
numbers (the 'noprimes' list). That comprehension is identical (apart
from some details that don't matter here) to this:

noprimes = []
for i in range(2,8):
for j in range(i*2, 50, i):
noprimes.append(j)

So, as you correctly deduced below, what you have is this list:
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38,
40, 42, 44, 46, 48, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42,
45, 48, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 10, 15, 20, 25, 30,
35, 40, 45, 12, 18, 24, 30, 36, 42, 48, 14, 21, 28, 35, 42, 49]

The inner loop (with j as its iteration variable) counts up in
increments of i, starting at twice i, stopping once it's gone past
fifty. That means it's every multiple of i other than i itself, which
means these are by definition composite numbers. Note that quite a few
of the numbers are coming up more than once; this would be more
efficient as a set comprehension, but leave that aside for now.

Note also that the range for i has to go as far as the square root of
the number we're working with - we have to go as far as 7*7==49. If
you want primes to some higher cap, say 100, you'd need to also
increase that, eg range(2,11).

> The change that I tried to apply to this comprehension would lead to the 
> following pattern: noprimes = = [[4, 6,8…48], [6, 9, 12….], ….,[some numbers]]
>
> But despite my struggling on it for the whole day, I haven’t got to the 
> desirable result(using comprehensions only)
>
> Please, don’t get me wrong, I’m not a lazy one (just a beginner).
>
> In my case, I  made some googling, and found some patterns for matrices, that 
> look this one(for example):
>
> Matrix = [[0 for x in range(5)] for x in range(5)]

The inner lists there can be created more simply, since you're working
with integers:

[[0]*5 for x in range(5)]

> But when I tried to use square brackets with my code, it yields an error 
> about definition of “i”, for instance:
>
> File "", line 1, in 
>
> noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]
>
> NameError: name 'i' is not defined.

That's because you have your nesting backwards. Instead of having the
for loops running left-to-right, they now are explicitly bracketed to
be the other way around. This is more like:

noprimes = []
for j in range(i*2, 50, i):
noprimes.append([j for i in range(2, 8)])

which can be unrolled another level:

noprimes = []
for j in range(i*2, 50, i):
tmp = []
for i in range(2, 8):
tmp.append(j)
noprimes.append(tmp)

Now you can see why i doesn't exist there.

> So I moved further, and succeeded to solve my problem in a different manner:
> >>> noprimes=[]
>
> >>> for i in range(2,8):
>
> noprimes.append(list(range(i*2,50,i)))
>
> Which yields, in fact, the matrix I wanted from the beginning:
>
> Yep, this the “classical” way for me, on the other hand I have the feeling, 
> that this is not, the ultimate solution. ^_^

In fact, this is exactly right, and now you can easily translate that
back to list comp syntax:

noprimes = [list(range(i*2,50,i)) for i in range(2,8)]

> So my questions is still persists:
>
> 1)  Is it possible to realize such a thing by applying changes only to 
> initial comprehension? If yes, it would be nice to see the solution.
> 2)  How actually bad is my solution? I mean, after all, there are nested 
> functions call in my code,  so how much the speed is affected(if any)?

Don't worry about speed of function calls. The algorithm used here is
so utterly appalling that it's going to get in your way long before
the performance of Python will. :)

List comprehensions are fairly readily convertible to and from
explicit loops. There are a couple of minor differences (a list comp
is actually executed inside a nested function, so the loop iterator
variable can't leak out), but generally, if you're having trouble,
just unroll the comprehension into a loop and see if it makes more
sense.

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


Recurring Task

2014-11-23 Thread tim
Hi All
Looking for some advice. I'm creating a small netwok poller and wondered what 
people recommend to use? Will be polling up to 100 hosts every ten reconds or so

Options I can see

Home grown using worker threads with Queue and dispatcher based on timestamp

Twisted timer service

Python Scheduler

Has anyone done anything similar and can share some insight?

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


Re: I have no class

2014-11-23 Thread Mark Lawrence

On 23/11/2014 03:55, Rustom Mody wrote:

On Sunday, November 23, 2014 9:06:03 AM UTC+5:30, Seymore4Head wrote:

Now I am trying to add a dictionary, but it is broke too.

How do I fix:
class RPS:
 key={0:"rock", 1:"paper",2:"scissors"};
 def __init__(self):
 self.throw=random.randrange(3)
 self.key=key[self.throw]


Maybe you want this?

class RPS:
 key ={0:"rock", 1:"paper", 2:"scissors"}
 def __init__(self):
 self.throw=random.randrange(3)
 self.key=RPS.key[self.throw]

Whether reusing 'key' like this is a good idea is another matter!



As I'm hopeless at thinking of good names to me it's always 'lookup'.

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

Mark Lawrence

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


RE: Comprehension with two variables - explanation needed

2014-11-23 Thread Ivan Evstegneev
>Is this what you want?
>
 [[j for j in range(i*2, 50, i)] for i in range(2,8)]
>[[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48],
[8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, >15, 20, 25, 30, 35, 40,
45], [12, 18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]]

>[I am not sure what you are trying -- just making local changes to the ZF
to make it work]

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

Yes, awesome. Thanks.

But it breaks all the picture that I've built in my head about comps till
now...

As I know from books and googling, the comps main idea looks approximately
like this:

[target <--main loop<--nested loop/s (and maybe some conditions)]Am I
right? 

But your code looks somehow inverted to me o_0

Like: 

[[target with nested  loop] <--- main loop with initial values for target]

On the other hand, if I'm comparing to my tryouts:

noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]

It looks same but the variables are not separated, so it definitely  was not
defined

Sincerely,

Ivan


 




-Original Message-
From: Python-list
[mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of
Rustom Mody
Sent: Sunday, November 23, 2014 17:09
To: python-list@python.org
Subject: Re: Comprehension with two variables - explanation needed

On Sunday, November 23, 2014 8:28:16 PM UTC+5:30, Ivan Evstegneev wrote:
> Hello guys,
>  
> I would like to ask you for some explanations on comprehensions. 
> (Don't be scared, it just some particular example ^_^)
>  
> I found this little "find prime number" example over the internet:
>  
> >>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] 
> >>> primes = [x for x in range(2, 50) if x not in noprimes] print 
> >>> primes
> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>  
>  
> It looked  pretty clear to me, till the time I decided to make some 
> changes to it %)))
>  
> Ok this is the case: 
>  
> As you can see the first line's comprehension produces a list, that
includes all the multiplications of "i" (that range(2,8) ) in range (i*2,
50, i).
> So  I get this pattern: noprimes  = =  [4, 6, 8.48, 6, 9,12 ].
> The change that I tried to apply to this comprehension would lead to 
> the following pattern: noprimes = = [[4, 6,8...48], [6, 9, 12], 
> ,[some numbers]]
>  
> But despite my struggling on it for the whole day, I haven't got to 
> the desirable result(using comprehensions only)
>  
> Please, don't get me wrong, I'm not a lazy one (just a beginner). 
>  
> In my case, I  made some googling, and found some patterns for matrices,
that look this one(for example):
>  
> Matrix = [[0 for x in range(5)] for x in range(5)]
>  
> But when I tried to use square brackets with my code, it yields an error
about definition of "i", for instance:
>  
> File "", line 1, in  noprimes = [[j for i in 
> range(2, 8)] for j in range(i*2, 50, i)]
> NameError: name 'i' is not defined.

Is this what you want?

>>> [[j for j in range(i*2, 50, i)] for i in range(2,8)]
[[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48],
[8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, 15, 20, 25, 30, 35, 40,
45], [12, 18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]]

[I am not sure what you are trying -- just making local changes to the ZF to
make it work]
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: ImportError: cannot import name 'Enum'

2014-11-23 Thread muhammedabuali
On Sunday, November 23, 2014 2:20:20 PM UTC+2, Chris Angelico wrote:
> On Sun, Nov 23, 2014 at 11:10 PM,   wrote:
> > Hello all,
> >
> > I am trying to use the python module but when I open the shell and write:
> >
> > ` import enum `
> >
> > I get the following error
> >
> > ` Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "/usr/lib/python3.4/enum.py", line 3, in 
> > from types import MappingProxyType, DynamicClassAttribute
> >   File "/home/muhammed/workspace/python/unification/types.py", line 1, in 
> > 
> > from enum import Enum
> > ImportError: cannot import name 'Enum'
> 
> Thank you for making it so clear and easy! By posting the entire
> traceback, plus everything you're expecting to see, you clearly show
> what's going on. THANK YOU!
> 
> What's happening here is that you have a file called "types.py".
> Unfortunately that name shadows the 'types' module in the standard
> library, and enum calls on that. So you'll need to rename your file,
> and then all should be well.
> 
> ChrisA

thank you alot! I didn't expect a reply that fast. I see the error now.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 2:37 AM, Ivan Evstegneev
 wrote:
> As I know from books and googling, the comps main idea looks approximately
> like this:
>
> [target <--main loop<--nested loop/s (and maybe some conditions)]Am I
> right?
>
> But your code looks somehow inverted to me o_0
>
> Like:
>
> [[target with nested  loop] <--- main loop with initial values for target]

Your analysis is correct, and it's because of the bracketing. Just as
you learned back in maths class (or math class, if you're that sort),
you start from the innermost brackets and work your way out. In fact,
the nested example starts with the main loop, and for each value it
goes through, it creates the entire inner comprehension.

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


RE: Comprehension with two variables - explanation needed

2014-11-23 Thread Skip Montanaro
> But it breaks all the picture that I've built in my head about comps till
> now...

Note that list comprehensions are little more than syntactic sugar for for
loops. If you're having terrible writing or understanding one, especially a
compound one like your example, it can help to write it as a (nested) for
loop, then covert it (perhaps incrementally) to the list comp form.

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


Re: Challenge: optimizing isqrt

2014-11-23 Thread Dave Angel

On 11/21/2014 03:15 AM, Stephen Tucker wrote:





On Thu, Nov 20, 2014 at 6:00 PM, Serhiy Storchaka 
wrote:


On 01.11.14 03:29, Steven D'Aprano wrote:


There is an algorithm for calculating the integer square root of any
positive integer using only integer operations:



Here is my optimized implementation inspired by Christian's ideas.

 
def isqrt(n):
 if n < 0:
 raise ValueError
 if n == 0:
 return 0
 if n <= C1:
 return int(math.sqrt(n))
 if n <= C2:
 x = int(math.sqrt(n))
 else:
 b = (n.bit_length() - C3) // 2
 x = int(math.sqrt(n >> (2 * b))) << b
 y = (x + n // x) // 2
 if y == x:
 return x
 while True:
 x = y
 y = (x + n // x) // 2
 if y >= x:
 return x

> Serhiy,

>
> This looks very good indeed. As a matter of interest, is there any
> particular reason you have used 2*b instead of b+b? Might b+b be faster
> than b*2?
>
> Also, in various lines, you use //2. Would >>1 be quicker? On reflection,
> perhaps you have had to use //2 because >>1 cannot be used in those
> situations.
>
> Stephen Tucker.
>

(Please don't top-post here.  I moved your remarks after the code you're 
referencing, so that others may see it in the preferred order)


It's been probably two decades since I've been in a programming 
situation where that kind of difference mattered.  In Python in 
particular, the actual arithmetic or bit shifting is probably only one 
part in a hundred, and in modern processors all these operations tend to 
be very close in timing.


You're welcome to use the timeit module to try to measure it.  But I 
doubt it makes a difference of more than one part in a thousand.  And in 
some situations I can imagine b+b to be slower than 2*b. (For example, 
if b were global)



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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Roy Smith
In article ,
 Skip Montanaro  wrote:

> > But it breaks all the picture that I've built in my head about comps till
> > now...
> 
> Note that list comprehensions are little more than syntactic sugar for for
> loops. If you're having terrible writing or understanding one, especially a
> compound one like your example, it can help to write it as a (nested) for
> loop, then covert it (perhaps incrementally) to the list comp form.

Or not.  If it was complicated enough that you needed to loopify it to 
understand what it's doing, have pity on the next person who has to 
maintain your code and leave it as a loop :-)

My general rule for code hygiene is, "If I have to think about whether 
something is too complicated, it is".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I have no class

2014-11-23 Thread Seymore4Head
On Sun, 23 Nov 2014 10:16:28 -0500, Dave Angel 
wrote:

>On 11/23/2014 05:52 AM, Seymore4Head wrote:
>> On Sun, 23 Nov 2014 17:00:08 +1100, Chris Angelico 
>> wrote:
>>
>>>
>>> 1) Python's namespacing rules mean that 'key' is a part of the RPS
>>> class, and can be referred to as 'self.key' or as 'RPS.key'
>>> 2) Use of 'self.key' for the textual form of the throw is shadowing
>>> the first of those reference names (but it's a poor name anyway)
>>> 3) A list would work just as well as a dictionary here, since your
>>> indices are sequential and start from zero
>>> 4) There's another function in the random module which can do both of
>>> your steps at once.
>>>
>>> Thank you for helping us help you help us all!
>>>
>>> ChrisA
>>
>> I wish I could explain my problems so precisely.  I will try to do
>> better in the future.
>> Thanks
>>
>> I will also try this using a list instead of a dictionary.
>>
>
>And please avoid the shadowing.  It's confusing whenever the same name 
>is used for a class attribute and an instance attribute of the same 
>class.  it can be useful for defaults and such, but not here.
>
>  class RPS:
>  KEY_TABLE={0:"rock", 1:"paper",2:"scissors"};
>   or
>  KEY_TABLE= ("rock", "paper", "scissors")
>  def __init__(self):
>  self.throw=random.randrange(3)
>  self.key=RPS.KEY_TABLE[self.throw]
>
>Note I also capitalized the tuple name, which is a convention saying we 
>don't intend to modify it.

I just learned by trial and error if I moved "key" out of the class, I
could still use it in the class without having to give it a RPS
extension.

I also changed it to a list and it works fine.

Thanks

key =["rock", "paper", "scissors"]
class RPS:
def __init__(self):
self.throw=random.randrange(3)
self.key=key[self.throw]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I have no class

2014-11-23 Thread Dave Angel

On 11/23/2014 10:54 AM, Seymore4Head wrote:

On Sun, 23 Nov 2014 10:16:28 -0500, Dave Angel 
wrote:


On 11/23/2014 05:52 AM, Seymore4Head wrote:

On Sun, 23 Nov 2014 17:00:08 +1100, Chris Angelico 
wrote:



1) Python's namespacing rules mean that 'key' is a part of the RPS
class, and can be referred to as 'self.key' or as 'RPS.key'
2) Use of 'self.key' for the textual form of the throw is shadowing
the first of those reference names (but it's a poor name anyway)
3) A list would work just as well as a dictionary here, since your
indices are sequential and start from zero
4) There's another function in the random module which can do both of
your steps at once.

Thank you for helping us help you help us all!

ChrisA


I wish I could explain my problems so precisely.  I will try to do
better in the future.
Thanks

I will also try this using a list instead of a dictionary.



And please avoid the shadowing.  It's confusing whenever the same name
is used for a class attribute and an instance attribute of the same
class.  it can be useful for defaults and such, but not here.

  class RPS:
  KEY_TABLE={0:"rock", 1:"paper",2:"scissors"};
   or
  KEY_TABLE= ("rock", "paper", "scissors")
  def __init__(self):
  self.throw=random.randrange(3)
  self.key=RPS.KEY_TABLE[self.throw]

Note I also capitalized the tuple name, which is a convention saying we
don't intend to modify it.


I just learned by trial and error if I moved "key" out of the class, I
could still use it in the class without having to give it a RPS
extension.


It's not an extension, it's a namespace qualifier.  That's a good thing, 
to constrain a particular name to as narrow a scope as possible.  In 
other words, instead of making it a global variable, put it in the 
namespace that gives it meaning.




I also changed it to a list and it works fine.

Thanks

key =["rock", "paper", "scissors"]
class RPS:
 def __init__(self):
 self.throw=random.randrange(3)
 self.key=key[self.throw]



But it belongs in the class, doesn't it?  If other code wants to use it, 
it'd be better if all references were of the form  RPS.KEY_TABLE.  And 
it should be a tuple, not a list, as you're not planning to change it.




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


Re: PyWart: "Python's import statement and the history of external dependencies"

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:23 AM, Dennis Lee Bieber
 wrote:
> On Sun, 23 Nov 2014 18:43:40 +1100, Ben Finney 
> declaimed the following:
>
>>  PostgreSQL is a full-blown system that is itself under continual
>>  development, and its APIs continually change to match. Whatever Python
>>  API for PostgreSQL gets put into the standard library today is likely
>>  to be obsolete long before today's version of Python gets close to
>>  ending support. That makes it a poor candidate for inclusion in the
>>  standard library.
>>
> I'd also consider that such a module is highly dependent upon having
> the related server available. If PostgreSQL access were to become a
> standard module I'd argue that the library should also include MySQL,
> Firebird/Interbase, M$ SQL Server, at a minimum.

I don't know how many ought to be included, but definitely MySQL would
be wanted. Including clients for proprietary protocols may be
considered less important. It would also be logical to include some of
the meta-protocols, though, like ODBC.

> SQLite3, as a file-server database, made sense as the actual database
> engine is accessed as part of the Python process when invoked -- not
> something that had to be configured/administered at a system-wide level.

This is true, and I've seen plenty of explanations as to why SQLite3
but no other database. I just found it odd that, against the exclusion
of several modules which would be of significant value to a very
common Python use-case (namely, servers (eg web) that need back-end
databases) is the inclusion of something equally specific but less
commonly useful (.WAV file manipulation). But, that's what PyPI's for.

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


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:33 AM, Dennis Lee Bieber
 wrote:
> On Sat, 22 Nov 2014 20:52:37 -0500, random...@fastmail.us declaimed the
> following:
>
>>On Sat, Nov 22, 2014, at 18:38, Mark Lawrence wrote:
>>> ...
>>> That is a standard Windows build. He is again conflating problems with
>>> using the Windows command line for a given code page with the FSR.
>>
>>The thing is, with a truetype font selected, a correctly written win32
>>console problem should be able to print any character without caring
>
> Why would that be possible? Many truetype fonts only supply glyphs for
> single-byte encodings (ISO-Latin-1, for example -- pop up the Windows
> character map utility and see what some of the font files contain.

A program should be able to print those characters even if they all
look identical. Chances are you can copy and paste them into something
else. But yes, finding a suitable font that covers the whole Unicode
range is *hard*. I've struggled with this one with a few programs (and
I still haven't managed to get VLC to satisfactorily display subtitles
that include Chinese characters).

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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Skip Montanaro
On Sun, Nov 23, 2014 at 9:57 AM, Roy Smith  wrote:
>
> If it was complicated enough that you needed to loopify it to
> understand what it's doing, have pity on the next person who has to
> maintain your code and leave it as a loop

Well, sure. I was mostly trying to give Ivan a path out of the weeds.
Poking through the code I'm involved with at work, using a crude
measuring stick (a couple regular expressions) I found over 1400 one
line list comprehensions, those which matched this regular expression:

\[.* for .*\]

OTOH, I only found 14 with two "for" keywords:

\[.* for .* for .*\]

(There may well have been more nested loop list comprehensions, simply
because it's hard to cram the full listcomp into 80 columns, my
self-imposed column limit.)

In my experience, list comprehensions rapidly get unwieldy once you
get to nesting them. I generally unravel such items into a nested set
of for loops.

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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Rustom Mody
On Sunday, November 23, 2014 9:27:22 PM UTC+5:30, Roy Smith wrote:
>  Skip Montanaro wrote:
> 
> > > But it breaks all the picture that I've built in my head about comps till
> > > now...
> > 
> > Note that list comprehensions are little more than syntactic sugar for for
> > loops. If you're having terrible writing or understanding one, especially a
> > compound one like your example, it can help to write it as a (nested) for
> > loop, then covert it (perhaps incrementally) to the list comp form.
> 
> Or not.  If it was complicated enough that you needed to loopify it to 
> understand what it's doing, have pity on the next person who has to 
> maintain your code and leave it as a loop :-)
> 
> My general rule for code hygiene is, "If I have to think about whether 
> something is too complicated, it is".

[I guess I am in the minority here... anyways... here goes]

1. I find comprehensions are harder than for-loops -- corollary to
functional code is easier than imperative --
corollary to time is a major headache. If the problem does not
involve time the solution should try to avoid it

2. "List comprehensions are syntactic sugar for for loops"
Cannot technically quarrel with that as that is the position of the official
docs.
However to me it puts the cart before the horse.
Its like saying that 

def foo(x): return x+1

is just the same as

  0 LOAD_FAST0 (x)
  3 LOAD_CONST   1 (1)
  6 BINARY_ADD
  7 RETURN_VALUE


(output of dis)

That may be the case but it seems (to me at least) to defeat the purpose
of using an hi-level language.

3. So how should one think of list comprehensions?
   As a python/executable version of 'set-builder notation'
   http://en.wikipedia.org/wiki/Set-builder_notation

4. Finally to the OP (assuming you wanted a prime-number generator)
Heres a solution for your consideration.

First a one-line solution in haskell

sieve (p:xs)   =p:sieve [x | x <- xs, x `mod` p /= 0]

Call with sieve [2..]

Now a pythonification of that

def n2s():  # natural nos from 2; ie [2..]
i=2
while True:
yield i
i+=1

def sieve(l):
p = next(l)
yield p
yield from sieve (x for x in l if x % p != 0)


Call as
for p in sieve(n2s()): print(p)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I have no class

2014-11-23 Thread Seymore4Head
On Sun, 23 Nov 2014 11:14:34 -0500, Dave Angel 
wrote:

>On 11/23/2014 10:54 AM, Seymore4Head wrote:
>> On Sun, 23 Nov 2014 10:16:28 -0500, Dave Angel 
>> wrote:
>>
>>> On 11/23/2014 05:52 AM, Seymore4Head wrote:
 On Sun, 23 Nov 2014 17:00:08 +1100, Chris Angelico 
 wrote:

>
> 1) Python's namespacing rules mean that 'key' is a part of the RPS
> class, and can be referred to as 'self.key' or as 'RPS.key'
> 2) Use of 'self.key' for the textual form of the throw is shadowing
> the first of those reference names (but it's a poor name anyway)
> 3) A list would work just as well as a dictionary here, since your
> indices are sequential and start from zero
> 4) There's another function in the random module which can do both of
> your steps at once.
>
> Thank you for helping us help you help us all!
>
> ChrisA

 I wish I could explain my problems so precisely.  I will try to do
 better in the future.
 Thanks

 I will also try this using a list instead of a dictionary.

>>>
>>> And please avoid the shadowing.  It's confusing whenever the same name
>>> is used for a class attribute and an instance attribute of the same
>>> class.  it can be useful for defaults and such, but not here.
>>>
>>>   class RPS:
>>>   KEY_TABLE={0:"rock", 1:"paper",2:"scissors"};
>>>or
>>>   KEY_TABLE= ("rock", "paper", "scissors")
>>>   def __init__(self):
>>>   self.throw=random.randrange(3)
>>>   self.key=RPS.KEY_TABLE[self.throw]
>>>
>>> Note I also capitalized the tuple name, which is a convention saying we
>>> don't intend to modify it.
>>
>> I just learned by trial and error if I moved "key" out of the class, I
>> could still use it in the class without having to give it a RPS
>> extension.
>
>It's not an extension, it's a namespace qualifier.  That's a good thing, 
>to constrain a particular name to as narrow a scope as possible.  In 
>other words, instead of making it a global variable, put it in the 
>namespace that gives it meaning.
>
>>
>> I also changed it to a list and it works fine.
>>
>> Thanks
>>
>> key =["rock", "paper", "scissors"]
>> class RPS:
>>  def __init__(self):
>>  self.throw=random.randrange(3)
>>  self.key=key[self.throw]
>>
>
>But it belongs in the class, doesn't it?  If other code wants to use it, 
>it'd be better if all references were of the form  RPS.KEY_TABLE.  And 
>it should be a tuple, not a list, as you're not planning to change it.

Like I have said, most of the stuff I am doing is still trial and
error.  Having to specify RPS to use it inside the class seemed wrong
to me.

I haven't read enough about classes yet to know what the correct way
is yet.

I will leave it in.

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


Re: I have no class

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:49 AM, Seymore4Head
 wrote:
> Like I have said, most of the stuff I am doing is still trial and
> error.  Having to specify RPS to use it inside the class seemed wrong
> to me.
>
> I haven't read enough about classes yet to know what the correct way
> is yet.

That's because Python doesn't really do the whole "infinitely-nested
scopes" thing that you see in C-like languages. (That kind of scoping
doesn't really work without declared variables, which is completely
against the Python model.) So you have to be a bit more explicit about
where you want to reference things from. What you can do is use 'self'
instead of the class name; that's often the cleanest way to do it.

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


Re: I have no class

2014-11-23 Thread Rustom Mody
On Sunday, November 23, 2014 10:20:05 PM UTC+5:30, Seymore4Head wrote:
> Like I have said, most of the stuff I am doing is still trial and
> error.  Having to specify RPS to use it inside the class seemed wrong
> to me.

Yes that is natural.
Python is a bit odd in the OO-world in that it prioritizes
"Explicit is better than implicit" over convenience.

Notice that you use self.throw where in most other OOP languages
you would use just throw.

Since the whole point of making 'key' (the table) a class variable
as against an instance variable is that it is not attached to 
self.
So where is it attached?
Answer follows from "Explicit is better than implicit"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Roy Smith
We seem to be somewhat more liberal about nested comprehensions here, but I 
can't say I'm proud of that :-)

906 Python source files, 109k lines. 

$ find . -name '*.py' | xargs grep '\[.* for .*\]' | wc -l
729

$ find . -name '*.py' | xargs grep '\[.* for .* for .*\]' | wc -l
46

Without naming names, a quick look into our nested comprehensions with "hg 
blame" shows a very strong correlation between "people who wrote many nested 
comprehensions" and "people who's code I find difficult to read in general".  I 
see one of these that has my name on the commit:

   report = [keys] + [[line[key] for key in keys] for line in results]

but I'm glad to report that this was merely some third-party code that I 
imported into our repo.  Whew, that was close!

On Nov 23, 2014, at 11:45 AM, Skip Montanaro wrote:

> On Sun, Nov 23, 2014 at 9:57 AM, Roy Smith  wrote:
>> 
>> If it was complicated enough that you needed to loopify it to
>> understand what it's doing, have pity on the next person who has to
>> maintain your code and leave it as a loop
> 
> Well, sure. I was mostly trying to give Ivan a path out of the weeds.
> Poking through the code I'm involved with at work, using a crude
> measuring stick (a couple regular expressions) I found over 1400 one
> line list comprehensions, those which matched this regular expression:
> 
> \[.* for .*\]
> 
> OTOH, I only found 14 with two "for" keywords:
> 
> \[.* for .* for .*\]
> 
> (There may well have been more nested loop list comprehensions, simply
> because it's hard to cram the full listcomp into 80 columns, my
> self-imposed column limit.)
> 
> In my experience, list comprehensions rapidly get unwieldy once you
> get to nesting them. I generally unravel such items into a nested set
> of for loops.
> 
> Skip
> 


--
Roy Smith
r...@panix.com



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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Rustom Mody
On Sunday, November 23, 2014 10:15:51 PM UTC+5:30, Rustom Mody wrote:
> 1. I find comprehensions are harder than for-loops -- 

Heh! Meant to say 'easier' of course...
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Comprehension with two variables - explanation needed

2014-11-23 Thread Ivan Evstegneev
Got the main idea. 
Still need to "chew it up"  in depth. (As I mentioned I'm a beginner EE
student, so please excuse me for my  "lameness"  ^_^)

-Original Message-
From: Python-list
[mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of
Rustom Mody
Sent: Sunday, November 23, 2014 18:46
To: python-list@python.org
Subject: Re: Comprehension with two variables - explanation needed

On Sunday, November 23, 2014 9:27:22 PM UTC+5:30, Roy Smith wrote:
>  Skip Montanaro wrote:
> 
> > > But it breaks all the picture that I've built in my head about 
> > > comps till now...
> > 
> > Note that list comprehensions are little more than syntactic sugar 
> > for for loops. If you're having terrible writing or understanding 
> > one, especially a compound one like your example, it can help to 
> > write it as a (nested) for loop, then covert it (perhaps incrementally)
to the list comp form.
> 
> Or not.  If it was complicated enough that you needed to loopify it to 
> understand what it's doing, have pity on the next person who has to 
> maintain your code and leave it as a loop :-)
> 
> My general rule for code hygiene is, "If I have to think about whether 
> something is too complicated, it is".

[I guess I am in the minority here... anyways... here goes]

1. I find comprehensions are harder than for-loops -- corollary to
functional code is easier than imperative -- corollary to time is a major
headache. If the problem does not involve time the solution should try to
avoid it

2. "List comprehensions are syntactic sugar for for loops"
Cannot technically quarrel with that as that is the position of the official
docs.
However to me it puts the cart before the horse.
Its like saying that 

def foo(x): return x+1

is just the same as

  0 LOAD_FAST0 (x)
  3 LOAD_CONST   1 (1)
  6 BINARY_ADD
  7 RETURN_VALUE


(output of dis)

That may be the case but it seems (to me at least) to defeat the purpose of
using an hi-level language.

3. So how should one think of list comprehensions?
   As a python/executable version of 'set-builder notation'
   http://en.wikipedia.org/wiki/Set-builder_notation

4. Finally to the OP (assuming you wanted a prime-number generator) Heres a
solution for your consideration.

First a one-line solution in haskell

sieve (p:xs)   =p:sieve [x | x <- xs, x `mod` p /= 0]

Call with sieve [2..]

Now a pythonification of that

def n2s():  # natural nos from 2; ie [2..]
i=2
while True:
yield i
i+=1

def sieve(l):
p = next(l)
yield p
yield from sieve (x for x in l if x % p != 0)


Call as
for p in sieve(n2s()): print(p)
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Jon Ribbens
On 2014-11-23, Roy Smith  wrote:
> In article ,
>  Skip Montanaro  wrote:
>> > But it breaks all the picture that I've built in my head about comps till
>> > now...
>> 
>> Note that list comprehensions are little more than syntactic sugar for for
>> loops. If you're having terrible writing or understanding one, especially a
>> compound one like your example, it can help to write it as a (nested) for
>> loop, then covert it (perhaps incrementally) to the list comp form.
>
> Or not.  If it was complicated enough that you needed to loopify it to 
> understand what it's doing, have pity on the next person who has to 
> maintain your code and leave it as a loop :-)
>
> My general rule for code hygiene is, "If I have to think about whether 
> something is too complicated, it is".

My reminder rule for nested comprehensions is "Which way do you
instinctively think they should nest and makes logical sense?
They don't work that way."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread random832
On Sun, Nov 23, 2014, at 11:33, Dennis Lee Bieber wrote:
>   Why would that be possible? Many truetype fonts only supply glyphs for
> single-byte encodings (ISO-Latin-1, for example -- pop up the Windows
> character map utility and see what some of the font files contain.

With a bitmap font selected, the characters will be immediately replaced
with characters present in the font's codepage, and will copy to
clipboard as such.

With a truetype font (Lucida Console or Consolas) selected, the
characters will be displayed as replacement glyphs (box with a question
mark in it) if not present in the font, but *will still copy to the
clipboard as the original code point* (which you might notice is where
we started, with someone claiming success by being able to do so with
codepage 65001 selected). And in any case, all characters that *are* in
the font will work and display correctly, rather than only those in the
OEM codepage.

>   Heck -- on my current machine, the True Type fonts are all old
> third-party items. All the standard fonts are now Open Type.

The win32 console's configuration UI refers to opentype fonts as
truetype. Opentype fonts can use either truetype or type 1 as the
underlying format, and all opentype fonts supplied with windows use
truetype. You are being excessively pedantic in objecting to my use of
the term "truetype".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recurring Task

2014-11-23 Thread Dan Stromberg
On Sun, Nov 23, 2014 at 7:23 AM,   wrote:
> Hi All
> Looking for some advice. I'm creating a small netwok poller and wondered what 
> people recommend to use? Will be polling up to 100 hosts every ten reconds or 
> so
>
> Options I can see
>
> Home grown using worker threads with Queue and dispatcher based on timestamp

This might be good, as might the multiprocessing module.

> Twisted timer service

I wouldn't wish a large Twisted project on my worst enemy.  If you
need async, you might consider gevent.

> Python Scheduler

Perhaps - I have no experience with this.

I'd probably go the multiprocessing route.  multithreading is fine
with CPython if you're 100% I/O bound, but as soon as you add one
CPU-bound thread, the multitasking gets all messed up - unless you
move to jython.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recurring Task

2014-11-23 Thread Dan Stromberg
On Sun, Nov 23, 2014 at 10:35 AM, Dennis Lee Bieber
 wrote:
> On Sun, 23 Nov 2014 07:23:43 -0800 (PST), t...@timothyarnold.co.uk declaimed
> the following:
>
>>Hi All
>>Looking for some advice. I'm creating a small netwok poller and wondered what 
>>people recommend to use? Will be polling up to 100 hosts every ten reconds or 
>>so
>>
>
> Trickiest part would be maintaining the time-ordered queue (has Python
> created a priority queue yet? -- Ah, apparently it has -- so one could use
> the desired clock value for the priority, and when the thread finishes it
> requeues incrementing the clock value by the rescan interval... -- you'd
> need to implement a sleep_until if the thread grabs an entry before its
> time)

The standard library way: https://docs.python.org/3/library/queue.html
Here's another way - a class I ported from Java:
https://pypi.python.org/pypi/fibonacci-heap-mod

The Fibonacci Heap is theoretically nice because it's lazy and
supports some interesting operations like O(1) merge and O(1)
decrease-key, but it has a large constant on its O(logn) dequeue-min.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Dave Angel

On 11/23/2014 01:13 PM, random...@fastmail.us wrote:

On Sun, Nov 23, 2014, at 11:33, Dennis Lee Bieber wrote:

Why would that be possible? Many truetype fonts only supply glyphs for
single-byte encodings (ISO-Latin-1, for example -- pop up the Windows
character map utility and see what some of the font files contain.


With a bitmap font selected, the characters will be immediately replaced
with characters present in the font's codepage, and will copy to
clipboard as such.


I didn't realize Windows shell (DOS box) had that bug.  Course I don't 
use Windows much the last few years.


it's one thing to not display it properly.  It's quite another to supply 
faulty data to the clipboard.  Especially since the Windows clipboard 
has a separate Unicode type available.


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


Re: Help with Python Multiprocessing

2014-11-23 Thread Anurag
Hey Socha,
Your solution works. But then, all my 3 workers are running in a single command 
window. How do I make them run in three different command windows?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 7:31 AM, Dave Angel  wrote:
> On 11/23/2014 01:13 PM, random...@fastmail.us wrote:
>>
>> On Sun, Nov 23, 2014, at 11:33, Dennis Lee Bieber wrote:
>>>
>>> Why would that be possible? Many truetype fonts only supply
>>> glyphs for
>>> single-byte encodings (ISO-Latin-1, for example -- pop up the Windows
>>> character map utility and see what some of the font files contain.
>>
>>
>> With a bitmap font selected, the characters will be immediately replaced
>> with characters present in the font's codepage, and will copy to
>> clipboard as such.
>
>
> I didn't realize Windows shell (DOS box) had that bug.  Course I don't use
> Windows much the last few years.

Likewise. I've been accustomed to copying and pasting unrecognized
characters (one of the easiest solutions is to paste them into a
Python console - ord() for one character, or a Py2 repr() for multiple
- to quickly see what the codepoints are), relying on the clipboard
getting the exact same sequence that was printed by the application.
Thanks, Windows, just what I always wanted to hear.

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


Re: PyWart: "Python's import statement and the history of external dependencies"

2014-11-23 Thread Gregory Ewing

Chris Angelico wrote:

Just out of curiosity, why does the stdlib need modules for
manipulating .wav and other sound files, but we have to go to PyPI to
get a PostgreSQL client?


I suspect it's mainly for historical reasons. The wave
module has been around since the very early days of
Python when the stldib was smaller and the barrier
to entry was lower. By today's standards, it probably
wouldn't make it in.

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


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Gregory Ewing

Marko Rauhamaa wrote:

Unicode strings is not wrong but the technical emphasis on Unicode is as
strange as a "tire car" or "rectangular door" when "car" and "door" are
what you usually mean.


The reason Unicode gets emphasised so much is that
until relatively recently, it *wasn't* what "string"
usually meant in Python.

When Python 3 has been around for as long as Python
2 was, things may change.

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


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 9:51 AM, Gregory Ewing
 wrote:
> Marko Rauhamaa wrote:
>>
>> Unicode strings is not wrong but the technical emphasis on Unicode is as
>> strange as a "tire car" or "rectangular door" when "car" and "door" are
>> what you usually mean.
>
>
> The reason Unicode gets emphasised so much is that
> until relatively recently, it *wasn't* what "string"
> usually meant in Python.
>
> When Python 3 has been around for as long as Python
> 2 was, things may change.

I doubt it; the bytes() type is sufficiently stringy to require the
distinction to still be made. PEP 461 makes it clear that byte strings
are not blobs of opaque data, but are very definitely ASCII-compatible
objects, for the benefit of boundary code.

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


"**" in python

2014-11-23 Thread Abdul Abdul
Hello,

I came across an example that showed the following:

Wxy**2

What do ** mean here?

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


Re: "**" in python

2014-11-23 Thread Tim Chase
On 2014-11-24 01:33, Abdul Abdul wrote:
> Wxy**2
> 
> What do ** mean here?

"to the power of", so your code squares the value of "Wxy", or "Wxy *
Wxy"

https://docs.python.org/2/reference/expressions.html#the-power-operator

-tkc



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


Re: "**" in python

2014-11-23 Thread Mark Lawrence

On 24/11/2014 00:33, Abdul Abdul wrote:

Hello,

I came across an example that showed the following:

Wxy**2

What do ** mean here?

Thanks.




You can find out about these by going to 
https://docs.python.org/3/genindex.html and clicking on 'Symbols' which 
takes you to https://docs.python.org/3/genindex-Symbols.html where ** is 
the 11th one down in the left hand column.


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

Mark Lawrence

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


Re: "**" in python

2014-11-23 Thread Cameron Simpson

On 23Nov2014 18:43, Tim Chase  wrote:

On 2014-11-24 01:33, Abdul Abdul wrote:

Wxy**2

What do ** mean here?


"to the power of", so your code squares the value of "Wxy", or "Wxy *
Wxy"

https://docs.python.org/2/reference/expressions.html#the-power-operator


With respect to finding this out for yourself, if you go the Python docs:

 https://docs.python.org/3/

and follow the "index" link at the top right:

 https://docs.python.org/3/genindex.html

and in that page, follow the "Symbols" link:

 https://docs.python.org/3/genindex-Symbols.html

you will find "**" there, along with a lot of other operator and syntax stuff.

Cheers,
Cameron Simpson 

Swiftkey, [...] teaches one the lamentable lesson that most
English speakers start most sentences, phrases and sub-clauses
with 'I'. One does not use the word often oneself and it therefore
strikes one as a little unfair that one's texts and emails so often
end up littered with implications of egocentricity. - Stephen Fry
http://www.stephenfry.com/2012/04/03/four-and-half-years-on/9/
--
https://mail.python.org/mailman/listinfo/python-list


Re: unloading a module created with imp.new_module

2014-11-23 Thread Ian Kelly
On Nov 23, 2014 4:10 AM, "Patrick Stinson"  wrote:
> m = types.ModuleType('mine')
> exec(s, m.__dict__)
> print('deleting...')
> m = None
> print('done')
>
> and the output is:
>
> deleting...
> done
> __del__
>
> I the “__del__" to come between “deleting…” and “done”. This is not being
run from the interactive interpreter by via a .py file.

This suggests the presence of a reference cycle, since the object is
deleted afterward by the garbage collector. One cycle here is that the
__del__ function has a reference to the module's globals dict, which has a
reference to the class instance, which has a reference to the class, which
has a reference back to the function. There may be other cycles here as
well, but it may also be that the module object itself isn't part of them.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread llanitedave
On Sunday, November 23, 2014 12:22:30 AM UTC-8, Frank Millman wrote:
> "Chris Angelico"  wrote in message 
> news:captjjmp4y5zowwn5yftjutko4h5jvtqlantwqepa6b35xnd...@mail.gmail.com...
> >
> > Entirely possible. I never did track down the actual cause of the
> > SQLite3 issues my students were having; though I suspect it's not
> > purely a Python API issue. I tried to demonstrate the concept of
> > foreign keys using the sqlite3 command line tool, and did a sequence
> > of commands which ought to have failed, but didn't.
> 
> The default is for sqlite3 to ignore foreign key contraints.
> 
> To enable them, add the following -
> 
> pragma foreign_keys = on;
> 
> It works for me.
> 
> Unfortunately it has a limitation, which they acknowledge but they say is 
> unlikely to be addressed. You can access more than one database concurrently 
> by using the 'attach' command, and qualifying a remote tablename as 
> {database} dot {tablename}. You can then include the remote table in any sql 
> command. However, it will not enforce foreign key constraints across 
> databases.
> 
> Frank Millman

Well in this case the foreign keys ARE on, otherwise it wouldn't be throwing up 
a foreign key  conflict.  I've got one more thing to try, but so far I still 
haven't figured out why it's not accepting the foreign key data.  The only 
thing I can conclude so far is that it chokes if the fields are TEXT.  I've got 
other foreign keys in the database that are more traditional integer fields, 
and they seem to be working fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "**" in python

2014-11-23 Thread Dan Stromberg
On Sun, Nov 23, 2014 at 5:00 PM, Cameron Simpson  wrote:
> On 23Nov2014 18:43, Tim Chase  wrote:
>>
>> On 2014-11-24 01:33, Abdul Abdul wrote:
>>>
>>> Wxy**2
>>>
>>> What do ** mean here?
>>
>>
>> "to the power of", so your code squares the value of "Wxy", or "Wxy *
>> Wxy"
>>
>> https://docs.python.org/2/reference/expressions.html#the-power-operator
>
>
> With respect to finding this out for yourself, if you go the Python docs:
>
>  https://docs.python.org/3/
>
> and follow the "index" link at the top right:
>
>  https://docs.python.org/3/genindex.html
>
> and in that page, follow the "Symbols" link:
>
>  https://docs.python.org/3/genindex-Symbols.html
>
> you will find "**" there, along with a lot of other operator and syntax
> stuff.

You can also learn this with Google, by searching for:
 python "star star"

It takes you to a stackoverflow page about python exponentiation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "**" in python

2014-11-23 Thread Skip Montanaro
I want to add one more thing to the other responses. People new to Python
often seem unaware that being an interpreted language, often the best way
to figure something out is to simply try it at the interpreter prompt. The
OP saw "var ** 2" in done code. The most obvious thing to me would have
been to type

var = 42
var ** 2

and see what happened. It's unlikely to trigger a nuclear meltdown, or even
crash the interpreter.

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


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread llanitedave
On Saturday, November 22, 2014 6:11:22 PM UTC-8, llanitedave wrote:
> I've built a database in SQLite3 to be embedded into a python application 
> using wxPython 2.8.12 and Python 2.7.6.  I'm using Sqliteman to manage the 
> database directly and make changes to the structure when necessary.
> 
> One item that's been bugging me is when I'm inserting records into one 
> particular table:
> 
> The parent table is called "borehole", and the 'borehole_id' field is TEXT.  
> It's essentially a name field, because every borehole name is naturally 
> unique, therefore I thought an autoincrementing integer would be superfluous.
> 
> A related field is called "core_run", and its foreign key field is named 
> "of_borehole" -- of course its type is TEXT NOT NULL as well.  It's described 
> in the "DESCRIBE TABLE" feature of Sqliteman as "FOREIGN KEY(of_borehole) 
> REFERENCES borehole(borehole_id)"
> 
> When I use Sqliteman to manually create a record using INSERT INTO core_run 
> VALUES..., it works properly.  However, when I do the same thing, using the 
> same test data, from inside Python, I get the following SQLite error"
> 
> 'foreign key mismatch - "core_run" referencing "borehole"'
> 
> To make sure the core_run.of_borehole and borehole.borehole_id fields are 
> equivalent, I inserted a logging statement just prior to the database cursor.
> 
> [code]
> # retrieve the borehole id field, check it matches with of_borehole field
> db_cursor.execute("select borehole_id from borehole where borehole_id = ?", 
> (runfields[1],))
> relatedbh = db_cursor.fetchone()[0]
> logging.info("Related borehole_id is %s, of_borehole is %s", relatedbh, 
> runfields[1])
> [/code]
> 
> runfields[1] here is the of_borehole field taken from the applications GUI 
> field.
> 
> In this case, the displayed data from both is identical -- the logging line 
> comes back as:
> INFO:Related borehole_id is testbh3, of_borehole is testbh3
> 
> So the data type is the same, and the content appears to be the same.  So why 
> would there be a foreign key mismatch?  Is it possible that there is some 
> invisible code in the string which isn't being detected by the logging 
> command?  Is this just a quirk of the Sqlite3 implementation in Python that 
> demands foreign keys be integers?
> 
> I feel like I've hit a brick wall here.
> 
> Thanks!

OK, I got it working.  VICTORY!

Here's what I did.

The original CREATE TABLE command for the core_run table defined all the fields 
and then added the foreign key at the bottom of the definition like so:

"FOREIGN KEY(of_borehole) REFERENCES borehole(borehole_id)"

I recreated the table and put the foreign key reference directly into the field 
definition:

"of_borehole TEXT NOT NULL REFERENCES borehole,"

This is a valid alternative according to the SQLite3 docs, if you don't 
explicitly define the field name then it references to the primary key that 
already exists in the referenced table.

And that's all I had to do.  Strange, but it did the trick.

For the enhanced version of this application I will DEFINITELY use an integer 
primary key for the boreholes table!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "**" in python

2014-11-23 Thread llanitedave
On Sunday, November 23, 2014 5:49:05 PM UTC-8, Skip Montanaro wrote:
> I want to add one more thing to the other responses. People new to Python 
> often seem unaware that being an interpreted language, often the best way to 
> figure something out is to simply try it at the interpreter prompt. The OP 
> saw "var ** 2" in done code. The most obvious thing to me would have been to 
> type
> 
> var = 42
> 
> var ** 2
> 
> and see what happened. It's unlikely to trigger a nuclear meltdown, or even 
> crash the interpreter.
> 
> Skip


I dunno, if it took 7.5 million years to come up with the answer in the first 
place, imagine how long it might take to square it!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unloading a module created with imp.new_module

2014-11-23 Thread Ned Batchelder

On 11/23/14 1:49 AM, Patrick Stinson wrote:

If I create a module with imp.new_module(name), how can I unload it so that all 
the references contained in it are set to zero and the module is deleted? 
deleting the reference that is returned doesn’t seem to do the job, and it’s 
not in sys.modules, so where is the dangling reference?

Thanks!



This sounds tricky, and possible very difficult to do properly.  Do you 
mind if I ask what the larger problem is?  Python might not be very good 
at having modules come and go as you want.


--
Ned Batchelder, http://nedbatchelder.com

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


Why do I keep getting emails from Dennis?

2014-11-23 Thread Sayth Renshaw
I keep receiving emails from Dennis and it appears Dennis only on this
list, I am signed up to comp.lang.python and am unsure why I keep getting
Dennis' s emails.

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


Re: Why do I keep getting emails from Dennis?

2014-11-23 Thread Michael Torrie
On 11/23/2014 08:21 PM, Sayth Renshaw wrote:
> I keep receiving emails from Dennis and it appears Dennis only on this
> list, I am signed up to comp.lang.python and am unsure why I keep getting
> Dennis' s emails.

If you post to the newsgroup, using your e-mail address as the "from
address", when people who use this list via e-mail respond, and click
"reply all" it will go back to the list and to your e-mail address.

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


Re: unloading a module created with imp.new_module

2014-11-23 Thread Steven D'Aprano
On Sat, 22 Nov 2014 21:49:32 -0900, Patrick Stinson wrote:

> If I create a module with imp.new_module(name), how can I unload it so
> that all the references contained in it are set to zero and the module
> is deleted? deleting the reference that is returned doesn’t seem to do
> the job, and it’s not in sys.modules, so where is the dangling
> reference?

It would be very surprising (although not impossible) if you have found a 
bug in the garbage collector. More likely you've just misinterpreted what 
you're seeing.

Can you please reply to the list with the simplest example of code that 
behaves in the way you are describing?

(If you reply to me privately, I may not get to see it for days or weeks, 
and when I do, my response will be to ask you to resend it to the list. 
So save all of us some time by replying directly to the list.)

If you're experimenting in the interactive interpreter, be aware that it 
holds onto a reference to the last few objects displayed. IPython can 
hold on to an unlimited number of such references, but the standard 
Python REPL only holds onto one. That can confound experimentation:


py> import imp, gc, types
py> mymodule = imp.new_module("mymodule")
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[]
py> del mymodule
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[]


It appears that the module isn't being garbage collected. But that's 
because the list [] is being held in the interactive 
interpreter's special _ variable. If we get rid of that by displaying 
something else, the module is garbage collected:


py> 23
23
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[]



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


Re: I have no class

2014-11-23 Thread Steven D'Aprano
On Sun, 23 Nov 2014 09:02:57 -0800, Rustom Mody wrote:

> Python is a bit odd in the OO-world in that it prioritizes "Explicit is
> better than implicit" over convenience.
> 
> Notice that you use self.throw where in most other OOP languages you
> would use just throw.

I don't think that is correct. I think that most OOP languages are like 
Python, and use a special variable to reference the current instance:

"self" is used by:
Smalltalk, Python, Perl, Objective-C, Swift, Ruby, OCAML

"this" is used by:
C++, C#, Java, D, Javascript, F#, Cobra, PHP, Powershell

"me" is used by:
ABAP Objects, Visual Basic

"Current" is used by:
Eiffel


http://en.wikipedia.org/wiki/This_(computer_programming)


http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(object-
oriented_programming)#Special_variables


In some of these languages, the use of "this/self/me" is optional, but 
I'm not aware of *any* OOP language where there is no named reference to 
the current object at all.

In any case, Python is not unusual in this regard.


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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Steven D'Aprano
On Sun, 23 Nov 2014 08:45:39 -0800, Rustom Mody wrote:

> 2. "List comprehensions are syntactic sugar for for loops" Cannot
> technically quarrel with that as that is the position of the official
> docs.
> However to me it puts the cart before the horse. Its like saying that
> 
> def foo(x): return x+1
> 
> is just the same as
> 
>   0 LOAD_FAST0 (x)
>   3 LOAD_CONST   1 (1)
>   6 BINARY_ADD
>   7 RETURN_VALUE
> 
> 
> (output of dis)


The two situations are not related. The output of dis is an 
implementation detail. Try running it under IronPython or Jython and see 
what you get. Even in CPython, it is still an implementation detail 
subject to change. Today dis() returns the above, tomorrow it may return:

  0 LOAD_GLOBAL  0 (x)
  3 INCREMENT
  5 RETURN_VALUE

(say), and the Python code remains the same even though the byte code is 
different.

Whereas the statement that "comprehensions are syntactic sugar for for-
loops" is a statement about the semantics of comprehensions. It's a 
language promise, part of the API of Python, and not subject to change 
without a period of deprecation.  It is a promise that

[expression for name in sequence]

is closely equivalent to:

for name in sequence:
expression


(They are not *identical* because list comprehensions collect the result 
of expression into a list, set comprehensions collect them into a set, 
etc. But the actual looping part is the same.)


> 3. So how should one think of list comprehensions?
>As a python/executable version of 'set-builder notation'
>http://en.wikipedia.org/wiki/Set-builder_notation

For those who learned, and remember, set-builder notation, that is an 
excellent analogy.


> 4. Finally to the OP (assuming you wanted a prime-number generator)
> Heres a solution for your consideration.
> 
> First a one-line solution in haskell
> 
> sieve (p:xs)   =p:sieve [x | x <- xs, x `mod` p /= 0]

Don't use that! That is a horribly inefficient way to generate primes.

Mathematically, it is a version of Euler's Sieve. It is sometimes wrongly 
described as "Sieve of Eratosthenes", but that is wrong. Due to it's 
horrible performance, Melissa O'Neill calls this the "Sleight on 
Eratosthenes":

http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf

Asymptotic behaviour of this is O(N**2/(log N)**2) which is worse than 
trial division and only *marginally* better than this stupidly naive 
version:

def primes0():
i = 2
yield i
while True:
i += 1
composite = False
for p in range(2, i):
if i%p == 0:
composite = True
if not composite:  # It must be a prime.
yield i



> Call with sieve [2..]
> 
> Now a pythonification of that
[...]





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


Re: SQLite3 in Python 2.7 Rejecting Foreign Key Insert

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 1:22 PM, llanitedave
 wrote:
> I recreated the table and put the foreign key reference directly into the 
> field definition:
>
> "of_borehole TEXT NOT NULL REFERENCES borehole,"
>
> This is a valid alternative according to the SQLite3 docs, if you don't 
> explicitly define the field name then it references to the primary key that 
> already exists in the referenced table.
>
> And that's all I had to do.  Strange, but it did the trick.

That's also perfectly valid according to the SQL spec. I prefer to put
the foreign key up there where possible (obviously it's not possible
with a multi-column FK, but those aren't common). Strange that the
other form doesn't work.

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


Re: "**" in python

2014-11-23 Thread Steven D'Aprano
On Sun, 23 Nov 2014 19:48:50 -0600, Skip Montanaro wrote:

> I want to add one more thing to the other responses. People new to
> Python often seem unaware that being an interpreted language, often the
> best way to figure something out is to simply try it at the interpreter
> prompt. The OP saw "var ** 2" in done code. The most obvious thing to me
> would have been to type
> 
> var = 42
> var ** 2
> 
> and see what happened. It's unlikely to trigger a nuclear meltdown, or
> even crash the interpreter.

Hmmm, it appears that ** is a no-op that always returns its left hand 
argument:


py> 0**2
0
py> 0**7
0
py> 0**99
0

Of course, that could be a coincidence, better try a few other things:

py> 1**57
1
py> 57**1
57
py> -1**12
-1



:-)



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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:42 PM, Steven D'Aprano  wrote:
> Today dis() returns the above, tomorrow it may return:
>
>   0 LOAD_GLOBAL  0 (x)
>   3 INCREMENT
>   5 RETURN_VALUE
>
> (say), and the Python code remains the same even though the byte code is
> different.

I hope not! The x in the original function was a local, not a global,
and if dis.dis() says LOAD_GLOBAL for something that's not global, it
would be *very* confusing! :)

But yes, CPython could grow an INCREMENT bytecode, and it'd not break anything.

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


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread random832
On Sun, Nov 23, 2014, at 15:31, Dave Angel wrote:
> I didn't realize Windows shell (DOS box) had that bug.  Course I don't 
> use Windows much the last few years.
> 
> it's one thing to not display it properly.  It's quite another to supply 
> faulty data to the clipboard.  Especially since the Windows clipboard 
> has a separate Unicode type available.

It's because console bitmap fonts almost always (always?) only have one
codepage's worth of characters, and it's considered better to display A
for U+0100 than a blank space, and the clipboard has always been a bit
of an afterthought for the windows console. Meanwhile, a truetype font
is considered likely to have real glyphs for most characters a user
would want to display, so no conversion is done. And there's no font
rendering routine for bitmap fonts that will allow for dynamic
substitution of glyphs, so it becomes a real A (or whatever) in the
console buffer itself - this isn't a conversion done at clipboard-copy
time.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I have no class

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:21 PM, Steven D'Aprano  wrote:
> On Sun, 23 Nov 2014 09:02:57 -0800, Rustom Mody wrote:
>
>> Python is a bit odd in the OO-world in that it prioritizes "Explicit is
>> better than implicit" over convenience.
>>
>> Notice that you use self.throw where in most other OOP languages you
>> would use just throw.
>
> I don't think that is correct. I think that most OOP languages are like
> Python, and use a special variable to reference the current instance:
>
> In some of these languages, the use of "this/self/me" is optional, but
> I'm not aware of *any* OOP language where there is no named reference to
> the current object at all.

I believe his point is that Python, unlike every other language he can
think of, requires "self.x" instead of just "x". Every language needs
a way to say "current object", but not every language needs you to say
that for every member reference. C++, Pike, and Java let you
short-hand that. (They're all deriving from the same syntactic style
anyway.) JavaScript doesn't, I believe, although its variable scoping
rules are some of the most insane I've ever met, so there might be a
way to shortcut it. If your experience of OO is mainly from C++/Java
family languages, then yes, Python will seem odd.

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


Re: I have no class

2014-11-23 Thread Dave Angel

On 11/23/2014 11:21 PM, Steven D'Aprano wrote:


In some of these languages, the use of "this/self/me" is optional, but
I'm not aware of *any* OOP language where there is no named reference to
the current object at all.



The case I found astounding in C++ was in the initializer list where the 
line


value:value

would assume that the first one was  this->value, and the second was a 
local named value (usually an argument to the constructor).



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


Re: "**" in python

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 3:47 PM, Steven D'Aprano  wrote:
> Hmmm, it appears that ** is a no-op that always returns its left hand
> argument:
>
> py> -1**12
> -1

Ahh but you see, you misunderstand how the whole negative-numbers
thing works. You have your syntax wrong. Python was developed by an
accountant, and you write negative numbers like this:

>>> (1)**12
1

And then, because you're raising it to an even power, you get back
positive one. The hyphen is actually an alignment operator, and it
means "left-align this value".

https://www.python.org/dev/peps/pep-0461/
https://docs.python.org/2/library/stdtypes.html#string-formatting

:)

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


Re: "**" in python

2014-11-23 Thread Sturla Molden
Abdul Abdul  wrote:
 
> Wxy**2
> 
> What do ** mean here?

Exponentiation. Same as ** means in Fortran.

Sturla

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


Re: I have no class

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 4:11 PM, Dave Angel  wrote:
> The case I found astounding in C++ was in the initializer list where the
> line
>
> value:value
>
> would assume that the first one was  this->value, and the second was a local
> named value (usually an argument to the constructor).

That's occasionally quite useful. You can create a variable which
shadows another, and reference the original in its initialization, as
a simple means of mocking for debug:

//Maybe a global, or at least at wider scope
string separator="whatever... maybe pulled from a MIME document";
...
{
string separator="** DEBUG **"+separator+"** DEBUG **";
...
code using separator
...
}

You can comment or uncomment the debug line, and everything inside the
braces will be affected by its alteration - but nothing outside them
will, because it's shadowed and not altered. Can be extremely handy.

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


Re: I have no class

2014-11-23 Thread Dave Angel

On 11/24/2014 12:11 AM, Dave Angel wrote:

On 11/23/2014 11:21 PM, Steven D'Aprano wrote:


In some of these languages, the use of "this/self/me" is optional, but
I'm not aware of *any* OOP language where there is no named reference to
the current object at all.



The case I found astounding in C++ was in the initializer list where the
line

 value:value

would assume that the first one was  this->value, and the second was a
local named value (usually an argument to the constructor).




That was rather sloppy.  Since this is only used in a constructor, and 
it appears before the body of the function/method, the second one must 
be an argument, or else something non-local.


Anyway, the construct is a bit of a surprise the first time you see it.

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


Re: PyWart: "Python's import statement and the history of external dependencies"

2014-11-23 Thread Rick Johnson
On Sunday, November 23, 2014 4:37:53 PM UTC-6, Gregory Ewing wrote:
> Chris Angelico wrote:
> > Just out of curiosity, why does the stdlib need modules
> > for manipulating .wav and other sound files, but we have
> > to go to PyPI to get a PostgreSQL client?
>
> I suspect it's mainly for historical reasons. The wave
> module has been around since the very early days of
> Python when the stldib was smaller and the barrier
> to entry was lower. By today's standards, it probably
> wouldn't make it in.

Immigration policies evolve basically in the same manner.
When a country is founded in a land which is sparsely
populated, naturally the state will welcome any and all
immigrants (as noted in the "New Colossus"), but as the
population becomes more and more dense, the natural (and
wise) reaction is to limit, or even prohibit, the influx of
migrants.


 PSYCHOANALYSIS OF MIGRANT/STATE SYMBIOSIS:


The majority my readers would probably agree that any state
which projected such liberal immigration policies would be
doing so based on pure "selfishness", and they would be
correct, however, most would fail to realize that both the
migrant *AND* the state are basing their decisions on pure
selfishness.

THERE IS NO SUCH THING AS A PURELY SELFISH ACT!

For the state, gaining citizens means expanding it's
military power (you know, the whole "power-in-numbers"
thing), and expanding it's economic power (money, money,
money!), and last but not least, expanding it's tax base
(hey, did i mention money yet?).

GREED IS PROPAGATED BY THE SYNERGY OF "SYMBIOTIC SELFISHNESS"!

For the migrant, he seeks to gain or benefit by some means,
because if he did not gain something *positive* from the
interaction, then he would not be a migrant, no, by
definition he would be a *masochist*! Like the old saying
goes: "When your at the bottom, the only direction you can
go is up!". So by this definition, the migrant seeks to
utilize the resources in his "new land" for he failed to
utilize in his "home land".

FLIES DON'T CARE MUCH FOR VINEGAR, BUT THEY SURE LOVE HONEY!

In the balance of this "relationship", the state is more
venerable than the migrant. The state only survives *if* it
can maintain its population (but more importantly *IF* it
can maintain a "quality" population!), but the migrant can
survive under *any* state that is willing to provide for
him, he need not pledge allegiance to any one state, no, no,,,
and if at any point the relationship becomes untenable for
him, he has proven *already* his willingness to betray his
responsibility as an equal member of this symbiosis, by
simply re-locating!

But is the migrant *really* an equal member?  No. The
migrant does not share equally the burdens of the symbiosis.
Since the migrant is free to utilize the resources of the
state, and then simply pack-up and leave when the resources
are exhausted, the migrant is in-effect the master, and the
state is the slave. And although the state does extract a
tiny amount of power from the migrant, this power is useless
when one party can nullify the contract just because the
"honey pot" ran empty.


 CONCLUSION:


The migrant/state symbiosis is a fine example of how we (as
*weak* emotional beings) fall into these "emotional traps"
set by "forked tongued propagandist" in hopes of diverting
our attention away from reality. No being in this universe
makes any choice based on altruistic motives, no, altruism
is a mask worn by the most cunning of con-artist -- a true
weapon of deceit!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyWart: "Python's import statement and the history of external dependencies"

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 5:25 PM, Rick Johnson
 wrote:
> The migrant/state symbiosis is a fine example of how we (as
> *weak* emotional beings) fall into these "emotional traps"
> set by "forked tongued propagandist" in hopes of diverting
> our attention away from reality. No being in this universe
> makes any choice based on altruistic motives, no, altruism
> is a mask worn by the most cunning of con-artist -- a true
> weapon of deceit!

As CS Lewis wrote in various places, notably "The Screwtape Letters",
people who are fundamentally driven by pure selfishness are utterly
unable to even comprehend love and genuine altruism. Fortunately for
us, your email is both off-topic and useless, so we can cheerfully
ignore it.

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


Re: Comprehension with two variables - explanation needed

2014-11-23 Thread Rustom Mody
On Monday, November 24, 2014 10:13:04 AM UTC+5:30, Steven D'Aprano wrote:
> On Sun, 23 Nov 2014 08:45:39 -0800, Rustom Mody wrote:
> > First a one-line solution in haskell
> > 
> > sieve (p:xs)   =p:sieve [x | x <- xs, x `mod` p /= 0]
> 
> Don't use that! That is a horribly inefficient way to generate primes.
> 
> Mathematically, it is a version of Euler's Sieve. It is sometimes wrongly 
> described as "Sieve of Eratosthenes", but that is wrong. Due to it's 
> horrible performance, Melissa O'Neill calls this the "Sleight on 
> Eratosthenes":
> 
> http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf

Thanks for that link -- I'll need to look at it carefully
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Marko Rauhamaa
Gregory Ewing :
> Marko Rauhamaa wrote:
>> Unicode strings is not wrong but the technical emphasis on Unicode is as
>> strange as a "tire car" or "rectangular door" when "car" and "door" are
>> what you usually mean.
>
> The reason Unicode gets emphasised so much is that until relatively
> recently, it *wasn't* what "string" usually meant in Python.
>
> When Python 3 has been around for as long as Python 2 was, things may
> change.

Yes, people call strings "Unicdoe strings" because Python2 *did have*
unicode strings separate from regular strings:

Python2Python3
--
string bytes (byte string)
unicode string string


In Python2 days, Unicode was a fancy, exotic datatype for the
connoisseurs. The rest used strings. Python3 supposedly elevates Unicode
to boring normalcy. Now it's bytes that have fallen into (unmerited)
disfavor.

But old habits die hard; you call cars "automobile cars" instead of
"cars" since, after all, "cars" were always pulled by horses...


Marko

PS Maybe interestingly, Guile went through an analogous transition. As
of Guile 2.0,

  a character is anything in the Unicode Character Database.
  [...]
  Strings are fixed-length sequences of characters.
  [...]
  A bytevector is a raw bit string.

  https://www.gnu.org/software/guile/manual/html_node/index.html>

However, Guile 1.8 still had:

  The Guile implementation of character sets currently deals only with
  8-bit characters.

  https://www.gnu.org/software/guile/docs/docs-1.8/guile-ref/inde
  x.html>

and there were no bytevectors.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Chris Angelico
On Mon, Nov 24, 2014 at 5:57 PM, Marko Rauhamaa  wrote:
> Yes, people call strings "Unicdoe strings" because Python2 *did have*
> unicode strings separate from regular strings:
>
> Python2Python3
> --
> string bytes (byte string)
> unicode string string
>
>
> In Python2 days, Unicode was a fancy, exotic datatype for the
> connoisseurs. The rest used strings. Python3 supposedly elevates Unicode
> to boring normalcy. Now it's bytes that have fallen into (unmerited)
> disfavor.

Py3's byte strings are still strings, though. People don't use
bytearray for everything.

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


Re: python 2.7 and unicode (one more time)

2014-11-23 Thread Marko Rauhamaa
Chris Angelico :

> Py3's byte strings are still strings, though.

Hm. I don't think so. In a plain English sense, maybe, but that kind of
usage can lead to confusion.

For example,

   A subscription selects an item of a sequence (string, tuple or list)
   or mapping (dictionary) object:

   subscription ::=  primary "[" expression_list "]"

   [...]

   A string’s items are characters. A character is not a separate data
   type but a string of exactly one character.

   https://docs.python.org/3/reference/expressions.html#subscripti
   ons>


The text is probably a bit buggy since it skates over bytes and byte
arrays listed as sequences (by https://docs.python.org/3/reference/datamodel.html>). However, your
Python3 implementation would fail if it interpreted bytes objects to be
strings in the above paragraph:

   >>> "abc"[1]
   'b'
   >>> b'abc'[1]
   98

The subscription of a *string* evaluates to a *string*. The subscription
of a *bytes* object evaluates to a *number*.


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