Re: Identifying tkinter version

2020-04-01 Thread Tony van der Hoff




On 01/04/2020 17:34, Rich Shepard wrote:

Here, on Slackware-14.2, Python3-3.8.2 is installed. I would like to learn
which version of tkinter is provided with it. There's no local VERSION file
and tkinter.version() returns nothing.

How do I determine the installed version?

>>> import tkinter
>>> tkinter.TkVersion
8.6

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: can't install http module

2019-11-08 Thread Tony van der Hoff




On 07/11/2019 19:39, Chris Angelico wrote:

On Fri, Nov 8, 2019 at 6:34 AM Tony van der Hoff  wrote:




On 07/11/2019 19:00, Chris Angelico wrote:

On Fri, Nov 8, 2019 at 5:47 AM tony van der Hoff  wrote:


Hi,
I'm attempting to install (among other things) the "http" module on my
debian10 box, and am encountering the following problem:



Can you link to the documentation for the package you're trying to
install? Python already ships with a module called "http". You don't
need to install it.


Thanks Chris, but it doesn't seem to be installed here, but maybe I'm
doing something stupid:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-



Ah. I wouldn't call this "something stupid", because this is a bit of
a gotcha, but there is a small problem here. In your original post,
you attempted to install using "python3 -m pip", but here your shebang
just says "python", so you're running it in Python 2.7. Replace the
shebang with "python3" (and then drop the coding cookie - Python 3
assumes UTF-8 by default) and you should be able to run your code. (At
least the import lines you posted. No idea about anything else.)

ChrisA



Excellent catch, Chris. Thank you so much. I changed the version while 
tracking down another problem, and forgot to restore it.

It should have been obvious, but somehow it escaped me.

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


Re: can't install http module

2019-11-07 Thread Tony van der Hoff




On 07/11/2019 19:00, Chris Angelico wrote:

On Fri, Nov 8, 2019 at 5:47 AM tony van der Hoff  wrote:


Hi,
I'm attempting to install (among other things) the "http" module on my
debian10 box, and am encountering the following problem:



Can you link to the documentation for the package you're trying to
install? Python already ships with a module called "http". You don't
need to install it.

Thanks Chris, but it doesn't seem to be installed here, but maybe I'm 
doing something stupid:


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import cgi
import logging
from http import cookies


[Thu Nov 07 17:29:24.002303 2019] [cgi:error] [pid 30937] [client 
127.0.0.1:41912] AH01215: Traceback (most recent call last):: 
/home/tony/public_html/private/pygallery/pygallery.py
[Thu Nov 07 17:29:24.002455 2019] [cgi:error] [pid 30937] [client 
127.0.0.1:41912] AH01215:   File 
"/home/tony/public_html/private/pygallery/pygallery.py", line 6, in 
: /home/tony/public_html/private/pygallery/pygallery.py
[Thu Nov 07 17:29:24.002480 2019] [cgi:error] [pid 30937] [client 
127.0.0.1:41912] AH01215: from http import cookies: 
/home/tony/public_html/private/pygallery/pygallery.py
[Thu Nov 07 17:29:24.002502 2019] [cgi:error] [pid 30937] [client 
127.0.0.1:41912] AH01215: ImportError: No module named http: 
/home/tony/public_html/private/pygallery/pygallery.py


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


can't install http module

2019-11-07 Thread tony van der Hoff

Hi,
I'm attempting to install (among other things) the "http" module on my 
debian10 box, and am encountering the following problem:


##
tony@tony-lx:~/_pycharm/pygallery$ python3 -m pip install http

Collecting http
   Using cached 
https://files.pythonhosted.org/packages/e3/91/a9260805e532e33df273b8f7dffad5c51693f8f9ba5f86bedcf42a7f22eb/http-0.02.tar.gz

     Complete output from command python setup.py egg_info:
     Traceback (most recent call last):
   File "", line 1, in 
   File "/tmp/pip-install-fr02g_f6/http/setup.py", line 3, in 
     import http
   File "/tmp/pip-install-fr02g_f6/http/http/__init__.py", line 17, 
in 

     from request import Request
     ModuleNotFoundError: No module named 'request'

     
Command "python setup.py egg_info" failed with error code 1 in 
/tmp/pip-install-fr02g_f6/http/


##
So, I tried installing "request":

##

tony@tony-lx:~/_pycharm/pygallery$ python3 -m pip install request
Collecting request
   Downloading 
https://files.pythonhosted.org/packages/f1/27/7cbde262d854aedf217061a97020d66a63163c5c04e0ec02ff98c5d8f44e/request-2019.4.13.tar.gz

Collecting get (from request)
   Downloading 
https://files.pythonhosted.org/packages/3f/ef/bb46f77f7220ac1b7edba0c76d810c89fddb24ddd8c08f337b9b4a618db7/get-2019.4.13.tar.gz

Collecting post (from request)
   Downloading 
https://files.pythonhosted.org/packages/0f/05/bd79da5849ea6a92485ed7029ef97b1b75e55c26bc0ed3a7ec769af666f3/post-2019.4.13.tar.gz
Requirement already satisfied: setuptools in 
/usr/lib/python3/dist-packages (from request) (40.8.0)

Collecting query_string (from get->request)
   Downloading 
https://files.pythonhosted.org/packages/12/3c/412a45daf5bea9b1d06d7de41787ec4168001dfa418db7ec8723356b119f/query-string-2019.4.13.tar.gz

Collecting public (from query_string->get->request)
   Downloading 
https://files.pythonhosted.org/packages/54/4d/b40004cc6c07665e48af22cfe1e631f219bf4282e15fa76a5b6364f6885c/public-2019.4.13.tar.gz
Building wheels for collected packages: request, get, post, 
query-string, public

   Running setup.py bdist_wheel for request ... done
   Stored in directory: 
/home/tony/.cache/pip/wheels/30/84/5f/484cfba678967ef58c16fce6890925d5c7172622f20111fbfd

   Running setup.py bdist_wheel for get ... done
   Stored in directory: 
/home/tony/.cache/pip/wheels/c1/e3/c1/d02c8c58538853e4c9b78cadb74f6d5c5c370b48a69a7271aa

   Running setup.py bdist_wheel for post ... done
   Stored in directory: 
/home/tony/.cache/pip/wheels/c3/c3/24/b5c132b537ab380c02d69e6bd4dec1f5db56b5fe19030473d7

   Running setup.py bdist_wheel for query-string ... done
   Stored in directory: 
/home/tony/.cache/pip/wheels/d6/a4/78/01b20a9dc224dcc009fab669f7f27b943b8889c5150bd68d8a

   Running setup.py bdist_wheel for public ... done
   Stored in directory: 
/home/tony/.cache/pip/wheels/23/7c/6e/f5b4e09d6596c8b8802b347e48f149031e2363368048f1347a

Successfully built request get post query-string public
Installing collected packages: public, query-string, get, post, request
Successfully installed get-2019.4.13 post-2019.4.13 public-2019.4.13 
query-string-2019.4.13 request-2019.4.13

##
So far, so good; retry http:

##

tony@tony-lx:~/_pycharm/pygallery$ python3 -m pip install http
Collecting http
   Using cached 
https://files.pythonhosted.org/packages/e3/91/a9260805e532e33df273b8f7dffad5c51693f8f9ba5f86bedcf42a7f22eb/http-0.02.tar.gz

     Complete output from command python setup.py egg_info:
     Traceback (most recent call last):
   File "", line 1, in 
   File "/tmp/pip-install-zwguez5m/http/setup.py", line 3, in 
     import http
   File "/tmp/pip-install-zwguez5m/http/http/__init__.py", line 17, 
in 

     from request import Request
     ImportError: cannot import name 'Request' from 'request' 
(/home/tony/.local/lib/python3.7/site-packages/request/__init__.py)


     
Command "python setup.py egg_info" failed with error code 1 in 
/tmp/pip-install-zwguez5m/http/


##
So now I seem to have broken it. I'm not very savvy with the python 
packaging system, so perhaps someone here can help me as a numpty.

Thanks in advance.


-- Tony van der Hoff | mailto:t...@vanderhoff.org Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: my python is not working

2019-10-14 Thread Tony van der Hoff
On 14/10/2019 09:52, KAMALDEEP GUPTA wrote:
> 


Mine is!

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Jinja and non-ASCII characters (was Re: Prepare accented characters for HTML)

2019-03-29 Thread Tony van der Hoff
On 29/03/2019 11:08, Chris Angelico wrote:
> On Fri, Mar 29, 2019 at 9:12 PM Tony van der Hoff  
> wrote:
>>
>> Hello Chris.
>> Thanks for your interest.
>>
>> On 28/03/2019 18:04, Chris Angelico wrote:
>>> On Fri, Mar 29, 2019 at 4:10 AM Tony van der Hoff  
>>> wrote:
>>>>
>>>> This'll probably work:
>>>
>>> You have a python3 shebang, but are you definitely running this under 
>>> Python 3?
>>>
>> Absolutely.
>>
>>> Here's a much more minimal example. Can you see if this also fails for you?
>>>
>>> import sys
>>> from jinja2 import Template
>>> print(Template("French: {{french}}").render({"french": "année"}))
>>> print(sys.version)
>>>
>>
>> Presumably you expect to run this from the command line. It works as
>> expected:
>>
>> French: année
>> 3.5.3 (default, Sep 27 2018, 17:25:39)
>> [GCC 6.3.0 20170516]
>>
>> However, with a slight modification:
>>
>> #!/usr/bin/env python3
>>
>> import sys
>> from jinja2 import Template
>> print ("Content-type: text/html\n\n")
> 
> Try: text/html; charset=utf-8
> 
No difference

> That might be all you need to make the browser understand it
> correctly. Otherwise, as Thomas says, you will need to figure out
> where the traceback is, which can probably be answered by figuring out
> what "running it in a browser" actually means.
> 

Running in browser:
http://localhost/~tony/private/home/learning/jinja/minimal/minimal.py

In apache2.access.log:
::1 - tony [29/Mar/2019:11:22:13 +] "GET
/~tony/private/home/learning/jinja/minimal/minimal.py HTTP/1.1" 200 204
"http://localhost/~tony/private/home/learning/jinja/minimal/";
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.81 Safari/537.36"
::1 - - [29/Mar/2019:11:23:04 +] "-" 408 0 "-" "-"
::1 - - [29/Mar/2019:11:23:04 +] "-" 408 0 "-" "-"

So, 408 is a bit unusual for localhost. With the accented character
removed, no timeout is reported. Maybe a clue.

Can find no other traceback. Nothing relevant in apache2/error.log


-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Jinja and non-ASCII characters (was Re: Prepare accented characters for HTML)

2019-03-29 Thread Tony van der Hoff
Hello Chris.
Thanks for your interest.

On 28/03/2019 18:04, Chris Angelico wrote:
> On Fri, Mar 29, 2019 at 4:10 AM Tony van der Hoff  
> wrote:
>>
>> This'll probably work:
> 
> You have a python3 shebang, but are you definitely running this under Python 
> 3?
> 
Absolutely.

> Here's a much more minimal example. Can you see if this also fails for you?
> 
> import sys
> from jinja2 import Template
> print(Template("French: {{french}}").render({"french": "année"}))
> print(sys.version)
> 

Presumably you expect to run this from the command line. It works as
expected:

French: année
3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516]

However, with a slight modification:

#!/usr/bin/env python3

import sys
from jinja2 import Template
print ("Content-type: text/html\n\n")
print(Template("French: {{french}}").render({"french": "année"}))
print(sys.version)

and running it in a browser (tried both chrome and Firefox),
it fails as before: blank web page. Replacing the accented character
displays the expected result:

French: annee 3.5.3 (default, Sep 27 2018, 17:25:39) [GCC 6.3.0 20170516]

Thanks to all who have pitched in. As I previously mentioned, I have a
work-around, so no big deal, but I would like to get to the bottom of this.

Cheers, Tony
-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
On 28/03/2019 16:58, Chris Angelico wrote:
> On Fri, Mar 29, 2019 at 3:47 AM Tony van der Hoff  
> wrote:
>>
>> On 28/03/2019 15:09, Peter Otten wrote:
>>> Tony van der Hoff wrote:
>>>
>>>> On 28/03/2019 12:46, Jon Ribbens wrote:
>>>>> On 2019-03-28, Tony van der Hoff  wrote:
>>>>>> Thanks, Chris. The problem is not with the browser, but Jinja crashes.
>>>>>> Probably a bug, but I'm too wedded to that engine to change now. I'll
>>>>>> raise it on the Jinja bug site.
>>>>>
>>>>> It'll almost certainly be a mistake in the way you're using Jinja.
>>>>> I can't believe nobody's used non-ASCII characters in Jinja before.
>>>>>
>>>>
>>>> I'm open to suggestions.
>>>
>>> You have to describe the "crash". If you can provide a small script to
>>> reproduce it that would be best. For demonstration purposes feed the
>>> renderer a constant string instead of reading from the db.
>>>
>>> You should also tell us which version of Python and Jinja you are using.
>>>
>>>
>> OK,The crash is evidenced by an empty web page being generated,
>> containing just 
>> elements, with no content. No error messages nor exceptions.
>>
>> I.m using python3.5.3 and jinja 2.10.
>>
>> I have placed a sample script with a jnj template at
>> https://drive.google.com/drive/folders/1rM5F46wRqHYn0VBXUhSl8DkNcwsp2u8b?usp=sharing
>>
>> The template contains a commented-out line, which when uncommented shows
>> the alleged bug.
> 
> I can't see any of the code. Are you able to share it in a more
> code-friendly way, such as linking to a repository on GitHub, GitLab,
> BitBucket, SourceForge, or something else (probably with a capital
> letter in the middle of the name, for consistency)?
> 
> Or, even better: create a short enough example that you can just
> include it in the body of your post?
> 

I hate Google!

This'll probably work:

accent-test/accent-test.py:
#
#!/usr/bin/env python3

import os
from jinja2 import Environment, FileSystemLoader

PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = Environment(
autoescape=False,
loader=FileSystemLoader(os.path.join(PATH, 'templates')),
trim_blocks=False)


def render_template(template_filename, context):
return
TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)


def create_index_html():

# put the list into a dictionary for rendering
context = {
'title': "accent-test",
'french': 'année',
'french1': 'année',
  }

# render the template to html
print ("Content-type: text/html\n\n")
print (render_template('accent-test.jnj', context))

def main():
create_index_html()



if __name__ == "__main__":
main()
#

accent-test/templates/accent-test.jnj:

#


  

{{title}}
  
  

  {{title}}
{#
  {{french}}
#}
  {{french1}}

  


#

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
On 28/03/2019 15:09, Peter Otten wrote:
> Tony van der Hoff wrote:
> 
>> On 28/03/2019 12:46, Jon Ribbens wrote:
>>> On 2019-03-28, Tony van der Hoff  wrote:
>>>> Thanks, Chris. The problem is not with the browser, but Jinja crashes.
>>>> Probably a bug, but I'm too wedded to that engine to change now. I'll
>>>> raise it on the Jinja bug site.
>>>
>>> It'll almost certainly be a mistake in the way you're using Jinja.
>>> I can't believe nobody's used non-ASCII characters in Jinja before.
>>>
>>
>> I'm open to suggestions.
> 
> You have to describe the "crash". If you can provide a small script to 
> reproduce it that would be best. For demonstration purposes feed the 
> renderer a constant string instead of reading from the db.
> 
> You should also tell us which version of Python and Jinja you are using.
> 
> 
OK,The crash is evidenced by an empty web page being generated,
containing just 
elements, with no content. No error messages nor exceptions.

I.m using python3.5.3 and jinja 2.10.

I have placed a sample script with a jnj template at
https://drive.google.com/drive/folders/1rM5F46wRqHYn0VBXUhSl8DkNcwsp2u8b?usp=sharing

The template contains a commented-out line, which when uncommented shows
the alleged bug.

Good luck!
-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
On 28/03/2019 12:46, Jon Ribbens wrote:
> On 2019-03-28, Tony van der Hoff  wrote:
>> Thanks, Chris. The problem is not with the browser, but Jinja crashes.
>> Probably a bug, but I'm too wedded to that engine to change now. I'll
>> raise it on the Jinja bug site.
> 
> It'll almost certainly be a mistake in the way you're using Jinja.
> I can't believe nobody's used non-ASCII characters in Jinja before.
> 

I'm open to suggestions.

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
On 28/03/2019 11:02, Chris Angelico wrote:
> On Thu, Mar 28, 2019 at 8:58 PM Tony van der Hoff  
> wrote:
>>
>> Hi,
>>
>> I have a MariaDB database, which contains accented (mostly French)
>> characters. I need to display these on an HTML page. I'm using the Jinja
>> templating engine.
>>
>> So, for instance, é needs to be replaced by é and so on. I've had
>> some success using string.replace(), but it is difficult to cater for
>> every case.
> 
> Why not just include them as-is? Modern web browsers should have no
> trouble at all.
> 
> ChrisA
> 
Thanks, Chris. The problem is not with the browser, but Jinja crashes.
Probably a bug, but I'm too wedded to that engine to change now. I'll
raise it on the Jinja bug site.



-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
On 28/03/2019 10:19, Antoon Pardon wrote:
> On 28/03/19 10:38, Tony van der Hoff wrote:
>> Hi,
>>
>> I have a MariaDB database, which contains accented (mostly French)
>> characters. I need to display these on an HTML page. I'm using the Jinja
>> templating engine.
>>
>> So, for instance, é needs to be replaced by é and so on. I've had
>> some success using string.replace(), but it is difficult to cater for
>> every case.
> 
> How about this function (python3):
> 
> def char2html(l):
> return '&#%d;' % ord(l)
> 

Thanks, that'll work, but it's a bit of a pain examining every character
in the long (unicode?) string, and replacing it if necessary.

Meanwhile, by trial-and-error, I've found this workaround (maybe there's
a better way):

>>>'année'.encode(encoding='ascii',errors='xmlcharrefreplace').decode('ascii')
'année'


-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Prepare accented characters for HTML

2019-03-28 Thread Tony van der Hoff
Hi,

I have a MariaDB database, which contains accented (mostly French)
characters. I need to display these on an HTML page. I'm using the Jinja
templating engine.

So, for instance, é needs to be replaced by é and so on. I've had
some success using string.replace(), but it is difficult to cater for
every case.

Ideally there would be a library function to handle this, either in
Python, or Jinja, but Googling around has not revealed such.

Does anyone know of such a function, and where I might find it?

Cheers, Tony
-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Program to find Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.

2018-10-04 Thread Tony van der Hoff
On 04/10/18 09:31, Alister via Python-list wrote:
> On Wed, 03 Oct 2018 09:43:07 -0700, Musatov wrote:
> 
>> On Wednesday, October 3, 2018 at 11:12:43 AM UTC-5, Michael Torrie
>> wrote:
>>> On 10/03/2018 09:26 AM, Musatov wrote:
>>>> I don't even know where to begin! (I'm reading the Dummies book)
>>>
>>> If you have no experience in computer programming, it's going to be a
>>> steep learning curve.
>>>
>>> But your first step is to learn Python and how to write programs in it.
>>> That book and others will help with that.  You'll have to write lots of
>>> simple programs unrelated to primes along the way that help you
>>> understand programming concepts.
>>>
>>> If you already have experience in other languages, the task will be
>>> easier.
>>>
>>> Computer programming is quite natural to some (small children seem to
>>> get it much easier than us adults), but I've seen others struggle to
>>> grasp the abstract concepts for years.
>>>
>>> Once you've grasped basic Python programming, you can return top the
>>> original problem at hand.  Start by identifying the process or
>>> algorithm that would find these primes. In other words, how would you
>>> do it on pen and paper?  Computer programs are not magic.  They are
>>> only expressions of human thinking. Often some very smart
>>> mathematicians have come up with powerful algorithms (a step-by-step
>>> process) to do these things,
>>> and your job as a programmer is to turn this mathematical process into
>>> a computer program using things like loops and Boolean logic. How would
>>> you find these primes using your pen, paper, and calculator?
>>
>> Literally, how I found them was taking a list of primes and checking if
>> the calculations with the lesser primes resulted in numbers also further
>> along on the list.
>>
>> Another way I guess would be to do the calculations then check if the
>> number is prime.
> 
> That is exactly how you do it with in a program.
> 
> create a loop & check to see if the target number can be divided by each 
> possible divisor in turn
> .
> for large numbers this will take a large number of tests (hey that is why 
> you have the computer do them, it is faster than you & does not get 
> bored ;-) ) there are numerous tricks for speeding up this process once 
> you have the basic working.
> 
> start by testing small numbers & then use your real data once you have 
> something that works
> 
> as a starter a simple loop in python could be as follows
> 
> for x in xrange(10):
>   print x
> 
> once you have an outline of a program post it back here if things dont 
> work as expected
> 

Two lines, two errors! To save the noob a lot of head-scratching, that
should be:
for x in range(10):

If you're running python 3, as you should do for any new project:
print( x )



-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


[SOLVED] Re: Querying MariaDB from python

2018-10-02 Thread Tony van der Hoff
On 02/10/18 17:13, Larry Martell wrote:
> On Tue, Oct 2, 2018 at 12:09 PM Tony van der Hoff  
> wrote:
>>
>> On 02/10/18 16:47, Ervin Hegedüs wrote:
>>> hi,
>>>
>>> now rows will looks like this:
>>> ({'id':...,...},{'id':...,}...)
>>
>> Thanks Ervin, but:
>>
>>cursor = cnx.cursor(pymysql.cursors.DictCursor)
>> NameError: name 'pymysql' is not defined
>>
>> I have been using the mysql.connector module, which seems to be the
>> "official" python interface.
> 
> That also supports the cursordict:
> 
> https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
> 

Great, thanks Larry, that sorts it.

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Querying MariaDB from python

2018-10-02 Thread Tony van der Hoff
On 02/10/18 16:47, Ervin Hegedüs wrote:
> hi,
> 
> now rows will looks like this:
> ({'id':...,...},{'id':...,}...)

Thanks Ervin, but:

   cursor = cnx.cursor(pymysql.cursors.DictCursor)
NameError: name 'pymysql' is not defined

I have been using the mysql.connector module, which seems to be the
"official" python interface. I hadn't spotted the pymysql module. Is the
consensus here that pymysql is the preferred connector?

Cheers,

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Querying MariaDB from python

2018-10-02 Thread Tony van der Hoff
On 02/10/18 16:37, Larry Martell wrote:
> On Tue, Oct 2, 2018 at 11:34 AM Tony van der Hoff  
> wrote:
>>I would have expected the connector to be able to return a
>> dictionary.
>>
>> Can anyone suggest a better way of doing this?
> 
> https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.DictCursor
> 
Well, thanks, Larry, for taking the trouble to reply, but I can't see
how that solves the issue.

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Querying MariaDB from python

2018-10-02 Thread Tony van der Hoff
I'm writing a database application, in python 3,5 under Debian9.

My code:

    def get_albums(self, parent_id = 0 ):
    cursor = self.cnx.cursor()
    sql =(  "select"
    "    id"
    ",   parent_id"
    ",   title"
    ",   ifnull( description, '' )"
    ",   path"
    ",   date( from_unixtime( date_created ) ) as date"
    " from album"
    " where parent_id = %(parent_id)s"
    " order by date_created"
 )
    cursor.execute( sql, {'parent_id': parent_id } )   
    rows = cursor.fetchall()

    # return result as a list of dicts
    result = []

    for row in rows:
    result.append({ 'id':row[0],
    'parent_id':row[1],
    'title':row[2],
    'description':row[3],
    'path':row[4],
    'date':row[5],
    }
    )
    return result

This works OK, but looks inelegant. Having to iterate through the
returned data to get it into a dictionary is error-prone if the query
changes. I would have expected the connector to be able to return a
dictionary.

Can anyone suggest a better way of doing this?
 

-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |

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


Re: New PyPI launched, legacy PyPI shutting down April 30

2018-04-18 Thread Tony van der Hoff
On 18/04/18 13:15, Zbigniew Jędrzejewski-Szmek wrote:
> On Mon, Apr 16, 2018 at 01:21:50PM -0400, Laura Hampton wrote:
>> New PyPI launched, legacy PyPI shutting down April 30[1]  
>>
>> Starting today, the canonical Python Package Index is at https://pypi.org 
>> and uses the new Warehouse codebase.  We announced the https://pypi.org beta 
>> on March 26 and your feedback and test usage have helped us get it 
>> production-ready.  
> Search seems to be broken:
>> https://pypi.org/search/?q=numpy
> There were no results for 'numpy' 
>
> Zbyszek
*Using your link:
2,797* projects for "/numpy/"

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


Re: we want python software

2017-12-08 Thread Tony van der Hoff
On 05/12/17 16:55, Igor Korot wrote:
> Hi,
>
> On Tue, Dec 5, 2017 at 9:10 AM, Jyothiswaroop Reddy
>  wrote:
>> Sir,
>> I am b.tech student I would like to learn python. So please send the
python software.
> Sorry, we don't send anything. You will have to go get it yourself. -)
>
Well, at least try to be helpful:
https://www.python.org/downloads/

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


Re: we want python software

2017-12-05 Thread Tony van der Hoff
On 05/12/17 16:55, Igor Korot wrote:
> Hi,
>
> On Tue, Dec 5, 2017 at 9:10 AM, Jyothiswaroop Reddy
>  wrote:
>> Sir,
>> I am b.tech student I would like to learn python. So please send the 
>> python software.
> Sorry, we don't send anything. You will have to go get it yourself. -)
>
Well, at least try to be helpful:
https://www.python.org/downloads/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please improve these comprehensions (was meaning of [ ])

2017-09-06 Thread Tony van der Hoff
On 06/09/17 16:31, Ian Kelly wrote:
> On Wed, Sep 6, 2017 at 1:37 AM, Marko Rauhamaa  wrote:
>> Which reminds me of this puzzle I saw a couple of days ago:
>>
>>1 + 4 = 5
>>2 + 5 = 12
>>3 + 6 = 21
>>8 + 11 = ?
>>
>> A mathematician immediately comes up with a "wrong" answer.
> There are no "wrong" answers with these kinds of puzzles. There are
> only answers with varying degrees of parsimony with the known facts.
>
> I say the answer is clearly "banana" because the key to the puzzle is
> that everything matches a line from the following look-up table:
>
> 5 => 5
> 7 => 12
> 9 => 21
> 19 => banana

40


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


Re: Dynamically replacing an objects __class__; is it safe?

2017-03-17 Thread Tony van der Hoff

On 17/03/17 04:18, Gregory Ewing wrote:

Dennis Lee Bieber wrote:

I'd say satellites do "not" fly, as they have no force/action
opposing
the fall caused by the pull of gravity.


Arrows, bullets, thrown stones, etc. are often said to be
flying.

Seems to me the word gets applied to anything that is
moving while not contacting the ground.


Yep, like a Ferrari on a motorway


--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: Dynamically replacing an objects __class__; is it safe?

2017-03-16 Thread Tony van der Hoff

On 16/03/17 13:45, Robin Becker wrote:

On 15/03/2017 13:53, Steve D'Aprano wrote:

You probably can't make a whale fly just by changing the class to
bird. It
will need wings, and feathers, at the very least.


the whale in the Hitchhiker's Guide found itself flying without feathers
or wings


It didn't so much fly, as plummet.

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


HTML templating tools

2016-10-20 Thread Tony van der Hoff
For a long time, under Python 2.7, I have been using htmltmpl to
generate htmjl pages programmatically from Python.

However, htmltmpl is not available for python3, and doesn't look as if
it ever will be. Can anyone recommend a suitable replacement (preferably
compatible with htmltmpl)?

Cheers, Tony

-- 
Tony van der Hoff  | mailto:t...@vanderhoff.org
Ariège, France |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: manually sorting images?

2016-09-05 Thread Tony van der Hoff
On 04/09/16 09:53, Ulli Horlacher wrote:
> I need to sort images (*.jpg), visually, not by file name.
> It looks, there is no standard UNIX tool for this job?
> 

There is a very good tutorial here:
http://www.pyimagesearch.com/2014/12/01/complete-guide-building-image-search-engine-python-opencv/
-- 
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sum accuracy

2016-04-15 Thread Tony van der Hoff

On 15/04/16 11:10, Ben Bacarisse wrote:

Oscar Benjamin  writes:


On 15 April 2016 at 10:24, Robin Becker  wrote:



yes indeed summation is hard :(


Not with Fraction it isn't:

from fractions import Fraction

def exact_sum(nums):
 return sum(map(Fraction, nums))

This will give you the exact result with precisely zero rounding
error. You can convert it to float at the end.


Just a word of warning for people new to numerical work: there's no
rounding error, but unless you start with Fraction objects you still
have input or conversion errors.  The uninitiated might expect

   exact_sum([0.3, 0.7])

to be 1.



So I'm uninitiated:
NameError: name 'exact_sum' is not defined

I appreciate the word of warning, but, in my case, it's not helpful.

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: Import error

2016-04-05 Thread Tony van der Hoff

On 05/04/16 10:53, Nicolae Morkov wrote:

What can I do   I've tried everything



Just hang your head and cry...

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: importing

2016-03-07 Thread Tony van der Hoff
Thanks to all who replied to my cry for help; I understand it better 
now. But:


On 07/03/16 16:08, Chris Angelico wrote:


The documentation should tell you what you need to import to make
something work. In this case, I would guess that "import
tkinter.messagebox" or "from tkinter import messagebox" would be the
recommended way to use this module.


Well, I found the tkinter documentation to be sparse in the extreme 
(https://docs.python.org/release/3.1.3/library/tkinter.html), and it 
certainly doesn't go into that sort of detail.


However, more generally, how am I supposed to know that a module is part 
of a package, and needs a "magic" stanza to get a module loaded?


Cheers,
--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


importing

2016-03-07 Thread Tony van der Hoff

I thought I understood this, but apparently not:
Under py3:

1. "import tkinter" imports the whole module into the name space. Any 
access to names therein must be prefixed with the module name.

ie top = tkinter.Tk()
But tkinter.messagebox.showwarning()  errors with "module has no 
attribute 'messagebox'"


2. "from tkinter import *" loads the name space from the module into the 
program name space. No need to prefix the module name onto the attribute 
name. Pollutes the name space, but makes typing easier.

ie top = Tk()
But messagebox.showwarning() still errors.

3. in either of the above cases, if I add "from tkinter import 
messagebox, the attribute resolves correctly.


I imagined that the "*" form implied "load the lot". Evidently, my 
understanding is lacking. Will somebody please put me straight, or give 
me a reference to some definitive documentation?


--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: Pyhon 2.x or 3.x, which is faster?

2016-03-07 Thread Tony van der Hoff

On 06/03/16 14:41, Steven D'Aprano wrote:

On Sun, 6 Mar 2016 10:34 pm, Tony van der Hoff wrote:


Hi, I've been experimenting with a short test program under python 2.7
and python 3.4.2. It's a simple read from file, and locate a word therein.

I get the (subjective) impression that python2  is slightly faster than
python3. Is that correct? Is there any documentation to support this?


I believe that, overall, Python 3 is still slightly slower than Python 2,
but it's a near thing. Have a look at the latest performance benchmarks:

https://speed.python.org/comparison/

Eyeballing the graph, I estimate that the latest 3.x version is probably
about 10% slower overall, although different benchmarks show different
speeds.


Excellent, just what I was looking for. Thank you very much, Steven.

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Pyhon 2.x or 3.x, which is faster?

2016-03-06 Thread Tony van der Hoff
Hi, I've been experimenting with a short test program under python 2.7 
and python 3.4.2. It's a simple read from file, and locate a word therein.


I get the (subjective) impression that python2  is slightly faster than 
python3. Is that correct? Is there any documentation to support this?


Thanks,
--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-19 Thread Tony van der Hoff

On 19/02/16 11:23, Mark Lawrence wrote:

On 19/02/2016 10:47, wrong.addres...@gmail.com wrote:


2 12.657823 0.1823467E-04 114 0
3 4 5 9 11
"Lower"
278.15

Is it straightforward to read this, or does one have to read one
character at a time and then figure out what the numbers are?



One character at a time in a high level language like Python, please.
See http://nedbatchelder.com/text/python-parsers.html for a list of
parsers that can do all sorts for you.  Or the stdlib re module
https://docs.python.org/3/library/re.html.  Or a likely replacement for
the re module https://pypi.python.org/pypi/regex.


Am I alone in thinking that this wrongaddress character is trolling?

How much effort can it be to just install python, and try out these 
simple things *before* asking trivia here?


--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: Reg: Data frame conversion

2016-02-17 Thread Tony van der Hoff

On 17/02/16 18:00, Sushanth wrote:

​i need to convert r data fr​ame to pandas dataframe and vise versa


Wow! How do you plan to do that?

--
Tony van der Hoff| mailto:t...@vanderhoff.org
Buckinghamshire, England |
--
https://mail.python.org/mailman/listinfo/python-list


Re: What is the fastest way to do 400 HTTP requests using requests library?

2016-01-05 Thread Tony van der Hoff
On 05/01/16 00:51, Ian Kelly wrote:
> On Mon, Jan 4, 2016 at 4:38 PM, Steven D'Aprano  wrote:
>> On Tue, 5 Jan 2016 07:50 am, livems...@gmail.com wrote:
>>
>>> So what is the fastest way to make 400 HTTP requests using "requests"
>>> library and also using tor proxy?
>>
>>
>> Since this will be I/O bound, not CPU bound, probably use separate threads.
>>
>> Push the 400 requests into a queue, then create N threads, where N will need
>> to be determined by experiment, but will probably be something like 4 or 8,
>> and let each thread pop a request from the queue as needed.
>>
>> Are you experienced with threads? Do you need further information about
>> using threads and queues?
> 
> Also see the concurrent.futures module in the standard library, which
> makes this sort of setup very simple to implement.
> 
Why would someone want to make 400 HTTP requests in a short time?


-- 
Tony van der Hoff  | mailto:t...@vanderhoff.org
Ariège, France |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trailing zeros of 100!

2016-01-03 Thread Tony van der Hoff
On 02/01/16 17:56, Robin Koch wrote:
> Am 02.01.2016 um 17:09 schrieb Tony van der Hoff:
>> On 02/01/16 16:57, Robin Koch wrote:
>>> sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])
>>
>> But did you actually test it?
> 
> Yes, should work for n >= 1.
> 
> Why do you ask?
> 
>From your original post:

How about:

 >>> from math import log
 >>> sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])

That would never work; n is undefined. Now, you may have left that as an
exercise for the reader, but without warning, for an obvious newbie such
as the OP, that would have been unnecessarily confusing.

-- 
Tony van der Hoff  | mailto:t...@vanderhoff.org
Ariège, France |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trailing zeros of 100!

2016-01-02 Thread Tony van der Hoff
On 02/01/16 16:57, Robin Koch wrote:
> sum([int(0.2**k*n) for k in range(1, int(log(n, 5))+1)])

But did you actually test it?

-- 
Tony van der Hoff  | mailto:t...@vanderhoff.org
Ariège, France |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 2to3 translation problem

2015-12-12 Thread Tony van der Hoff

On 12/12/15 17:54, Laura Creighton wrote:

In a message of Sun, 13 Dec 2015 04:50:43 +1100, Chris Angelico writes:

On Sun, Dec 13, 2015 at 4:30 AM, Tony van der Hoff  wrote:

Thanks, Laura, and others who have replied. You're right; python-3-pygame
exists in unstable, but has not yet made it to jessie, even in backports.

So, I'll stick with python 2.7 for the time being; really no hardship :)


The easiest solution is simply:

python3 -m pip install pygame

Don't worry about it not being in the Jessie repo - you can always
grab things using pip.

ChrisA


What Chris said. :)

If you are about to move your life from being python2.7 based to
being 3.x, you are not going to be able to depend on things getting
to jessie in a timely fashion.  So you will be doing this a whole lot.


No:
tony@tony-lx:~$ python3 -m pip install pygame
/usr/bin/python3: No module named pip

Hmm, apt-get install python3-pip: OK

tony@tony-lx:~$ python3 -m pip install pygame
Downloading/unpacking pygame
  Could not find any downloads that satisfy the requirement pygame
  Some externally hosted files were ignored (use --allow-external 
pygame to allow).

Cleaning up...
No distributions at all found for pygame
Storing debug log for failure in /home/tony/.pip/pip.log

I really can't be bothered...

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


Re: 2to3 translation problem

2015-12-12 Thread Tony van der Hoff

On 12/12/15 17:09, Laura Creighton wrote:

In a message of Sat, 12 Dec 2015 17:59:52 +0100, Peter Otten writes:

Tony van der Hoff wrote:


On 12/12/15 15:09, Mark Lawrence wrote:

On 12/12/2015 14:42, Tony van der Hoff wrote:

Debian Jessie, python 2.7; python 3.4

I have an application, using pygame for graphics, that works fine under
python2.7. I have run it through 2to3, but when running the result under
python 3.4, I get the error :

Traceback (most recent call last):
File "ppm304.py", line 9, in 
  import pygame
ImportError: No module named 'pygame'

So, python 3.4 can't find the library, whilst python 2.7 can.
How do I track down/fix the missing dependency.


This isn't a 2to3 translation problem.  You've installed pygame under
2.7 at some point, repeat the process for 3.4.  I've no idea how you'd
do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame".


Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from
Debian's repository, via apt-get install python-pygame. I believe that
should be effective for any version of Python.


No, that is the version for Python 2. If there is a Python 3 version it will
be called

python3-pygame

but no such package seems to be available:

https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=python3-pygame


There is one in unstable, I forgot to check for jessie, sorry about that.

Laura

Thanks, Laura, and others who have replied. You're right; 
python-3-pygame exists in unstable, but has not yet made it to jessie, 
even in backports.


So, I'll stick with python 2.7 for the time being; really no hardship :)

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


Re: 2to3 translation problem

2015-12-12 Thread Tony van der Hoff

On 12/12/15 15:09, Mark Lawrence wrote:

On 12/12/2015 14:42, Tony van der Hoff wrote:

Debian Jessie, python 2.7; python 3.4

I have an application, using pygame for graphics, that works fine under
python2.7. I have run it through 2to3, but when running the result under
python 3.4, I get the error :

Traceback (most recent call last):
   File "ppm304.py", line 9, in 
 import pygame
ImportError: No module named 'pygame'

So, python 3.4 can't find the library, whilst python 2.7 can.
How do I track down/fix the missing dependency.


This isn't a 2to3 translation problem.  You've installed pygame under
2.7 at some point, repeat the process for 3.4.  I've no idea how you'd
do that on Debian Jessie but on Windows it'd be "pip3.4 install pygame".

Thanks, Mark, for the pointer. I'm pretty sure I installed Pygame from 
Debian's repository, via apt-get install python-pygame. I believe that 
should be effective for any version of Python.


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


2to3 translation problem

2015-12-12 Thread Tony van der Hoff

Debian Jessie, python 2.7; python 3.4

I have an application, using pygame for graphics, that works fine under 
python2.7. I have run it through 2to3, but when running the result under 
python 3.4, I get the error :


Traceback (most recent call last):
  File "ppm304.py", line 9, in 
import pygame
ImportError: No module named 'pygame'

So, python 3.4 can't find the library, whilst python 2.7 can.
How do I track down/fix the missing dependency.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Accessing container's methods [solved]

2015-12-08 Thread Tony van der Hoff

Hum, sorry about the empty reply; just finger trouble!

Anyway I wasn't expecting such a great response; thanks to all.

On 07/12/15 23:47, Erik wrote:
[snip]


As you can't sensibly put the object into more than one container at a
time anyway, then you can pass the container object to the Actor object
as its "parent". It can then call its parent object for things that the
parent will know (such as, the total number of contained objects):

class Actor:
def __init__ ( self, name, id, parent ):
  self.name = name
  self.id = id
  self.parent = parent

def get_name( self ):
  txt = "I'm Actor {} Number {} of {}".\
   format(  self.name, self.id, self.parent.count_actors() )
  return txt

Then you can add a new actor with:

   self.actors.append( Actor( n, i, self ) )

Whilst I'm grateful for all the responses, this is the one that got me 
out of the hole I dug myself into.


In fact, this is precisely what I tried previously, and got:
TypeError: 'instancemethod' object has no attribute '__getitem__'

In my naivety, I concluded that this meant I couldn't use the 'self' 
pointer in this way. However, trying it with the Monty example, it 
worked fine, and I have now tracked down my error elsewhere.




Note that you are creating circular references here, too (the container
references the Actor object and the Actor object references the
container). Just another possible issue to bear in mind ...

Yes, I guess it's quite nasty, but, in the non-trivial case, I'm only 
calling for dynamic data from the parent, and not modifying it in any 
way, so I think I can get away with it. Otherwise, I'd have to pass a 
vast list of initialization data to the (many) children, and keep that 
up to date by passing it down the line to each one, just in case it's 
required, which would slow down things excessively. I know that if a 
design doesn't feel comfortable, then it's probably wrong, but I believe 
that in this case it's probably the best way forward.




Also, while I'm looking at this, you have this loop and comment:

 >def __init__( self, names ):
 >  self.actors = []
 >
 >  i = 0
 >  for n in names:
 >self.actors.append( Actor( n, i ) )
 >i += 1# here is a case for python supporting post-increment!

However, if you refactor that loop to use iterators, you don't need to
manually manipulate 'i' at all (you need to import the itertools module
first, and this is the "new" version where the container is passed in as
the parent):

 def __init__( self, names ):
   self.actors = [ Actor ( n, i, self ) for n, i in
itertools.izip(names, itertools.count()) ]

Or, if you don't like list comprehensions:

 def __init__( self, names ):
   self.actors = []
   for n, i in itertools.izip(names, itertools.count()):
 self.actors.append( Actor( n, i, self ) )


I rather liked Terry's suggestion of using enumerate.

The comment was tounge-in-cheek: Referring to an earlier thread, I'm yet 
to be convinced that Python is better for not having 
pre/post-increment/decrement operators. But, hey, I'm sure better minds 
than mine have addressed the subject ;)



(I assume you're using Python 3 because of your print statement - in
Python 3, 'itertools.izip' should just be 'zip'.)


No, Im actually stuck on Python 2.7. I don't see how you jumped to that 
conclusion from a simple print statement.


On 07/12/15 21:38, Terry Reedy wrote:
[snip]
> This is actually a case for using enumerate:
>for i, name in enumerate(names):
>
I've not come across this previously, but shall certainly use it in 
future. Thanks!


> return list(self.actors)  # or perhaps even faster
> return self.actors[:]

That doesn't seem to work:
<__main__.Actor instance at 0x7fc7478ba560>
<__main__.Actor instance at 0x7fc7478ba5a8>
<__main__.Actor instance at 0x7fc7478ba5f0>


Anyway, I'm no longer in a hole; thanks for all the excellent help. I'll 
certainly review the design of my current project, to see if it can be 
improved.


Cheers, Tony

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


Re: Accessing container's methods

2015-12-08 Thread Tony van der Hoff

On 07/12/15 23:47, Erik wrote:

Hi Tony,

On 07/12/15 18:10, Tony van der Hoff wrote:

A highly contrived example, where I'm setting up an outer class in a
Has-a relationship, containing a number of Actors. The inner class needs
to access a method of the outer class; here the method get_name.


Generally, an object should not need to know which container it's in
(let alone its "index" or "key" in that container). Amongst other
things, you can't put the object into multiple containers which might be
organised differently and you are asking for bugs where the container
and the object get out of sync WRT just where the object is in the
container (in your example, if you found you wanted to add a method
where the 'actors' list is modified (say, calling "self.actors.insert(3,
...)", or sorting the list) then things get nasty quickly.

However, you've said this is a highly contrived example, so I'll bear
with you and assume what you're trying to do is not quite as nasty as
the example implies ;)


Can anyone please advise me on how to achieve this magic?


As you can't sensibly put the object into more than one container at a
time anyway, then you can pass the container object to the Actor object
as its "parent". It can then call its parent object for things that the
parent will know (such as, the total number of contained objects):

class Actor:
def __init__ ( self, name, id, parent ):
  self.name = name
  self.id = id
  self.parent = parent

def get_name( self ):
  txt = "I'm Actor {} Number {} of {}".\
   format(  self.name, self.id, self.parent.count_actors() )
  return txt

Then you can add a new actor with:

   self.actors.append( Actor( n, i, self ) )


Note that you are creating circular references here, too (the container
references the Actor object and the Actor object references the
container). Just another possible issue to bear in mind ...


Also, while I'm looking at this, you have this loop and comment:

 >def __init__( self, names ):
 >  self.actors = []
 >
 >  i = 0
 >  for n in names:
 >self.actors.append( Actor( n, i ) )
 >i += 1# here is a case for python supporting post-increment!

However, if you refactor that loop to use iterators, you don't need to
manually manipulate 'i' at all (you need to import the itertools module
first, and this is the "new" version where the container is passed in as
the parent):

 def __init__( self, names ):
   self.actors = [ Actor ( n, i, self ) for n, i in
itertools.izip(names, itertools.count()) ]

Or, if you don't like list comprehensions:

 def __init__( self, names ):
   self.actors = []
   for n, i in itertools.izip(names, itertools.count()):
 self.actors.append( Actor( n, i, self ) )

(I assume you're using Python 3 because of your print statement - in
Python 3, 'itertools.izip' should just be 'zip'.)
HTH,
E.


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


Accessing container's methods

2015-12-07 Thread Tony van der Hoff

Hi,

I have a class A, containing embedded embedded classes, which need to 
access methods from A.

.
A highly contrived example, where I'm setting up an outer class in a 
Has-a relationship, containing a number of Actors. The inner class needs 
to access a method of the outer class; here the method get_name.


I don't really want to make Actor a sub-class (is-a; it isn't) of Monty; 
that would raise all sorts of other problems.


Can anyone please advise me on how to achieve this magic?

# define the outer class
class Monty:
  def __init__( self, names ):
self.actors = []

i = 0
for n in names:
  self.actors.append( Actor( n, i ) )
  i += 1# here is a case for python supporting post-increment!

  def count_actors( self ):
return len( self.actors )

  def list_actors( self ):
h=[]
for n in self.actors:
  h.append( n.get_name() )
return h

# define the inner class
class Actor:
  def __init__ ( self, name, id ):
self.name = name
self.id = id

  def get_name( self ):

# and here lies the problem;
# AttributeError: Actor instance has no attribute 'count_actors'
# how do I access the method in the enclosing class
txt = "I'm Actor {} Number {} of {}".\
 format(  self.name, self.id, self.count_actors() )

# this works, of course
#txt = "I'm Actor \"{}\"; Number {}.  ".\
format( self.name, self.id )

return txt

if __name__ == '__main__':
  o = Monty( ["Cleese", "Idle", "Palin" ] )
  print "number: ",o.count_actors()
  a = o.list_actors()
  for l in a:
print l

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


Re: increment/decrement operators

2015-12-05 Thread Tony van der Hoff

On 05/12/15 12:56, Robin Koch wrote:

Am 05.12.2015 um 13:40 schrieb Tony van der Hoff:

Hi,

I'm a relative newbie to python, and this NG, but it's certainly growing
on me.

One thing I'm missing is the increment/decrement operator from C, ie
x++, and its ilk. Likewise x += y.

is there any way of doing this in Python?


Quick answer:

x += y works. (Well, it should.)

x++ doesn't.

Long answer:

I'm sure someone more experienced will come up with one shortly. :-)

Until then I found this:
http://stackoverflow.com/a/1485854


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


increment/decrement operators

2015-12-05 Thread Tony van der Hoff

Hi,

I'm a relative newbie to python, and this NG, but it's certainly growing 
on me.


One thing I'm missing is the increment/decrement operator from C, ie 
x++, and its ilk. Likewise x += y.


is there any way of doing this in Python?

TIA, Tony
--
https://mail.python.org/mailman/listinfo/python-list