which is the right file path format in python3.4 ?

2014-12-14 Thread sir

My system is :win7+python3.4  .

I want to write a new file "named names.txt"  in disk f:

 >>> ff=open(r"F:\names.txt","w")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 22] Invalid argument: 'F:\\names.txt'
>>> ff=open(r"F:/names.txt","w")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 22] Invalid argument: 'F:/names.txt'
>>> ff=open(r"F://names.txt","w")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 22] Invalid argument: 'F://names.txt'
>>> ff=open(r"f://names.txt","w")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 22] Invalid argument: 'f://names.txt'
>>> ff=open(r"f:/names.txt","w")
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 22] Invalid argument: 'f:/names.txt'

which is the right  file path format in python3.4 ?
--
https://mail.python.org/mailman/listinfo/python-list


Re: which is the right file path format in python3.4 ?

2014-12-14 Thread Irmen de Jong
On 14-12-2014 10:05, sir wrote:
> My system is :win7+python3.4  .
> 
> I want to write a new file "named names.txt"  in disk f:
> 
>  >>> ff=open(r"F:\names.txt","w")
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'F:\\names.txt'
 ff=open(r"F:/names.txt","w")
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'F:/names.txt'
 ff=open(r"F://names.txt","w")
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'F://names.txt'
 ff=open(r"f://names.txt","w")
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'f://names.txt'
 ff=open(r"f:/names.txt","w")
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'f:/names.txt'
> 
> which is the right  file path format in python3.4 ?

They all should work. (They do on my machine when subtituting F with a drive 
letter that
exists here. Win 7, Python 3.4.2).

It's something else on your end that is causing the error. Is drive F: full? Do 
you have
the correct permissions? Is it a network share that has certain restrictions?
What exact python is is that you are running?


Irmen

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


Re: which is the right file path format in python3.4 ?

2014-12-14 Thread Steven D'Aprano
sir wrote:

> My system is :win7+python3.4  .
> 
> I want to write a new file "named names.txt"  in disk f:
> 
>   >>> ff=open(r"F:\names.txt","w")
> Traceback (most recent call last):
>File "", line 1, in 
> OSError: [Errno 22] Invalid argument: 'F:\\names.txt'

Are you sure that you have an F drive?

Is it a writable disk? e.g. a hard drive, not a CD drive.

Do you have read and write permissions to F drive?


Run this code and show us what it prints:

import os
print(os.stat("F:\\")
print(os.access("F:\\", os.O_RDWR))




-- 
Steven

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


Re: which is the right file path format in python3.4 ?

2014-12-14 Thread Chris Angelico
On Sun, Dec 14, 2014 at 10:03 PM, Steven D'Aprano
 wrote:
> Run this code and show us what it prints:
>
> import os
> print(os.stat("F:\\")
> print(os.access("F:\\", os.O_RDWR))

(With an extra close parenthesis on the first print call)

I'm suspicious here that drive F might not even exist. I would expect
a permissions error to be errno 13, but "invalid argument" seems
really weird. Definitely these checks will be informative.

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


Re: which is the right file path format in python3.4 ?

2014-12-14 Thread Steven D'Aprano
Chris Angelico wrote:

> On Sun, Dec 14, 2014 at 10:03 PM, Steven D'Aprano
>  wrote:
>> Run this code and show us what it prints:
>>
>> import os
>> print(os.stat("F:\\")
>> print(os.access("F:\\", os.O_RDWR))
> 
> (With an extra close parenthesis on the first print call)

Thanks.

 
> I'm suspicious here that drive F might not even exist. I would expect
> a permissions error to be errno 13, but "invalid argument" seems
> really weird. Definitely these checks will be informative.

I don't have access to a Windows box to check, otherwise I would do it
myself. What happens if you specify a non-existent drive letter?

open("Q:\\xxx")  # Assuming you don't have a drive Q.




-- 
Steven

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


Re: which is the right file path format in python3.4 ?

2014-12-14 Thread Chris Angelico
On Sun, Dec 14, 2014 at 10:51 PM, Steven D'Aprano
 wrote:
> I don't have access to a Windows box to check, otherwise I would do it
> myself. What happens if you specify a non-existent drive letter?
>
> open("Q:\\xxx")  # Assuming you don't have a drive Q.

Hmm. I just grabbed one (granted, it's XP not W7) and checked it, and
it's not what I was expecting either.

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> open("Q:\\xxx")
Traceback (most recent call last):
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'Q:\\xxx'

Still, it might be something unusual about the OP's drive. Maybe a
network drive with a broken connection, or a mounted CD, or an alias
for another directory... who knows. Hopefully the stat and access
checks will reveal something.

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


how to delete my file if exits in the remote server with paramiko?

2014-12-14 Thread ????????
I want to delete the file "names.txt" if it exits in "/home/names.txt" in my 
remote vps server.
 import paramiko
host = "vps ip"
port = 22
transport = paramiko.Transport((host, port))
password = "key"
username = "root"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
if "names.txt" in sftp.listdir("/home") : sftp.remove("/home/names.txt")
  
  
 Is there more elegant way to do the same work?-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to delete my file if exits in the remote server with paramiko?

2014-12-14 Thread Skip Montanaro
On Sun, Dec 14, 2014 at 6:49 AM, 水静流深 <1248283...@qq.com> wrote:
> Is there more elegant way to do the same work?

Unlikely. You have two fairly simple bits of code in your example, one
to connect to the remote server, the other to check for the file's
existence and remove it. The only extra elegance I see is to isolate
those two bits of work into separate functions, so you execute
something like:

sftp = connect_via_paramiko("vps ip", 22)
remove_remote_file(sftp, "/home/names.txt")

Presumably, if you have other work to do on the server, you'd save the
sftp object for reuse.

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


Re: numpy question (fairly basic, I think)

2014-12-14 Thread Albert-Jan Roskam


- Original Message -

> From: Steven D'Aprano 
> To: python-list@python.org
> Cc: 
> Sent: Sunday, December 14, 2014 12:52 AM
> Subject: Re: numpy question (fairly basic, I think)
> 
> Albert-Jan Roskam wrote:
> 
>>  Hi,
>> 
>>  I am new to numpy. I am reading binary data one record at a time (I have
>>  to) and I would like to store all the records in a numpy array which I
>>  pre-allocate. Below I try to fill the empty array with exactly one record,
>>  but it is filled with as many rows as there are columns. Why is this? It
>>  is probably something simple, but I am stuck! It is like the original
>>  record is not unpacked *as in tuple unpacking) into the array, so it
>>  remains one chunk, not an (nrows, ncols) structure.
> 
> Can you simplify the example to something shorter that focuses on the issue
> at hand? It isn't clear to me which bits of the code you show are behaving
> the way you expect and which bits are not.


Hi Steven,

Thanks for replying. My code was so elaborate because I did not know which part 
made it go wrong. I think I have got it already. Numpy arrays (ndarrays) must 
be homogeneous wrt their datatype (dtype). 

Probably to make vectorization work (?). However, a structured array (which I 
was using) *can* contain multiple dtypes, but it can only be one-dimensional. 
Its records are tuples (or arrays). In this sense, even a structured array is 
homogeneous. I was trying to change the one-dim array into a two-dim array so I 
could easily retrieve columns. I now use a pandas DataFrame to do that. If my 
sample data would have contained *only* floats (or ints, or ...), my original 
approach would have worked. 


Thanks!

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


Re: Text Code(from 'Getting Started in Beautiful Soup' re: cd Soup , returns 'Syntax Error, invalid syntax'

2014-12-14 Thread Simon Evans
Thanks Guys 
This book keeps swapping from the Python console to the Windows - without 
telling you, but it is the only book out there on 'Beautiful Soup' so I have 
got to put up with it. There's more problems with it, but I will start a new 
thread in regard of, I don't know if its related to the above or not. 
Yours 
Simon.
-- 
https://mail.python.org/mailman/listinfo/python-list


SQLObject 1.7.2

2014-12-14 Thread Oleg Broytman
Hello!

I'm pleased to announce version 1.7.2, a bugfix release of branch
1.7 of SQLObject.


What's new in SQLObject
===

* Fix a bug: zero-pad microseconds on the right, not on the left; 0.0835
  seconds means 83500 microseconds.

For a more complete list, please see the news:
http://sqlobject.org/News.html


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
https://pypi.python.org/pypi/SQLObject/1.7.2

News and changes:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmanhttp://phdru.name/p...@phdru.name
   Programmers don't die, they just GOSUB without RETURN.
-- 
https://mail.python.org/mailman/listinfo/python-list


How to import sqlite3 in my python3.4 successfully?

2014-12-14 Thread sir
There are two python version in my debian7, one is python2.7 the system 
default version, the other is python3.4 which compiled to install this way.


|  apt-get  update
 apt-get  upgrade
 apt-get  install build-essential
 wget http://www.python.org/ftp/python/3.4.0/Python-3.4.0.tgz
 tar-zxvfPython-3.4.0.tgz
 cdPython-3.4.0
 mkdir/usr/local/python3.4
 ./configure--prefix=/usr/local/python3.4
 make
 make install
 ln-s/usr/local/python3.4/bin/python3.4/usr/bin/python3.4
 ln-s/usr/local/python3.4/bin/pip3.4/usr/bin/pip3.4|

I have installed sqlite this way on my debian.

|sudo apt-get  install sqlite3 libsqlite3-dev|

In python2.7

|root@rebuild:~#  python
Python  2.7.3  (default,  Mar  14  2014,  11:57:14)
[GCC4.7.2]  on linux2
Type  "help",  "copyright",  "credits"  or  "license"  for  more information.

 import  sqlite3|


In python3.4

|root@rebuild:~#  python3.4
Python  3.4.0  (default,  Nov  27  2014,  13:54:17)
[GCC4.7.2]  on linux
Type  "help",  "copyright",  "credits"  or  "license"  for  more information.

 import  sqlite3

Traceback  (most recent calllast):
  File  "",  line1,  in  
  File  "/usr/local/python3.4/lib/python3.4/sqlite3/__init__.py",  line23,  in  

from  sqlite3.dbapi2import  *
  File  "/usr/local/python3.4/lib/python3.4/sqlite3/dbapi2.py",  line26,  in  

from  _sqlite3import  *
ImportError:  No  module  named'_sqlite3'|

How can i import sqlite3 in my python3.4 successfully?

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


Re: how to delete my file if exits in the remote server with paramiko?

2014-12-14 Thread Roy Smith
In article ,
 "" <1248283...@qq.com> wrote:

> I want to delete the file "names.txt" if it exits in "/home/names.txt" in my 
> remote vps server.
>  import paramiko
> host = "vps ip"
> port = 22
> transport = paramiko.Transport((host, port))
> password = "key"
> username = "root"
> transport.connect(username = username, password = password)
> sftp = paramiko.SFTPClient.from_transport(transport)
> if "names.txt" in sftp.listdir("/home") : sftp.remove("/home/names.txt")
>   
>   
>  Is there more elegant way to do the same work?

I generally try to avoid using raw paramiko.  Fabric gives you a much 
nicer interface to the same basic functionality (and is indeed layered 
on top of paramiko).  The above functionality can be expressed in fabric 
as simply as:


-
from fabric.api import env, run

env.host_string = "my-remote-hostname"
run("rm -f /tmp/roy-temp")
-

Of course, I cheated a little bit.  I'm assuming you have ssh access to 
your remote host; the above code depends on that.  Going through sftp 
makes everything more difficult.  You can drive sftp through fabric, but 
it's a lot more painful.  I also assume that you can use ssh key 
authentication, which simplifies everything compared to passing 
usernames and passwords around.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Simon Evans
Dear Python programmers,
Having input the line of code in text: 
cd Soup 
to the Windows console, and having put the file 'EcologicalPyramid.html' into 
the Directory 'Soup', on the C drive, in accordance with instructions I input 
the following code to the Python console, as given on page 30 of 'Getting 
Started with Beautiful Soup':

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
...  soup = BeautifulSoup(ecological_pyramid,"lxml")
... producer_entries = soup.find("ul")
 
   ^
SyntaxError: invalid syntax
>>> producer_entries = soup.find("ul")
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'soup' is not defined
>>>
   ^

so I cannot proceed with the next line withh would 've been :

print(producer_entries.li.div.string)

which would've given (according to the book) the output:
---
plants

Maybe that is getting a bit far ahead, but I can't quite see where I have gone 
wrong - 'soup' has been defined as an object made of file 
'EcologicalPyramid.html

I hope you can help me on this point. 
Yours 
Simon
-- 
https://mail.python.org/mailman/listinfo/python-list


Classes - converting external function to class's method.

2014-12-14 Thread Ivan Evstegneev
Hello Everyone,

I have stuck a bit with this example(took this one from the book).

Here are a description steps of what I've done till now:
 

Step 1 - creating an empty namespace:

>>>class rec: pass

Step 2 - adding some attributes:

>>>rec.name = 'Bob' 
>>>rec.age = 40

Step 3 - Creating an instance:

>>>x= rec()

Step 4 - write down external function: 

>>>def uppername(obj):
return obj.name.upper()

Step 5 - applying this function on x:

>>>uppername(x)
'BOB'

Till this moment its Ok.

But:

Step 6 - Creating a class method:


>>>rec.method = uppername

Then using the "help" function I  get (just checking what happened):

>>>help(rec)
class rec(builtins.object)
 |  Methods defined here:
 |  
 |  method = uppername(obj)
 |  
 |  --
 |omitted text..

 |
 |  Data and other attributes defined here:
 |  
 |  age = 40
 |  
 |  name = 'Bob'


Then the same about x:

>>>help(x)
class rec(builtins.object)
 |  Methods defined here:
 |  
 |  method = uppername(obj)
 | ---
 omitted text .
|-


The last check I've made:

>>> help(x.method)
Help on method uppername in module __main__:

uppername() method of __main__.rec instance

>>> help(rec.method)
Help on function uppername in module __main__:

uppername(obj)

and now to the Step 7 - using this new "method" on x:

>>>x.method()
'BOB'

>>>rec.method()
.
.
TypeError: uppername() missing 1 required positional argument: 'obj'

and then:

>>>rec.method(rec)
'BOB'

So my the question is: what is going on here? How this actually works?

According to the book's downside note:

**
In fact, this is one of the reasons the self argument must always be
explicit in Python methods-because
methods can be created as simple functions independent of a class, they need
to make the implied instance
argument explicit. They can be called as either functions or methods, and
Python can neither guess nor
assume that a simple function might eventually become a class's method. The
main reason for the explicit
self argument, though, is to make the meanings of names more obvious: names
not referenced through
self are simple variables mapped to scopes, while names referenced through
self with attribute notation
are obviously instance attributes.

*

Keeping it in mind, I wrote this code:

>>> class myclass:
def __init__(self, value):
self.name = value
def myupper(self):
return self.name.upper()

And then:

>>> b = myclass('bob')
>>>b.myupper()
'BOB'

I made an assumption that this is what happens(roughly speaking) when I
write this:

>>>rec.method = uppername

Am I right? (close enough maybe?)


On the other hand, when I checked further:

>>>dir(x.method)
[, '__self__',...]

but 
>>>dir(rec.method)
[ list of method and  '__self__'  wasn't there.]

I got a "bit" confused. 

Why  actually in instance "x"
>>>x.method() 
can auto-assign an "x" to uppername() function argument, but it doesn't work
in a class "rec" itself?

So  I need to write down an "obj" argument manually.
Why '__self__' exists only in instance "x"? (maybe because "rec", initially
was created as an empty class?)

How does a function "uppername()" looks like, when I apply it to "rec"
class, so it becomes  a class's method?

So in such a case, when instance "x" receives an "update" it reads the new
method as I described above(I mean the code of "myclass")?


Thanks a  lot in advance,

Ivan. 




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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Ned Batchelder

On 12/14/14 11:15 AM, Simon Evans wrote:

Dear Python programmers,
Having input the line of code in text:
cd Soup
to the Windows console, and having put the file 'EcologicalPyramid.html' into 
the Directory 'Soup', on the C drive, in accordance with instructions I input 
the following code to the Python console, as given on page 30 of 'Getting 
Started with Beautiful Soup':

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

from bs4 import BeautifulSoup
with open("ecologicalpyramid.html","r") as ecological_pyramid:

...  soup = BeautifulSoup(ecological_pyramid,"lxml")
... producer_entries = soup.find("ul")

^
SyntaxError: invalid syntax


This SyntaxError is indicating that none of the code you have just typed 
was run.  The reason it's a syntax error is because the interactive 
prompt is a bit simplistic about how to handle multiple statements.  It 
wants a blank line after the with-clause.


Because none of these lines were run, you never opened your HTML file, 
never parsed it, and never assigned to the name "soup".



producer_entries = soup.find("ul")

Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'soup' is not defined



^

so I cannot proceed with the next line withh would 've been :

print(producer_entries.li.div.string)

which would've given (according to the book) the output:
---
plants

Maybe that is getting a bit far ahead, but I can't quite see where I have gone 
wrong - 'soup' has been defined as an object made of file 
'EcologicalPyramid.html

I hope you can help me on this point.


For complex code experiments, it's better to put the code in a file, and 
run the file.  But if you do want to use the interactive interpreter, 
enter code carefully, and watch out for the error messages.


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

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


Re: How to import sqlite3 in my python3.4 successfully?

2014-12-14 Thread Albert-Jan Roskam

---
On Sun, Dec 14, 2014 4:06 PM CET sir wrote:

>There are two python version in my debian7, one is python2.7 the system 
>default version, the other is python3.4 which compiled to install this way.
>
>|  apt-get  update
> apt-get  upgrade
> apt-get  install build-essential
> wget http://www.python.org/ftp/python/3.4.0/Python-3.4.0.tgz
> tar-zxvfPython-3.4.0.tgz
> cdPython-3.4.0
> mkdir/usr/local/python3.4
> ./configure--prefix=/usr/local/python3.4
> make
> make install
> ln-s/usr/local/python3.4/bin/python3.4/usr/bin/python3.4
> ln-s/usr/local/python3.4/bin/pip3.4/usr/bin/pip3.4|
>
>I have installed sqlite this way on my debian.
>
>|sudo apt-get  install sqlite3 libsqlite3-dev|
>
>In python2.7
>
>|root@rebuild:~#  python
>Python  2.7.3  (default,  Mar  14  2014,  11:57:14)
>[GCC4.7.2]  on linux2
>Type  "help",  "copyright",  "credits"  or  "license"  for  more information.
>>>  import  sqlite3|
>
>In python3.4
>
>|root@rebuild:~#  python3.4
>Python  3.4.0  (default,  Nov  27  2014,  13:54:17)
>[GCC4.7.2]  on linux
>Type  "help",  "copyright",  "credits"  or  "license"  for  more information.
>>>  import  sqlite3
>Traceback  (most recent calllast):
>  File  "",  line1,  in  
>  File  "/usr/local/python3.4/lib/python3.4/sqlite3/__init__.py",  line23,  in 
>  
>from  sqlite3.dbapi2import  *
>  File  "/usr/local/python3.4/lib/python3.4/sqlite3/dbapi2.py",  line26,  in  
> 
>from  _sqlite3import  *
>ImportError:  No  module  named'_sqlite3'|
>
>How can i import sqlite3 in my python3.4 successfully?
>

Did you get any errors after compiling? One of the things to do BEFORE you 
install python is sudo apt-get install libsqlite3-dev, and probably a couple 
more (but not for sqlite)
-- 
https://mail.python.org/mailman/listinfo/python-list


How to use the .isalpha() function correctly

2014-12-14 Thread Luke Tomaneng
Here a very small program that I wrote for Codecademy. When I finished, 
Codecademy acted like it was correct, but testing of this code revealed 
otherwise.
--
print 'Welcome to the Pig Latin Translator!'

# Start coding here!
raw_input("Enter a word:")
original = str(raw_input)
if len(original) > 0 and original.isalpha():
print original
else:
print "empty"
--
No matter what I type in, the result is "empty." What do I need to do in order 
for it to accept words?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Run Programming ?????

2014-12-14 Thread Luke Tomaneng
On Friday, December 12, 2014 4:40:01 AM UTC-8, Delgado Motto wrote:
> I travel alot, if not just interested in things of pocketable portability, 
> and was curious if you can tell me if Python can be LEARNED from beginner on 
> an IOS device ( with interest of being able to test my code, possibly even if 
> a free website is capable of reviewing scripts ) but if not then I prefer if 
> you can suggest a language that can be used from such a machine. My ultimate 
> goal is to be able to create web pages and internet bots capable of searching 
> specific things for me, simply to save me time in my day as little as 
> crawling Youtube for a song that fails to be uploaded or other related 
> examples. Please advise me. Thanks. 

Yes, you can learn  and write Python on iOS. There are several apps for this.

Here are some websites to look at: 
http://pythonforios.com/
https://itunes.apple.com/us/app/pythonista/id528579881?mt=8
http://kivy.org/#home
https://itunes.apple.com/us/app/python-3.2-for-ios/id519319292?mt=8
Codecademy: Code Hour

I don't know how well these work, but since there are so many, I am assuming at 
least a couple are decent.

I included Codecademy at the end just in case you need to review some basic 
syntax, but I'm not sure if you'll need it.

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


Re: encoding name mappings in codecs.py with email/charset.py

2014-12-14 Thread gst
Le vendredi 12 décembre 2014 04:21:14 UTC-5, Stefanos Karasavvidis a écrit :
> I've hit a wall with mailman which seems to be caused by pyhon's character 
> encoding names.
> 
> I've narrowed the problem down to the email/charset.py file. Basically the 
> following happens:
> 

Hi, 

it's all in the email.charset.ALIASES dict.

you could also simply patch the __str__ method of Charset :

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> import email.charset
>>> 
>>> c = email.charset.Charset('iso-8859-7')
>>> str(c)
'iso8859-7'
>>> 
>>> old = email.charset.Charset.__str__
>>> 
>>> def patched(self):
r = old(self)
if r.startswith('iso'):
return 'iso-' + r[3:]
return r

>>> 
>>> email.charset.Charset.__str__ = patched
>>> 
>>> str(c)
'iso-8859-7'
>>> 


regards,

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


Re: How to use the .isalpha() function correctly

2014-12-14 Thread Chris Warrick
On Sun, Dec 14, 2014 at 6:16 PM, Luke Tomaneng  wrote:
> Here a very small program that I wrote for Codecademy. When I finished, 
> Codecademy acted like it was correct, but testing of this code revealed 
> otherwise.
> --
> print 'Welcome to the Pig Latin Translator!'
>
> # Start coding here!
> raw_input("Enter a word:")
> original = str(raw_input)
> if len(original) > 0 and original.isalpha():
> print original
> else:
> print "empty"
> --
> No matter what I type in, the result is "empty." What do I need to do in 
> order for it to accept words?
> --
> https://mail.python.org/mailman/listinfo/python-list

That’s not where the error is, actually.  You are:

1. taking input with "Enter a word: " and NOT SAVING IT
2. setting original to a string representation of the function
`raw_input`, which is something like

>>> str(raw_input)
''

The correct way to do this is:

original = raw_input("Enter a word: ")

as raw_input already outputs a string.

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


Re: Run Programming ?????

2014-12-14 Thread Luke Tomaneng
On Sunday, December 14, 2014 9:24:54 AM UTC-8, Luke Tomaneng wrote:
> On Friday, December 12, 2014 4:40:01 AM UTC-8, Delgado Motto wrote:
> > I travel alot, if not just interested in things of pocketable portability, 
> > and was curious if you can tell me if Python can be LEARNED from beginner 
> > on an IOS device ( with interest of being able to test my code, possibly 
> > even if a free website is capable of reviewing scripts ) but if not then I 
> > prefer if you can suggest a language that can be used from such a machine. 
> > My ultimate goal is to be able to create web pages and internet bots 
> > capable of searching specific things for me, simply to save me time in my 
> > day as little as crawling Youtube for a song that fails to be uploaded or 
> > other related examples. Please advise me. Thanks. 
> 
> Yes, you can learn  and write Python on iOS. There are several apps for this.
> 
> Here are some websites to look at: 
> http://pythonforios.com/
> https://itunes.apple.com/us/app/pythonista/id528579881?mt=8
> http://kivy.org/#home
> https://itunes.apple.com/us/app/python-3.2-for-ios/id519319292?mt=8
> Codecademy: Code Hour
> 
> I don't know how well these work, but since there are so many, I am assuming 
> at least a couple are decent.
> 
> I included Codecademy at the end just in case you need to review some basic 
> syntax, but I'm not sure if you'll need it.
> 
> Luke Tomaneng

Sorry, I didn't include the actual link for Codecademy. Here you go:

https://itunes.apple.com/us/app/codecademy-code-hour/id762950096?mt=8
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classes - converting external function to class's method.

2014-12-14 Thread Steven D'Aprano
Ivan Evstegneev wrote:

> Hello Everyone,
> 
> I have stuck a bit with this example(took this one from the book).

The example you are working on (adding external functions as methods) is
actually a bit more complicated than it seems, as you have discovered. You
have this:

class rec: pass
rec.name = 'Bob'
rec.age = 40

x= rec()

def uppername(obj):
return obj.name.upper()

rec.method = uppername


This is almost equivalent to the following:

class rec:
name = 'Bob'
age = 40
def method(obj):
return obj.name.upper()


You then try to use this new method, by calling it from the instance:

x.method()
--> returns 'BOB' as you expected


In this case, it works as you expect. Python looks up "method" on the
instance, and doesn't find anything attached to the instance. It then looks
at the class "rec", which does have something called "method". Because this
is a function, Python knows to provide the instance x as the first
argument. So the call

x.method()

ends up turning into this:

   rec.method(x)

Your function uppername() receives x as the argument "obj", it looks up
obj.name (x.name) and returns it as uppercase.

The important part to see here is that when you call a method from an
instance:

instance.method()

Python *automatically* fills in the "self" argument using the instance. (In
your case, you called that argument "obj" instead of self, but Python
doesn't care what it is called.)

How does Python know to use x as self? Because it's written right there:
x.method uses x as the first argument for method. But this is only done for
*instances*, not classes.


Now you move on to calling the method from the class itself:

rec.method()
--> raises TypeError

rec.method(rec)
--> returns 'BOB'

Looking at this, I can guess you are using Python 3, because that won't work
in Python 2. Am I right?

When you call a method from the class, Python cannot fill in the "self"
argument because it doesn't know what instance to use. This is called
an "unbound method" in Python 2, but in Python 3 it is just a regular
function. 

The important thing here are these two rules:

* when you call a method from an instance, Python automatically binds 
  that instance to the first argument (usually called "self") of the 
  method:

  instance.method() --> method gets instance as the "self" argument

* when you call a method from the class, Python cannot bind an 
  instance to "self", so you have to do it:

  Class.method()  --> no argument is given!

  Class.method(instance)  --> method gets instance as "self"


In your example, you didn't actually pass an instance, you just passed the
class itself:

rec.method(rec)

But that's okay, because in *this case* the class has a "name" attribute, so
it all works out alright. But normally this would fail.

The actual mechanism for how Python does this is called the descriptor
protocol, and if you look it up you can find some explanations for it, but
be warned that it is quite technical and it is only for very advanced work
that you need to care about it.


> Keeping it in mind, I wrote this code:
> 
> class myclass:
> def __init__(self, value):
> self.name = value
> def myupper(self):
> return self.name.upper()
> 
> And then:
> 
> b = myclass('bob')
> b.myupper()
> 'BOB'
> 
> I made an assumption that this is what happens(roughly speaking) when I
> write this:
> 
> rec.method = uppername
> 
> Am I right? (close enough maybe?)

Close enough.



> On the other hand, when I checked further:
> 
dir(x.method)
> [, '__self__',...]

That is because you are looking the method up on the instance, x. If you
look it up on rec, there is no instance so Python cannot give it an
__self__ attribute.


> but
dir(rec.method)
> [ list of method and  '__self__'  wasn't there.]

Exactly!

You are looking at a complicated part of Object Oriented Programming, as
done by Python, so it is not surprising if it takes a while to understand
this. Please feel free to ask more questions if anything is unclear.


> I got a "bit" confused.
> 
> Why  actually in instance "x"
x.method()
> can auto-assign an "x" to uppername() function argument, but it doesn't
> work in a class "rec" itself?

When you have an instance

x.method

then Python knows which instance to use, because it is right there: x.

But if you have no instance, only the class:

rec.method

how does Python know which instance to use? There could be a million
instances, or none.

Let us look at some strings: the class is called "str", and we can have
many, many different instances:

"hello".upper()
--> returns "HELLO"

"goodbye".upper()
--> returns "GOODBYE"


But if I call the method from the class, which instance should it use?

str.upper()
 return "HELLO" or "GOODBYE" or "1234" or "ABCD" or ... 

The only way is for you to tell Python which instance to use:

str.upper("hello")  # just like "hello".upper()
--> returns "HELLO"



> So  I need to write d

Re: How to use the .isalpha() function correctly

2014-12-14 Thread Luke Tomaneng
On Sunday, December 14, 2014 9:27:14 AM UTC-8, Chris Warrick wrote:
> On Sun, Dec 14, 2014 at 6:16 PM, Luke Tomaneng  wrote:
> > Here a very small program that I wrote for Codecademy. When I finished, 
> > Codecademy acted like it was correct, but testing of this code revealed 
> > otherwise.
> > --
> > print 'Welcome to the Pig Latin Translator!'
> >
> > # Start coding here!
> > raw_input("Enter a word:")
> > original = str(raw_input)
> > if len(original) > 0 and original.isalpha():
> > print original
> > else:
> > print "empty"
> > --
> > No matter what I type in, the result is "empty." What do I need to do in 
> > order for it to accept words?
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> 
> That's not where the error is, actually.  You are:
> 
> 1. taking input with "Enter a word: " and NOT SAVING IT
> 2. setting original to a string representation of the function
> `raw_input`, which is something like
> 
> >>> str(raw_input)
> ''
> 
> The correct way to do this is:
> 
> original = raw_input("Enter a word: ")
> 
> as raw_input already outputs a string.
> 
> -- 
> Chris Warrick 
> PGP: 5EAAEA16

Thanks very much. I'm not sure how I missed that, since I've used the exact 
same method you mentioned before. You've been very helpful.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Simon Evans
I had another attempt at inputting the code perhaps with the right indentation, 
I still get an error return, but not one that indicates that the code has not 
been read, as you suggested. re:- 


Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
...  soup = BeautifulSoup(ecological_pyramid,"lxml")
... producer_entries = soup.find("ul")
  File "", line 3
producer_entries = soup.find("ul")
   ^
SyntaxError: invalid syntax
>>>  from bs4 import BeautifulSoup
  File "", line 1
from bs4 import BeautifulSoup

If, as you suggest I left a free line after the "with open( etc" line, console 
returns an error, if I leave a free line after the "soup = etc" line which 
comes after, again I get an error return, my only point is that with the above 
input, console return does not seem to infer that soup has not been defined. 
You recommend that I put all the code into a file then run it - how do I do 
that ? I am new to Python, as you might have gathered. 
Thank you for your help.
Yours Simon
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Jussi Piitulainen
Simon Evans writes:

> I had another attempt at inputting the code perhaps with the right
> indentation, I still get an error return, but not one that indicates
> that the code has not been read, as you suggested. re:-
> --
> 
> Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit
> (Intel)] on win 32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from bs4 import BeautifulSoup
> >>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
> ...  soup = BeautifulSoup(ecological_pyramid,"lxml")
> ... producer_entries = soup.find("ul")
>   File "", line 3
> producer_entries = soup.find("ul")
>^
> SyntaxError: invalid syntax

It should look like this, except I'm using built-in functions to get a
single line from a file I happened to have around, and naming it beef
instead of soup:

Python 2.7.3 (default, Sep 26 2013, 16:38:10) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('let.scm') as whatever:
...beef = next(whatever)
... 
>>> beef
'(define-syntax lets ;let-values, attempt to mod\n'
>>> 

Note the line with only "..." on it? That's where I pressed enter to
let the interpreter know that I had written all the code I wanted it
to handle at that point. I was rewarded with (1) no error message, (2)
a new prompt, where I entered, er, the four letters b e e f and then
pressed enter, and the interpreter printed the first line of my file
for me.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: encoding name mappings in codecs.py with email/charset.py

2014-12-14 Thread Stefanos Karasavvidis
thanks for replying gst.

I've thought already of patching the Charset class, but hoped for a cleaner
solution.

This ALIASES dict has already all the iso names *with* a dash. So it must
get striped somewhere else.

sk

On Sun, Dec 14, 2014 at 7:21 PM, gst  wrote:

> Le vendredi 12 décembre 2014 04:21:14 UTC-5, Stefanos Karasavvidis a
> écrit :
> > I've hit a wall with mailman which seems to be caused by pyhon's
> character encoding names.
> >
> > I've narrowed the problem down to the email/charset.py file. Basically
> the following happens:
> >
>
> Hi,
>
> it's all in the email.charset.ALIASES dict.
>
> you could also simply patch the __str__ method of Charset :
>
> Python 2.7.6 (default, Mar 22 2014, 22:59:56)
> [GCC 4.8.2] on linux2
> Type "copyright", "credits" or "license()" for more information.
> >>>
> >>> import email.charset
> >>>
> >>> c = email.charset.Charset('iso-8859-7')
> >>> str(c)
> 'iso8859-7'
> >>>
> >>> old = email.charset.Charset.__str__
> >>>
> >>> def patched(self):
> r = old(self)
> if r.startswith('iso'):
> return 'iso-' + r[3:]
> return r
>
> >>>
> >>> email.charset.Charset.__str__ = patched
> >>>
> >>> str(c)
> 'iso-8859-7'
> >>>
>
>
> regards,
>
> gst.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
==
Stefanos Karasavvidis,  Electronic & Computer Engineer, M.Sc.
e-mail: s...@isc.tuc.gr, Tel.: (+30) 2821037508, Fax: (+30)
2821037520
Technical University of Crete, Campus, Building A1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Text Code(from 'Getting Started in Beautiful Soup' re: cd Soup , returns 'Syntax Error, invalid syntax'

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 1:48 AM, Simon Evans  wrote:
> Thanks Guys
> This book keeps swapping from the Python console to the Windows - without 
> telling you, but it is the only book out there on 'Beautiful Soup' so I have 
> got to put up with it. There's more problems with it, but I will start a new 
> thread in regard of, I don't know if its related to the above or not.
> Yours

You may be able to recognize the consoles by their prompts. Python's
console is probably marked with ">>>" or "ipy>" or something, and the
Windows prompt most likely would have a path followed by ">"  (eg
"C:\>"). If the book's followed this convention, then you should be
able to figure things out easily enough once you get used to it.
Otherwise, look at the syntactic style: Windows command line, like
most command shells, uses a basic structure of command and arguments
separated by spaces, while Python uses a lot more symbols and
structural layout characters. But now we're getting into heuristics,
and there are some commands that work equally in Python and in Windows
(and do different things).

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


Re: encoding name mappings in codecs.py with email/charset.py

2014-12-14 Thread gst
Le dimanche 14 décembre 2014 14:10:22 UTC-5, Stefanos Karasavvidis a écrit :
> thanks for replying gst.
> 
> I've thought already of patching the Charset class, but hoped for a cleaner 
> solution. 
> 
> 
> This ALIASES dict has already all the iso names *with* a dash. So it must get 
> striped somewhere else.


not on my side, modifying this dict with the missing key-value apparently does 
what you want also :

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> import email.charset
>>> email.charset.ALIASES
{'latin-8': 'iso-8859-14', 'latin-9': 'iso-8859-15', 'latin-2': 'iso-8859-2', 
'latin-3': 'iso-8859-3', 'latin-1': 'iso-8859-1', 'latin-6': 'iso-8859-10', 
'latin-7': 'iso-8859-13', 'latin-4': 'iso-8859-4', 'latin-5': 'iso-8859-9', 
'euc_jp': 'euc-jp', 'latin-10': 'iso-8859-16', 'ascii': 'us-ascii', 'latin_10': 
'iso-8859-16', 'latin_1': 'iso-8859-1', 'latin_2': 'iso-8859-2', 'latin_3': 
'iso-8859-3', 'latin_4': 'iso-8859-4', 'latin_5': 'iso-8859-9', 'latin_6': 
'iso-8859-10', 'latin_7': 'iso-8859-13', 'latin_8': 'iso-8859-14', 'latin_9': 
'iso-8859-15', 'cp949': 'ks_c_5601-1987', 'euc_kr': 'euc-kr'}
>>> 
>>> for i in range(1, 16):
c = 'iso-8859-' + str(i)
email.charset.ALIASES[c] = c


>>> 
>>> iso7 = email.charset.Charset('iso-8859-7')
>>> iso7
iso-8859-7
>>> str(iso7)
'iso-8859-7'
>>> 

regards,

gst.

> 
> sk
> 
> 
> 
> On Sun, Dec 14, 2014 at 7:21 PM, gst  wrote:
> Le vendredi 12 décembre 2014 04:21:14 UTC-5, Stefanos Karasavvidis a écrit :
> 
> > I've hit a wall with mailman which seems to be caused by pyhon's character 
> > encoding names.
> 
> >
> 
> > I've narrowed the problem down to the email/charset.py file. Basically the 
> > following happens:
> 
> >
> 
> 
> 
> Hi,
> 
> 
> 
> it's all in the email.charset.ALIASES dict.
> 
> 
> 
> you could also simply patch the __str__ method of Charset :
> 
> 
> 
> Python 2.7.6 (default, Mar 22 2014, 22:59:56)
> 
> [GCC 4.8.2] on linux2
> 
> Type "copyright", "credits" or "license()" for more information.
> 
> >>>
> 
> >>> import email.charset
> 
> >>>
> 
> >>> c = email.charset.Charset('iso-8859-7')
> 
> >>> str(c)
> 
> 'iso8859-7'
> 
> >>>
> 
> >>> old = email.charset.Charset.__str__
> 
> >>>
> 
> >>> def patched(self):
> 
>         r = old(self)
> 
>         if r.startswith('iso'):
> 
>                 return 'iso-' + r[3:]
> 
>         return r
> 
> 
> 
> >>>
> 
> >>> email.charset.Charset.__str__ = patched
> 
> >>>
> 
> >>> str(c)
> 
> 'iso-8859-7'
> 
> >>>
> 
> 
> 
> 
> 
> regards,
> 
> 
> 
> gst.
> 
> --
> 
> https://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> 
> -- 
> 
> 
> ==
> Stefanos Karasavvidis,  Electronic & Computer Engineer, M.Sc.
> e-mail: s...@isc.tuc.gr, Tel.: (+30) 2821037508, Fax: (+30) 2821037520
> Technical University of Crete, Campus, Building A1
-- 
https://mail.python.org/mailman/listinfo/python-list


PySchool.net, kickstarter campaign

2014-12-14 Thread Billy Earney
Greetings!

For the past few months, I've been developing a website for educators and
students to learn computer programming (ie, Python).  My first project has
been to create a basic programming environment entirely within a browser.
Students can create, edit, load, save, and execute Python scripts directly
in the browser.This coding environment (or IDE) is somewhat similar to
cloud9, but has education in mind, and thus provides a much simpler
environment for those focused on learning.

To keep things short,  here is the URL pyschool.net if you would be
interested in looking at the website.  This is a working application.  Feel
free to use it. There is also a gallery where you can view and execute
examples (many of these come off of the brython.info website,  which helps
power the pyschool.net app).   This is not written in stone.  If educators
make it clear that some other environment is needed, I'm willing to adjust.

I've decided to try to kick this into high gear (it took several months of
my free time (nights/weekends) to get the site where it is). I'd like to
work on this full time, and greatly enhance the site, add tutorials,
(compile existing web resources) and also look at adding some K-4 level
computing resources like blockly (https://code.google.com/p/blockly/)  and
tools to help educators and students.   To do this, I've created a
kickstarter campaign.

The main directives of PySchool.net is to be free for educators and
students forever, to reduce the technological burdens of hosting
programming classes,  and help compile resources to help produce lesson
plans, etc.

Here's the campaign link:

https://www.kickstarter.com/projects/2030013583/pyschoolnet-advancing-python-in-the-classroom

Feel free to check it out.. :)

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Billy Earney
It looks like the last line (producer_entries...) is not indented at the
same extent as the previous line.  Maybe this is causing the issue?

On Sun, Dec 14, 2014 at 10:15 AM, Simon Evans 
wrote:
>
> Dear Python programmers,
> Having input the line of code in text:
> cd Soup
> to the Windows console, and having put the file 'EcologicalPyramid.html'
> into the Directory 'Soup', on the C drive, in accordance with instructions
> I input the following code to the Python console, as given on page 30 of
> 'Getting Started with Beautiful Soup':
>
> 
> Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
> on win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from bs4 import BeautifulSoup
> >>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
> ...  soup = BeautifulSoup(ecological_pyramid,"lxml")
> ... producer_entries = soup.find("ul")
>
>^
> SyntaxError: invalid syntax
> >>> producer_entries = soup.find("ul")
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'soup' is not defined
> >>>
>^
>
> 
> so I cannot proceed with the next line withh would 've been :
>
> 
> print(producer_entries.li.div.string)
>
> 
> which would've given (according to the book) the output:
> ---
> plants
>
> Maybe that is getting a bit far ahead, but I can't quite see where I have
> gone wrong - 'soup' has been defined as an object made of file
> 'EcologicalPyramid.html
>
> I hope you can help me on this point.
> Yours
> Simon
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


problem with six.moves intern importError

2014-12-14 Thread jean-michel richer

Hi,
  I am new to python and I am trying to use pycuda but get some
error on the following script. My environement is :

Python 2.7.6
libboost 1.54
gcc/g++ 4.8.2
CUDA 6.5


import pycuda.autoinit
import pycuda.driver as drv
import numpy

from pycuda.compiler import SourceModule
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
  const int i = threadIdx.x;
  dest[i] = a[i] * b[i];
}
""")

multiply_them = mod.get_function("multiply_them")

a = numpy.random.randn(400).astype(numpy.float32)
b = numpy.random.randn(400).astype(numpy.float32)

dest = numpy.zeros_like(a)
multiply_them(
drv.Out(dest), drv.In(a), drv.In(b),
block=(400,1,1), grid=(1,1))

print dest-a*b


when I run the script I get the followin import error:

$ python ex_pycuda.py
Traceback (most recent call last):
  File "ex_pycuda.py", line 5, in 
from pycuda.compiler import SourceModule
  File 
"/usr/local/lib/python2.7/dist-packages/pycuda-2014.1-py2.7-linux-x86_64.egg/pycuda/compiler.py", 
line 1, in 

from pytools import memoize
  File 
"/usr/local/lib/python2.7/dist-packages/pytools-2014.3.5-py2.7.egg/pytools/__init__.py", 
line 5, in 

from six.moves import range, zip, intern, input
ImportError: cannot import name intern

Is there a workaround or is it a bug ?

Best regards,
Jean-Michel

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


RE: Classes - converting external function to class's method.

2014-12-14 Thread Ivan Evstegneev
Dear Steven,

I very appreciate your answer. 
You just explained a lot of background things and you did it in more
explicit and simple way  than it've appeared in the book.
I also agree with you about the fact that there are some advanced topics
spread within a book's text.
It is sometimes hard to a newbie to separate  essential and from non
essential(I mean more advanced) topics.

So I may find myself digging down too much ^_^

In order to assemble the picture I would like to refer to couple of things
you mentioned:

>In this case, it works as you expect. Python looks up "method" on the
instance, and doesn't find anything attached to the instance. It then looks
at the class "rec",
 >which does have something called "method". Because this is a function,
Python knows to provide the instance x as the first argument. So the call

> x.method()

>ends up turning into this:

>rec.method(x)

I saw something similar to this example, but initially didn't understand
what the author meant, so I skipped it 

Here is a quote from a book(Please see Pic1.jpg too):
***
Method Calls

If this I2.w reference is a function call, what it really means is "call the
C3.w function to
process I2." That is, Python will automatically map the call I2.w() into the
call
C3.w(I2), passing in the instance as the first argument to the inherited
function.

***
 This was much confusing, till the moment I've read your explanation on live
example. )))


> Looking at this, I can guess you are using Python 3, because that won't
work in
> Python 2. Am I right?

Yes. I downloaded, Python 3.4 from python.org.  Currently working with IDLE.



> The important part to see here is that when you call a method from an
> instance:
> 
> instance.method()
> 
> Python *automatically* fills in the "self" argument using the instance.
(In your
> case, you called that argument "obj" instead of self, but Python doesn't
care
> what it is called.)
> 
> How does Python know to use x as self? Because it's written right there:
> x.method uses x as the first argument for method. But this is only done
for
> *instances*, not classes.

So, just to summarize all this stuff: 

A class doesn't have method __self__  by itself.

I checked this on some other class provided in the book:

>>> class FirstClass:   # Define a class object
def setdata(self, value):# Define class's methods
self.data = value # self is the instance
def display(self):
print(self.data)

And then check it with:

>>>dir(FirstClass)

[Yep no __self__ here]

On the other side, when an instance created, it does have __self__ method.



> > How does a function "uppername()" looks like, when I apply it to "rec"
> > class, so it becomes  a class's method?
> 
> I don't understand this question.

Well this is an embarrassing moment, it's just shows how lame my English can
be )

What I tried to ask here is if there any changes applied by Python to code
of function "uppername()" when it becomes class method (after using this
command: rec.method = uppername)

Never mind, you already answered it here:

> This is almost equivalent to the following:
> 
> class rec:
> name = 'Bob'
> age = 40
> def method(obj):
> return obj.name.upper()

Moreover, regard to the "rec.method = uppername"
As I can understand, in this case Python does make some changes to the
function, but they are implicit. 
Am I right? 


Sincerely,

Ivan




























> -Original Message-
> From: Python-list [mailto:python-list-
> bounces+webmailgroups=gmail@python.org] On Behalf Of Steven
> D'Aprano
> Sent: Sunday, December 14, 2014 19:28
> To: python-list@python.org
> Subject: Re: Classes - converting external function to class's method.
> 
> Ivan Evstegneev wrote:
> 
> > Hello Everyone,
> >
> > I have stuck a bit with this example(took this one from the book).
> 
> The example you are working on (adding external functions as methods) is
> actually a bit more complicated than it seems, as you have discovered. You
have
> this:
> 
> class rec: pass
> rec.name = 'Bob'
> rec.age = 40
> 
> x= rec()
> 
> def uppername(obj):
> return obj.name.upper()
> 
> rec.method = uppername
> 
> 
> This is almost equivalent to the following:
> 
> class rec:
> name = 'Bob'
> age = 40
> def method(obj):
> return obj.name.upper()
> 
> 
> You then try to use this new method, by calling it from the instance:
> 
> x.method()
> --> returns 'BOB' as you expected
> 
> 
> In this case, it works as you expect. Python looks up "method" on the
instance,
> and doesn't find anything attached to the instance. It then looks at the
class
> "rec", which does have something called "method". Because this is a
function,
> Python knows to provide the instance x as the first argument. So the call
> 
> x.method()
> 
> ends up turning into this:
> 
> 

Re: numpy question (fairly basic, I think)

2014-12-14 Thread Gregory Ewing

Albert-Jan Roskam wrote:

I was trying to change the one-dim array into a two-dim array so
I could easily retrieve columns. I now use a pandas DataFrame to do that.


Numpy can do that, if I understand what you want correctly,
but it requires an unintuitive trick.

The trick is to index the array with the name of a field,
and *only* the name of the field. For example, the following
gives you a slice containing all the values from the 'v02'
fields of your data:

  array['v02']

Note: Indexing with a field name generally seems to follow
a different set of rules. Some things that you'd think would
work don't, e.g.

   array[:, 'v02']

fails with a rather confusing error message. Also,

   array[0, 'v02']

doesn't work either, and has to be written

   array[0]['v02']

instead.

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


Re: Classes - converting external function to class's method.

2014-12-14 Thread Thomas 'PointedEars' Lahn
Ivan Evstegneev wrote:

> I have stuck a bit with this example(took this one from the book).
> 
> Here are a description steps of what I've done till now:
>  
> 
> Step 1 - creating an empty namespace:
> 
class rec: pass

IMHO that is not actually creating a namespace; it is just 
declaring/defining an empty class.

The equivalent of a namespace in Python is a module; the file path starting 
from an entry in the PYTHONPATH works like a namespace (the module is 
considered to be in a package if the directory contains an __init__.py 
file).  (One can assume that this was derived from Java.)

BTW, the recommended Python 3.x way is

class Rec (object):
pass

(whereas “pass” is a placeholder statement, a bit like the yada-yada 
operator of Python) and you should start class identifiers uppercase 
(therefore, “Rec” instead) in order to avoid name collisions with built-in 
class identifiers (“str”, “int” etc.) and make it easier to tell apart 
instantiations from function/method calls.  This recommendation applies to 
other similar OOPLs too, but ISTM is especially important in Python code 
where there is no “new” keyword used in instantiation.

> Step 4 - write down external function: 
> 
> >>>def uppername(obj):
> return obj.name.upper()
> 
> […]
> Step 6 - Creating a class method:
> 
>>>rec.method = uppername
> […]
x.method()
> 'BOB'
> 
rec.method()
> .
> .
> TypeError: uppername() missing 1 required positional argument: 'obj'
> 
> and then:
> 
rec.method(rec)
> 'BOB'
> 
> So my the question is: what is going on here? How this actually works?

Short answer: Calling rec.method(x) is equivalent to calling x.method() if 
type(x) == rec.

| >>> class C (object): pass
| >>> def foo (self):
| ... print(self)
| >>> C.foo = foo
| >>> C.foo()
| Traceback (most recent call last):
| File "", line 1, in 
| TypeError: foo() missing 1 required positional argument: 'self'
| >>> o = C()
| >>> C.foo(o)
| <__main__.C object at 0x7f64a7458be0>
| >>> o.foo()
| <__main__.C object at 0x7f64a7458be0>

Long answer:

If you call that method as the method of a class (object), you need to pass 
an argument for the first parameter because you have made it positional, not 
optional (it has no default value).  If you pass (a reference to) the class 
as first argument of that method, the class is the object whose attribute is 
accessed.  Classes are objects (this, too, was probably derived from Java).  
(In fact, AFAIK almost everything is an object in Python; there are no 
primitive data types at all.)

If instead you call that method as the method of an instance, the first 
argument is a reference to that instance implicitly, so the signature of the 
method is met implicitly and there is no error.  (See below for an 
explanation as to why “self.name” still works.)  Any arguments that you pass 
then in the argument list are passed as second, third aso. argument to the 
method.  To this method, then, you MUST NOT pass other arguments because it 
does not take any more than already supplied implicitly.

[Fixed comb-quote; please keep to at most 80 characters per line, best 72]

> According to the book's downside note:
> 
> 
> In fact, this is one of the reasons the self argument must always be
> explicit in Python methods-because methods can be created as simple 
> functions independent of a class, they need to make the implied instance
> argument explicit. They can be called as either functions or methods,
> and Python can neither guess nor assume that a simple function might 
> eventually become a class's method.
> The main reason for the explicit self argument, though, is to make the 
> meanings of names more obvious: names not referenced through 
> self are simple variables mapped to scopes, while names referenced
> through self with attribute notation are obviously instance attributes.
> ***

Exactly.

> Keeping it in mind, I wrote this code:
> 
 class myclass:
>   def __init__(self, value):
>   self.name = value
>   def myupper(self):
>   return self.name.upper()
> 
> And then:
> 
 b = myclass('bob')
b.myupper()
> 'BOB'
> 
> I made an assumption that this is what happens(roughly speaking) when I
> write this:
> 
rec.method = uppername
> 
> Am I right? (close enough maybe?)

Close, maybe.  The difference is that in the original code the class has the 
attribute and the instance merely inherits it, while in the code above only 
the instance has the attribute.

IOW, in the code above the attribute (value) is not implicitly shared with 
other instances of that class.  And ISTM that with the original code it is 
not possible to modify the attribute value except by accessing it directly 
or through a method that is passed the reference to the *class* (because a 
simple assignment in a method merely defines a local var

Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Simon Evans
Dear Jussi, and Billy
I have changed the input in accordance with your advice, re:
--
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
... print(producer_entries.li.div.string)
  File "", line 5
print(producer_entries.li.div.string)
^
SyntaxError: invalid syntax
>>> print (producer_entries.li.div.string)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'producer_entries' is not defined
>>> from bs4 import BeautifulSoup
>>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
...

As no doubt you can see, the last line, indented as it is, does not provide the 
output that the book's text says it will return - ie the word 'plants'
If I do not indent it, it returns an 'invalid syntax error' stating that 
'producer_entries' is not defined. Though code in the previous line is meant to 
do just that - isn't it ? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PySchool.net, kickstarter campaign

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 2:07 AM, Billy Earney  wrote:
> Students can create, edit, load, save, and execute Python scripts directly
> in the browser.

Importantly, these scripts are actually executed in the client - they
are NOT being sent to the server for execution. That means there are
limitations on the language, to be sure, but none of the security
risks of letting untrusted users run Python code on the server.

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


Re: PySchool.net, kickstarter campaign

2014-12-14 Thread Billy Earney
ChrisA,

Yes, you are correct.  The scripts get compiled to javascript and then
executed in the browser.   Like you say, there are limitations, but most of
these focus around browser security issues,  and on the plus side, these
scripts do not get executed on the server side, so that helps reduce risk
there as well.

billy

On Sun, Dec 14, 2014 at 5:26 PM, Chris Angelico  wrote:
>
> On Mon, Dec 15, 2014 at 2:07 AM, Billy Earney 
> wrote:
> > Students can create, edit, load, save, and execute Python scripts
> directly
> > in the browser.
>
> Importantly, these scripts are actually executed in the client - they
> are NOT being sent to the server for execution. That means there are
> limitations on the language, to be sure, but none of the security
> risks of letting untrusted users run Python code on the server.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PySchool.net, kickstarter campaign

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 10:41 AM, Billy Earney  wrote:
> Yes, you are correct.  The scripts get compiled to javascript and then
> executed in the browser.   Like you say, there are limitations, but most of
> these focus around browser security issues,  and on the plus side, these
> scripts do not get executed on the server side, so that helps reduce risk
> there as well.

Right. Every form of "let the users type Python code in a web site and
see what it does" will have limitations; most of them also have
security risks, but Brython specifically doesn't.

I tossed a few dollars into your KS campaign, BTW, but you're going to
need a *lot* more people than me :)

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


Re: Classes - converting external function to class's method.

2014-12-14 Thread Terry Reedy

On 12/14/2014 6:15 PM, Thomas 'PointedEars' Lahn wrote:

Ivan Evstegneev wrote:


I have stuck a bit with this example(took this one from the book).

Here are a description steps of what I've done till now:


Step 1 - creating an empty namespace:


class rec: pass


IMHO that is not actually creating a namespace; it is just
declaring/defining an empty class.


I pythonland, a namespace is a many to one mapping between names and 
objects.  They are usually but not necessarily implemented with dicts. 
Some might restrict the term to a mapping with a .attribute interface 
for getting and setting.  Others consider any string-key dict to be a 
namespace. The types module has a class SimpleNamespace.  It has been 
proposed to move it to builtins with the name 'namespace'.



BTW, the recommended Python 3.x way is

class Rec (object):
 pass


I hope you meant Python *2*.x, where '(object)' *is* needed to make a 
newstyle class.  In 3.x, '(object)' is optional and normally omitted 
except in code meant to run unchanged in 2 and 3.


--
Terry Jan Reedy

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


Re: Classes - converting external function to class's method.

2014-12-14 Thread Thomas 'PointedEars' Lahn
Terry Reedy wrote:

> On 12/14/2014 6:15 PM, Thomas 'PointedEars' Lahn wrote:
>> Ivan Evstegneev wrote:
>>> I have stuck a bit with this example(took this one from the book).
>>>
>>> Here are a description steps of what I've done till now:
>>>
>>> Step 1 - creating an empty namespace:
>>>
>> class rec: pass
>>
>> IMHO that is not actually creating a namespace; it is just
>> declaring/defining an empty class.
> 
> I pythonland, a namespace is a many to one mapping between names and
> objects.  They are usually but not necessarily implemented with dicts.
> […]
> 
>> BTW, the recommended Python 3.x way is
>>
>> class Rec (object):
>>  pass
> 
> I hope you meant Python *2*.x,

I did not.

> where '(object)' *is* needed to make a newstyle class.  In 3.x, '(object)' 
> is optional and normally omitted except in code meant to run unchanged in 
> 2 and 3.

Your statements are corroborated by the Language Reference:





Thanks.

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Steven D'Aprano
Simon Evans wrote:

> Dear Jussi, and Billy
> I have changed the input in accordance with your advice, re:
> --
> Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
> on win 32
> Type "help", "copyright", "credits" or "license" for more information.
 from bs4 import BeautifulSoup
 with open("ecologicalpyramid.html","r") as ecological_pyramid:
> ...  soup = next(ecological_pyramid,"lxml")
> ...  producer_entries = soup.find("ul")
> ...  print(producer_entries.li.div.string)
> ... print(producer_entries.li.div.string)


Simon, you are not leaving a blank space between the indented block and the
unindented line.

The interactive interpreter is quite simple, and you MUST leave a blank line
after indented blocks. You need to press the ENTER key *twice* at the end
of the block:

with open("ecologicalpyramid.html","r") as ecological_pyramid: ENTER
TAB soup = next(ecological_pyramid,"lxml") ENTER
TAB producer_entries = soup.find("ul") ENTER
TAB print(producer_entries.li.div.string) ENTER
ENTER
print(producer_entries.li.div.string) ENTER


Don't type the letters E N T E R, press the ENTER key. The same goes for
TAB. Note carefully that after the indented block, there is a blank line.
It should look like this:


>>> with open("ecologicalpyramid.html","r") as ecological_pyramid:
...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
... 
>>> print(producer_entries.li.div.string)

If you don't leave the blank line, then *nothing* in that "with" block will
run and consequently the last print line will fail.

Until you fix that, we cannot even begin to help with any other issues you
might be having.



-- 
Steven

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


Re: PySchool.net, kickstarter campaign

2014-12-14 Thread Billy Earney
Thanks..  I appreciate your contribution!

On Sun, Dec 14, 2014 at 5:48 PM, Chris Angelico  wrote:
>
> On Mon, Dec 15, 2014 at 10:41 AM, Billy Earney 
> wrote:
> > Yes, you are correct.  The scripts get compiled to javascript and then
> > executed in the browser.   Like you say, there are limitations, but most
> of
> > these focus around browser security issues,  and on the plus side, these
> > scripts do not get executed on the server side, so that helps reduce risk
> > there as well.
>
> Right. Every form of "let the users type Python code in a web site and
> see what it does" will have limitations; most of them also have
> security risks, but Brython specifically doesn't.
>
> I tossed a few dollars into your KS campaign, BTW, but you're going to
> need a *lot* more people than me :)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classes - converting external function to class's method.

2014-12-14 Thread Steven D'Aprano
Thomas 'PointedEars' Lahn wrote:

> Ivan Evstegneev wrote:
> 
>> I have stuck a bit with this example(took this one from the book).
>> 
>> Here are a description steps of what I've done till now:
>>  
>> 
>> Step 1 - creating an empty namespace:
>> 
>class rec: pass
> 
> IMHO that is not actually creating a namespace; it is just
> declaring/defining an empty class.

And classes are namespaces. As are instances.

One clue is the fact that we use exactly the same syntax for accessing names
in a namespace regardless of whether the namespace is a package, a module,
a class or an instance:

import collections.abc  # a package namespace
math.sin  # a module namespace
OrderedDict.fromkeys  # a class namespace
mystring.upper  # an instance namespace

I call it a "clue" rather than definitive proof because the syntax is not
quite the same for all namespaces. Local and global variables also exist in
namespaces, but you don't use dotted notation for them.

Another clue is that most of these are implemented by using a __dict__ to
store the name:value mapping. Again, that's not universal: instances can
optionally use __slots__ instead of __dict__ and packages use the file
system.

Apart from packages, one can use getattr(), setattr() and delattr() on all
of these objects (modules, classes and instances) to manipulate their
attributes.

Wikipedia says:

"In general, a namespace is a container for a set of identifiers (also known
as symbols, names)."

https://en.wikipedia.org/wiki/Namespace

and that applies to packages, modules, classes, and instances.

Last but not least, another clue: in some languages, such as Java, what
Python calls "attributes" are known as *variables*. So per-instance members
are called "instance variables", per-class members are sometimes
called "class variables" (although not in Java, where I believe they are
known as static variables for technical reasons). Personally, I don't like
that terminology, but I do recognise that it does reflect a certain
connection between names in local/global/instance/class namespaces.


> BTW, the recommended Python 3.x way is
> 
> class Rec (object):
> pass


I think you mean Python 2 rather than 3. In Python 2, we have legacy "old
style" or "classic" classes, and "new style" classes which inherit from
object. In Python 3, classic classes are gone, and inheriting from object
is optional.


> (whereas “pass” is a placeholder statement, a bit like the yada-yada
> operator of Python) and you should start class identifiers uppercase
> (therefore, “Rec” instead) in order to avoid name collisions with built-in
> class identifiers (“str”, “int” etc.) and make it easier to tell apart
> instantiations from function/method calls.

Agreed!

It is good practice to name classes with initial capital letter, and
instances in all lowercase.


> If you call that method as the method of a class (object), you need to
> pass an argument for the first parameter because you have made it
> positional, not
> optional (it has no default value).  If you pass (a reference to) the
> class as first argument of that method, the class is the object whose
> attribute is
> accessed.  Classes are objects (this, too, was probably derived from
> Java). (In fact, AFAIK almost everything is an object in Python; there are
> no primitive data types at all.)

You are correct that "everything is an object" in Python, but wrong that
this is derived from Java. As I understand it, Java classes are not values:
you cannot assign a class to a variable, or create classes on the fly, or
delete them, or stick them in lists, etc. 

Well, I say that you can't do it, but you actually can, using reflection and
other tricks. But the important thing is that you need to use special
techniques to work around the fact that classes aren't values and therefore
not implemented as objects in Java. What is natural in Python is unnatural
in Java.

http://stackoverflow.com/questions/2320404/creating-classes-dynamically-with-java


[...]
> If you intend the function to be called as the method of an instance, you
> would be well-advised to name the parameter “self”, as recommended. 
> (Which is probably derived from Smalltalk-80 and Self, some of the first
> OOPLs.)

Good advice.


-- 
Steven

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Chris Roy-Smith

On 15/12/14 10:21, Simon Evans wrote:

Dear Jussi, and Billy
I have changed the input in accordance with your advice, re:
--
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win


here the user is using python 2.7.6



32
Type "help", "copyright", "credits" or "license" for more information.

from bs4 import BeautifulSoup
with open("ecologicalpyramid.html","r") as ecological_pyramid:

...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
... print(producer_entries.li.div.string)
   File "", line 5
 print(producer_entries.li.div.string)
 ^


and here he uses a python 3.x print syntax which triggers the following 
error message



SyntaxError: invalid syntax

print (producer_entries.li.div.string)

Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'producer_entries' is not defined

from bs4 import BeautifulSoup
with open("ecologicalpyramid.html","r") as ecological_pyramid:

...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
...

As no doubt you can see, the last line, indented as it is, does not provide the 
output that the book's text says it will return - ie the word 'plants'
If I do not indent it, it returns an 'invalid syntax error' stating that 
'producer_entries' is not defined. Though code in the previous line is meant to 
do just that - isn't it ?



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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 1:32 PM, Chris Roy-Smith
 wrote:
> and here he uses a python 3.x print syntax which triggers the following
> error message

On the contrary; parens around a single argument will work just fine
in Py2 (they're simply redundant parentheses, in the same way that you
can write "i = (1)" and it's the same as "i = 1"). The syntax error
comes from unindenting without ending the block, as several have
pointed out already.

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Mark Lawrence

On 15/12/2014 02:32, Chris Roy-Smith wrote:

On 15/12/14 10:21, Simon Evans wrote:

Dear Jussi, and Billy
I have changed the input in accordance with your advice, re:
--

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit
(Intel)] on win


here the user is using python 2.7.6



32
Type "help", "copyright", "credits" or "license" for more information.

from bs4 import BeautifulSoup
with open("ecologicalpyramid.html","r") as ecological_pyramid:

...  soup = next(ecological_pyramid,"lxml")
...  producer_entries = soup.find("ul")
...  print(producer_entries.li.div.string)
... print(producer_entries.li.div.string)
   File "", line 5
 print(producer_entries.li.div.string)
 ^


and here he uses a python 3.x print syntax which triggers the following
error message


SyntaxError: invalid syntax

print (producer_entries.li.div.string)

Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'producer_entries' is not defined




I didn't realise that Python was so smart.  It can indicate a syntax 
error at the final 't' in print before it gets to the opening bracket 
that is required for the print function in Python 3 (and Python 2 if 
you're using "from __future__ import print_function")?


--
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: How to import sqlite3 in my python3.4 successfully?

2014-12-14 Thread Thomas 'PointedEars' Lahn
sir wrote:
^^^
Please fix.

> There are two python version in my debian7, one is python2.7 the system
> default version, the other is python3.4 which compiled to install this
> way.
> 
> |  apt-get  update
>   apt-get  upgrade
>   apt-get  install build-essential
>   wget http://www.python.org/ftp/python/3.4.0/Python-3.4.0.tgz
>   tar-zxvfPython-3.4.0.tgz
>   cdPython-3.4.0
>   mkdir/usr/local/python3.4
>   ./configure--prefix=/usr/local/python3.4
>   make
>   make install
>   ln-s/usr/local/python3.4/bin/python3.4/usr/bin/python3.4
>   ln-s/usr/local/python3.4/bin/pip3.4/usr/bin/pip3.4|

Why do you not use the Debian packages instead?

> I have installed sqlite this way on my debian.
> 
> |sudo apt-get  install sqlite3 libsqlite3-dev|

That package has nothing to do with Python:

$ dpkg -L libsqlite3-dev
/.
/usr
/usr/include
/usr/include/sqlite3.h
/usr/include/sqlite3ext.h
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/libsqlite3.a
/usr/lib/x86_64-linux-gnu/libsqlite3.la
/usr/lib/x86_64-linux-gnu/pkgconfig
/usr/lib/x86_64-linux-gnu/pkgconfig/sqlite3.pc
/usr/share
/usr/share/doc
/usr/share/doc/libsqlite3-dev
/usr/share/doc/libsqlite3-dev/changelog.Debian.gz
/usr/share/doc/libsqlite3-dev/changelog.gz
/usr/share/doc/libsqlite3-dev/changelog.html.gz
/usr/share/doc/libsqlite3-dev/copyright
/usr/lib/x86_64-linux-gnu/libsqlite3.so

> In python3.4
> 
> |root@rebuild:~#  python3.4
> Python  3.4.0  (default,  Nov  27  2014,  13:54:17)
> [GCC4.7.2]  on linux
> Type  "help",  "copyright",  "credits"  or  "license"  for  more
> information.
  import  sqlite3
> Traceback  (most recent calllast):
>File  "",  line1,  in  
>File  "/usr/local/python3.4/lib/python3.4/sqlite3/__init__.py", 
>line23,  in  
>  from  sqlite3.dbapi2import  *
>File  "/usr/local/python3.4/lib/python3.4/sqlite3/dbapi2.py",  line26, 
>in  
>  from  _sqlite3import  *
> ImportError:  No  module  named'_sqlite3'|
> 
> How can i import sqlite3 in my python3.4 successfully?

Install the Debian packages.

,
| # apt-file search dbapi2.py | grep python3
| libpython3.4-stdlib: /usr/lib/python3.4/sqlite3/dbapi2.py
| python3.2: /usr/lib/python3.2/sqlite3/dbapi2.py
`

,
| $ python3.4
| Python 3.4.2 (default, Dec  2 2014, 15:08:18) 
| [GCC 4.9.2] on linux
| Type "help", "copyright", "credits" or "license" for more information.
| >>> import sqlite3
| >>> 
`

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Script to convert firewall rules

2014-12-14 Thread Jason Friedman
> Thank you very much. Appreciated ! But the first requirement was to convert
> format1 to format2 as below:
>
> set interface ethernet2/5 ip 10.17.10.1/24 (format 1)
> set interfaces ge-0/0/0 unit 0 family inet address 10.17.10.1/24 (format 2)
> (set, interface, ip) = (set, interfaces, family inet address)
> But some values are variable and should ask the user to convert manually
> like ethernet2/5 equal to ge-0/0/0 or ge-0/0/1 or ge-0/0/2
> And some values keep as it is like 10.17.10.1/24

Kashif, perhaps you should contact me off list, this subject is
becoming very particular and maybe not of interest to the general
audience.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Michael Torrie
On 12/14/2014 07:47 PM, Mark Lawrence wrote:
> I didn't realise that Python was so smart.  It can indicate a syntax 
> error at the final 't' in print before it gets to the opening bracket 
> that is required for the print function in Python 3 (and Python 2 if 
> you're using "from __future__ import print_function")?

Not really.  Python2 just interprets "print (value)" as an expression to
the print statement.  It's like saying "a=(value)" and then "print a".
Redundant but works.  However "print(value)" is interpreted as a
function call, and if you haven't imported it from future, it will error
out on Python2.

Python 3, on the other hand treats spaces between a function and its
opening paren to be optional whitespace.  Thus to python3,
"print(value)" and "print (value)" are the same.

So if you always put a space between print and (value) you can achieve
some measure of cross-version compatibility with print.  However by
including print_function from __future__ you are guaranteeing you won't
forget to add the parens.


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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 4:27 PM, Michael Torrie  wrote:
> On 12/14/2014 07:47 PM, Mark Lawrence wrote:
>> I didn't realise that Python was so smart.  It can indicate a syntax
>> error at the final 't' in print before it gets to the opening bracket
>> that is required for the print function in Python 3 (and Python 2 if
>> you're using "from __future__ import print_function")?
>
> Not really.  Python2 just interprets "print (value)" as an expression to
> the print statement.  It's like saying "a=(value)" and then "print a".
> Redundant but works.  However "print(value)" is interpreted as a
> function call, and if you haven't imported it from future, it will error
> out on Python2.

Did you actually test that?

Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print("hello")
hello

Since print is a keyword when not imported from future, there's no way
for print(value) to be parsed as a function call.

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Michael Torrie
On 12/14/2014 10:32 PM, Chris Angelico wrote:
> Did you actually test that?
> 
> Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
 print("hello")
> hello
> 
> Since print is a keyword when not imported from future, there's no way
> for print(value) to be parsed as a function call.

Thought I had indirectly, since I've been using this print technique for
the last few days.  Good to know it works either way, though.  Guess the
future import is only to make not having parens and error.

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Zachary Ware
On Sun, Dec 14, 2014 at 11:38 PM, Michael Torrie  wrote:
> Guess the future import is only to make not having parens and error.

Python 2.7.8+ (default, Nov  2 2014, 00:32:19) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1, 2)
(1, 2)
>>> from __future__ import print_function
>>> print(1, 2)
1 2

Also, without the future import you can't use the 'sep', 'end', and
'file' keyword arguments.

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


Re: Python console rejects an object reference, having made an object with that reference as its name in previous line

2014-12-14 Thread Chris Angelico
On Mon, Dec 15, 2014 at 4:38 PM, Michael Torrie  wrote:
> Thought I had indirectly, since I've been using this print technique for
> the last few days.  Good to know it works either way, though.  Guess the
> future import is only to make not having parens and error.

Yeah. I usually recommend using parens and a single native-string
argument, for maximum portability. That'll work even on pre-2.6 where
the future import isn't supported.

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


Portable code: __import__ demands different string types between 2 and 3

2014-12-14 Thread Ben Finney
Howdy all,

What should I do, in a world where all text literals are Unicode by
default, to make ‘__import__’ work in both Python 2 and 3?


I'm slowly learning about making Python code that will run under both
Python 2 (version 2.6 or above) and Python 3 (version 3.2 or above).

This entails, I believe, the admonition to ensure text literals are
Unicode by default::

from __future__ import unicode_literals

and to specify bytes literals explicitly with ‘b'wibble'’ if needed.


The ‘__import__’ built-in function, though, is tripping up.

A contrived, trivial project layout::

$ mkdir fooproject/
$ cd fooproject/

$ mkdir foo/
$ printf "" > foo/__init__.py
$ mkdir foo/bar/
$ printf "" > foo/bar/__init__.py

Here's a simple ‘fooproject/setup.py’::

from __future__ import unicode_literals

main_module_name = 'foo'
main_module = __import__(main_module_name, fromlist=['bar'])

assert main_module.bar

That fails under Python 2, but runs fine under Python 3::

$ python2 ./setup.py
Traceback (most recent call last):
  File "./setup.py", line 4, in 
main_module = __import__(main_module_name, fromlist=['bar'])
TypeError: Item in ``from list'' not a string

$ python3 ./setup.py

We've deliberately made unadorned strings Unicode by default. By “not a
string”, I presume Python 2 means “not a ‘bytes’ object”.


Okay, so we'll explicitly set that to a ‘bytes’ literal::

from __future__ import unicode_literals

main_module_name = 'foo'
main_module = __import__(main_module_name, fromlist=[b'bar'])

assert main_module.bar

Now Python 2 is satisfied, but Python 3 complains::

$ python2 ./setup.py

$ python3 ./setup.py
Traceback (most recent call last):
  File "./setup.py", line 4, in 
main_module = __import__(main_module_name, fromlist=[b'bar'])
  File "", line 2281, in
_handle_fromlist
TypeError: hasattr(): attribute name must be string


How can I get that ‘__import__’ call, complete with its ‘fromlist’
parameter, working correctly under both Python 2 and Python 3, keeping
the ‘unicode_literals’ setting?

If some kind of kludge is needed to make it work between versions, is
this a bug which should be fixed so “use Unicode for text” remains
applicable advice?

-- 
 \   “I do not believe in immortality of the individual, and I |
  `\consider ethics to be an exclusively human concern with no |
_o__)  superhuman authority behind it.” —Albert Einstein, letter, 1953 |
Ben Finney

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


Re: problem with six.moves intern importError

2014-12-14 Thread dieter
jean-michel richer  writes:

> Hi,
>   I am new to python and I am trying to use pycuda but get some
> error on the following script. My environement is :
>
> Python 2.7.6
> libboost 1.54
> gcc/g++ 4.8.2
> CUDA 6.5
> ...
> from six.moves import range, zip, intern, input
> ImportError: cannot import name intern
>
> Is there a workaround or is it a bug ?

You likely need a different version of "six.moves" (one that
defines "intern").

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


Re: Portable code: __import__ demands different string types between 2 and 3

2014-12-14 Thread Zachary Ware
On Mon, Dec 15, 2014 at 1:29 AM, Ben Finney  wrote:
> How can I get that ‘__import__’ call, complete with its ‘fromlist’
> parameter, working correctly under both Python 2 and Python 3, keeping
> the ‘unicode_literals’ setting?

How about "str('bar')"?

> If some kind of kludge is needed to make it work between versions, is
> this a bug which should be fixed so “use Unicode for text” remains
> applicable advice?

Fixed in which version?  The problem is that Python 2 mixes the
notions of strings and bytestrings, and the solution is Python 3.

I believe six also has a "give me a native string" function to help with this.

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