Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-18 Thread Barry via Python-list


> On 17 Aug 2023, at 15:01, c.buhtz--- via Python-list  
> wrote:
> 
> I want to display one string in its original source (untranslated) version 
> and in its translated version site by site without duplicating the string in 
> the python source code?
> It wouldn't be a big deal if it is only one word.

The key to solving this to separate the parsing of the string into the .po file 
and its translation.

def i18n(s):
  return s

msg = i18n(‘my message’)

print(_(msg))
print(msg)

Now you tell the xgettex, pygettext etc, to parse to use “i18n” to find strings 
to translate.

This is covered in the docs at 
https://docs.python.org/3/library/gettext.html#localizing-your-module

Barry





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


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Greg Ewing via Python-list

On 17/08/23 7:10 pm, c.bu...@posteo.jp wrote:

def foobar(translate):
     if not translate:
     # I try to mask the global _() builtins-function
     def _(txt):
     return txt

     return _('Hello')


This causes _ to become a local that is left undefined on one
branch of the if. You need to ensure it's always defined. Here's
one way that should work:

gttran = _

def foobar(translate):
def _(txt):
if translate:
return gttran(txt)
else:
return txt
return _('Hello')

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


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Mirko via Python-list

Am 17.08.23 um 21:17 schrieb c.buhtz--- via Python-list:

Hello Mirko,

thanks for reply.

Am 17.08.2023 18:19 schrieb Mirko via Python-list:

You could solve it by defining _() locally like so:

def foobar(translate):
    _ = gettext.gettext


I see no way to do that. It is not the "class based API" of gettext 
installing _() into the builtins namespace.



Does this work:

def foobar(translate):
_ = __builtins__._



My users are able to configure the language of their UI explicit. It 
is a full application.



def orig_and_trans(msg):
    return (_(msg), msg)


This will be ignored by GNU gettext utils (xgettext in my case) will 
ignore this line because they do not know what "msg" is. The string 
"hello" won't appear in the pot-file.



xgettext has an option "-k" which allows you to specify an 
additional "keyword" (like a function name, I guess) for detecting 
translatable strings. With the orig_and_trans() function, the 
following command produces a messages.po with "hello" in it.


xgettext -korig_and_trans source.py
--
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread c.buhtz--- via Python-list

Hello Mirko,

thanks for reply.

Am 17.08.2023 18:19 schrieb Mirko via Python-list:

You could solve it by defining _() locally like so:

def foobar(translate):
_ = gettext.gettext


I see no way to do that. It is not the "class based API" of gettext 
installing _() into the builtins namespace.
My users are able to configure the language of their UI explicit. It is 
a full application.



def orig_and_trans(msg):
return (_(msg), msg)


This will be ignored by GNU gettext utils (xgettext in my case) will 
ignore this line because they do not know what "msg" is. The string 
"hello" won't appear in the pot-file.

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


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Dieter Maurer via Python-list
c.bu...@posteo.jp wrote at 2023-8-17 07:10 +:
>I want to display one string in its original source (untranslated)
>version and in its translated version site by site without duplicating
>the string in the python source code?

You could try to translate into an unknown language: this
should give you the default translation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Richard Damon via Python-list
> On Aug 17, 2023, at 10:02 AM, c.buhtz--- via Python-list 
>  wrote:
> 
> X-Post: https://stackoverflow.com/q/76913082/4865723
> 
> I want to display one string in its original source (untranslated) version 
> and in its translated version site by site without duplicating the string in 
> the python source code?
> It wouldn't be a big deal if it is only one word.
> 
>print('The translated string "{}" is originally "{}".'.format(_('Hello'), 
> 'Hello'))
> 
> But in my situation it is a multi line string containing multiple paragraphs. 
> It is a full text. I don't want to duplicate that string.
> 
># Imagine 'Hello' as a 50x70 characters multi line string.
>original = 'Hello'
>translated = _('Hello')
>print('The translated string "{}" is originally "{}".'.format(translated, 
> original))
> 
> I do use the "class based API" of GNU gettext. My current approach, which is 
> not working, is to somehow (how!?) disable (or mask) the translation function 
> "_()" temporarily.
> But as described in the stackoverflow question (see first line of this mail) 
> this do not work.
> 
> def foobar(translate):
>if not translate:
>    # I try to mask the global _() builtins-function
>def _(txt):
>return txt
> 
>return _('Hello')
> 
> if __name__ == '__main__':
> 
># To ilustrate that _() is part of "builtins" namespace
>print(_('No problem.'))
> 
>print('The translated string "{}" is originally "{}".'
>  .format(foobar(True), foobar(False)))
> 
> This is the output:
> 
>Traceback (most recent call last):
>  File "/home/user/ownCloud/_transfer/./z.py", line 27, in 
>.format(foobar(True), foobar(False)))
>  File "/home/user/ownCloud/_transfer/./z.py", line 19, in foobar
>return _('Hello')
>UnboundLocalError: local variable '_' referenced before assignment
> 
> The full MWE can be found at stackoverflow 
> (https://stackoverflow.com/q/76913082/4865723).
> 
> The question is if this can be solved somehow or if there is an alternative 
> approach.
> The "_()" function is installed in the builtins namespace because of gettext 
> class based API. This is nice.
> Maybe I can somehow manipulate that builtins namespace? I tried to import 
> builtins and played around with it but couldn't find a way to do it.
> 
> Thanks
> Christian Buhtz
> 
> PS: This is IMHO not relevant for my question but if someone is interested 
> the connection to productive code can be found in this issue: 
> https://github.com/bit-team/backintime/issues/1473 There I describe what I 
> want to achive and also provide a GUI mockup.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

One thing to remember is that the _() function, which calls gettext doesn’t 
need a literal string, so you can set a variable to ‘raw’ string, and then 
translate it to another variable, so you can have both.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Dieter Maurer via Python-list
c.bu...@posteo.jp wrote at 2023-8-17 07:10 +:
>I want to display one string in its original source (untranslated)
>version and in its translated version site by site without duplicating
>the string in the python source code?

Is it an option for you to replace the `gettext` binding
by `zope.i18nmessageid`? Its `Message` instances provide
access to all interesting attributes (id, default, mapping, domain).
Together with other packages (--> `zope.i18n` and `i18ndude`)
it is compatible with `GNU gettext` translation catalogs.

If this is not an option, use Python's inspection functionality
to learn which attributes are made available by the binding's
message class.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Mirko via Python-list

Am 17.08.23 um 09:10 schrieb c.buhtz--- via Python-list:



     UnboundLocalError: local variable '_' referenced before assignment


This is a common gotcha:

https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

You could solve it by defining _() locally like so:


def foobar(translate):
_ = gettext.gettext
if not translate:
# I try to mask the global _() builtins-function
def _(txt):
return txt
return _('minutes')



The question is if this can be solved somehow or if there is an alternative 
approach.


However, you might not need this, because the following seems to 
work for me:


def orig_and_trans(msg):
return (_(msg), msg)

print('The translated string "{}" is originally 
"{}".'.format(*orig_and_trans("hello")))


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


GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread c.buhtz--- via Python-list

X-Post: https://stackoverflow.com/q/76913082/4865723

I want to display one string in its original source (untranslated) 
version and in its translated version site by site without duplicating 
the string in the python source code?

It wouldn't be a big deal if it is only one word.

print('The translated string "{}" is originally 
"{}".'.format(_('Hello'), 'Hello'))


But in my situation it is a multi line string containing multiple 
paragraphs. It is a full text. I don't want to duplicate that string.


# Imagine 'Hello' as a 50x70 characters multi line string.
original = 'Hello'
translated = _('Hello')
print('The translated string "{}" is originally 
"{}".'.format(translated, original))


I do use the "class based API" of GNU gettext. My current approach, 
which is not working, is to somehow (how!?) disable (or mask) the 
translation function "_()" temporarily.
But as described in the stackoverflow question (see first line of this 
mail) this do not work.


def foobar(translate):
if not translate:
# I try to mask the global _() builtins-function
def _(txt):
return txt

return _('Hello')

if __name__ == '__main__':

# To ilustrate that _() is part of "builtins" namespace
print(_('No problem.'))

print('The translated string "{}" is originally "{}".'
  .format(foobar(True), foobar(False)))

This is the output:

Traceback (most recent call last):
  File "/home/user/ownCloud/_transfer/./z.py", line 27, in 
.format(foobar(True), foobar(False)))
  File "/home/user/ownCloud/_transfer/./z.py", line 19, in foobar
return _('Hello')
UnboundLocalError: local variable '_' referenced before assignment

The full MWE can be found at stackoverflow 
(https://stackoverflow.com/q/76913082/4865723).


The question is if this can be solved somehow or if there is an 
alternative approach.
The "_()" function is installed in the builtins namespace because of 
gettext class based API. This is nice.
Maybe I can somehow manipulate that builtins namespace? I tried to 
import builtins and played around with it but couldn't find a way to do 
it.


Thanks
Christian Buhtz

PS: This is IMHO not relevant for my question but if someone is 
interested the connection to productive code can be found in this issue: 
https://github.com/bit-team/backintime/issues/1473 There I describe what 
I want to achive and also provide a GUI mockup.

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


Re: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug?

2022-11-13 Thread Eryk Sun
On 11/13/22, Jessica Smith <12jessicasmit...@gmail.com> wrote:
> Consider the following code ran in Powershell or cmd.exe:
>
> $ python -c "print('└')"
> └
>
> $ python -c "print('└')" > test_file.txt
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in
> encode
> return codecs.charmap_encode(input,self.errors,encoding_table)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in
> position 0: character maps to 

If your applications and existing data files are compatible with using
UTF-8, then in Windows 10+ you can modify the administrative regional
settings in the control panel to force using UTF-8. In this case,
GetACP() and GetOEMCP() will return CP_UTF8 (65001), and the reserved
code page constants CP_ACP (0),  CP_OEMCP (1), CP_MACCP (2), and
CP_THREAD_ACP (3) will use CP_UTF8.

You can override this on a per-application basis via the
ActiveCodePage setting in the manifest:

https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#activecodepage

In Windows 10, this setting only supports "UTF-8". In Windows 11, it
also supports "legacy" to allow old applications to run on a system
that's configured to use UTF-8.  Setting an explicit locale is also
supported in Windows 11, such as "en-US", with fallback to UTF-8 if
the given locale has no legacy code page.

Note that setting the system to use UTF-8 also affects the host
process for console sessions (i.e. conhost.exe or openconsole.exe),
since it defaults to using the OEM code page (UTF-8 in this case).
Unfortunately, a legacy read from the console host does not support
reading non-ASCII text as UTF-8. For example:

>>> os.read(0, 6)
SPĀM
b'SP\x00M\r\n'

This is a trivial bug in the console host, which stems from the fact
that UTF-8 is a multibyte encoding (1-4 bytes per code), but for some
reason the console team at Microsoft still hasn't fixed it. You can
use chcp.com to set the console's input and output code pages to
something other than UTF-8 if you have to read non-ASCII input in a
legacy console app. By default, this problem doesn't affect Python's
sys.stdin, which internally uses wide-character ReadConsoleW() with
the system's native text encoding, UTF-16LE.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug?

2022-11-13 Thread Thomas Passin

On 11/13/2022 9:49 AM, Jessica Smith wrote:

Consider the following code ran in Powershell or cmd.exe:

$ python -c "print('└')"
└

$ python -c "print('└')" > test_file.txt
Traceback (most recent call last):
   File "", line 1, in 
   File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode
 return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in
position 0: character maps to 

Is this a known limitation of Windows + Unicode? I understand that
using -x utf8 would fix this, or modifying various environment
variables. But is this expected for a standard Python installation on
Windows?

Jessica



This also fails with the same error:

$ python -c "print('└')" |clip
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug?

2022-11-13 Thread Barry


> On 13 Nov 2022, at 14:52, Jessica Smith <12jessicasmit...@gmail.com> wrote:
> 
> Consider the following code ran in Powershell or cmd.exe:
> 
> $ python -c "print('└')"
> └
> 
> $ python -c "print('└')" > test_file.txt
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode
>return codecs.charmap_encode(input,self.errors,encoding_table)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in
> position 0: character maps to 
> 
> Is this a known limitation of Windows + Unicode? I understand that
> using -x utf8 would fix this, or modifying various environment
> variables. But is this expected for a standard Python installation on
> Windows?

Your other thread has a reply that explained this.
It is a problem with windows and character sets.
You have to set things up to allow Unicode to work.

Barry

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

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


Python 3.7+ cannot print unicode characters when output is redirected to file - is this a bug?

2022-11-13 Thread Jessica Smith
Consider the following code ran in Powershell or cmd.exe:

$ python -c "print('└')"
└

$ python -c "print('└')" > test_file.txt
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2514' in
position 0: character maps to 

Is this a known limitation of Windows + Unicode? I understand that
using -x utf8 would fix this, or modifying various environment
variables. But is this expected for a standard Python installation on
Windows?

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


Re: ANN: pdfposter 0.8.1 - scale and tile PDF pages to print on multiple sheets

2022-11-04 Thread jkn
On Friday, November 4, 2022 at 6:21:55 PM UTC, Hartmut Goebel wrote:
> I'm pleased to announce pdftools.pdfposter 0.8.1, a tool to scale and 
> tile PDF images/pages to print on multiple pages. 
> 
> :Homepage:  https://pdfposter.readthedocs.io/ 
> :Author:Hartmut Goebel  
> :License:   GNU Public License v3 or later (GPL-3.0-or-later) 
> 
> :Quick Installation: 
> pip install -U pdftools.pdfposter 
> 
> :Tarballs:  https://pypi.org/project/pdftools.pdfposter/#files 
> 
> 
> What is pdfposter? 
> ---- 
> 
> Scale and tile PDF images/pages to print on multiple pages. 
> 
> ``Pdfposter`` can be used to create a large poster by building it from 
> multiple pages and/or printing it on large media. It expects as input a 
> PDF file, normally printing on a single page. The output is again a 
> PDF file, maybe containing multiple pages together building the 
> poster. 
> The input page will be scaled to obtain the desired size. 
> 
> This is much like ``poster`` does for Postscript files, but working 
> with PDF. Since sometimes poster does not like your files converted 
> from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``. 
> 
> For more information please refer to the manpage or visit 
> the `project homepage <https://pdfposter.readthedocs.io/>`_. 
> 
> 
> What's new in version 0.8.1 
> - 
> 
> * This is a bug-fix release for release 0.8. 
> 
> What's new in version 0.8 
> - 
> 
> * Be less strict when reading PDF files. 
> 
> * Enhance some help messages. 
> 
> * Drop support for Python 2 and Python <= 3.5. Minimum supported 
> versions are 
>   now 3.6 to 3.10. 
> 
> * Internal changes: 
> 
>   - Update required version of `PyPDF` to 2.1.1. 
>   - Enhance code quality. 
> 
> -- 
> Regards 
> Hartmut Goebel 
> 
> | Hartmut Goebel | h.go...@crazy-compilers.com | 
> | www.crazy-compilers.com | compilers which you thought are impossible |

Thanks for this - yes, I remember poster for n-up Postscript files...

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


ANN: pdfposter 0.8.1 - scale and tile PDF pages to print on multiple sheets

2022-11-04 Thread Hartmut Goebel

I'm pleased to announce pdftools.pdfposter 0.8.1, a tool to scale and
tile PDF images/pages to print on multiple pages.

:Homepage:  https://pdfposter.readthedocs.io/
:Author:    Hartmut Goebel 
:License:   GNU Public License v3 or later (GPL-3.0-or-later)

:Quick Installation:
    pip install -U pdftools.pdfposter

:Tarballs:  https://pypi.org/project/pdftools.pdfposter/#files


What is pdfposter?


Scale and tile PDF images/pages to print on multiple pages.

``Pdfposter`` can be used to create a large poster by building it from
multiple pages and/or printing it on large media. It expects as input a
PDF file, normally printing on a single page. The output is again a
PDF file, maybe containing multiple pages together building the
poster.
The input page will be scaled to obtain the desired size.

This is much like ``poster`` does for Postscript files, but working
with PDF. Since sometimes poster does not like your files converted
from PDF. :-) Indeed ``pdfposter`` was inspired by ``poster``.

For more information please refer to the manpage or visit
the `project homepage <https://pdfposter.readthedocs.io/>`_.


What's new in version 0.8.1
-

* This is a bug-fix release for release 0.8.

What's new in version 0.8
-

* Be less strict when reading PDF files.

* Enhance some help messages.

* Drop support for Python 2 and Python <= 3.5. Minimum supported 
versions are

  now 3.6 to 3.10.

* Internal changes:

  - Update required version of `PyPDF` to 2.1.1.
  - Enhance code quality.

--
Regards
Hartmut Goebel

| Hartmut Goebel  | h.goe...@crazy-compilers.com   |
| www.crazy-compilers.com | compilers which you thought are impossible |

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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Dan Stromberg
On Thu, Jun 9, 2022 at 1:52 PM Michael F. Stemper 
wrote:

> On 09/06/2022 12.52, Chris Angelico wrote:
> > On Fri, 10 Jun 2022 at 03:44, Dave  wrote:
>
> >> Before I write my own I wondering if anyone knows of a function that
> will print a nicely formatted dictionary?
> >>
> >> By nicely formatted I mean not all on one line!
> >>
> >
> > https://docs.python.org/3/library/pprint.html
> >
> > from pprint import pprint
> > pprint(thing)
>
>   >>> from pprint import pprint
>   >>> d = {'two':2, 'three':5}
>   >>> pprint(d)
>   {'three': 5, 'two': 2}
>   >>>
>
> This is all on one line. That might be acceptable to the OP, but it
> doesn't actually match what he said.
>

For small outputs, pprint uses a single line.  For larger outputs, it
inserts newlines. It's intended to be human-readable more than
machine-readable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Grant Edwards
On 2022-06-09, Dennis Lee Bieber  wrote:

> However, the Gmane list<>NNTP gateway server DOES make the tutor
> list available to news readers (unfortunately, the comp.lang.python
> <> list <> Gmane has been read-only since last fall (unless things
> have changed recently) so I'm stuck with the spammy general
> comp.lang.python news group.

Here's how I fixed that problem:

  https://github.com/GrantEdwards/hybrid-inews

I read this "group" using slrn pointed at gmane.comp.python.general,
on the NNTP server news.gmain.io. When I post to this group from slrn,
it gets e-mailed to the regular mailing list address. Other gmane
"groups" get posts sent via NNTP. slrn is configured to post all
articles via /usr/local/bin/inews (which is the python "inews"
work-alike program above) when connected to news.gmane.io.

How/why people follow mailing lists via actual e-mail is beyond my
ken... 

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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Cameron Simpson
On 09Jun2022 21:35, Dave  wrote:
>I quite like the format that JSON gives - thanks a lot!

Note that JSON output is JavaScript notation, not Python. The `pprint` 
module (which has `pprint` and `pformat` functions) outputs Python 
notation.

If you're just writing for human eyes, JSON is fine, though you will 
want to keep in mind that JSON spells `None` as `null`.

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Michael F. Stemper

On 09/06/2022 12.52, Chris Angelico wrote:

On Fri, 10 Jun 2022 at 03:44, Dave  wrote:



Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!



https://docs.python.org/3/library/pprint.html

from pprint import pprint
pprint(thing)


 >>> from pprint import pprint
 >>> d = {'two':2, 'three':5}
 >>> pprint(d)
 {'three': 5, 'two': 2}
 >>>

This is all on one line. That might be acceptable to the OP, but it
doesn't actually match what he said.

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Friedrich Rentsch
If you want tables layed out in a framing grid, you might want to take a 
look at this:


https://bitbucket.org/astanin/python-tabulate/pull-requests/31/allow-specifying-float-formats-per-column/diff

Frederic



On 6/9/22 12:43, Dave wrote:

Hi,

Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!

Cheers
Dave



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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Dave
Hi,

I quite like the format that JSON gives - thanks a lot!

Cheers
Dave

> On 9 Jun 2022, at 20:02, Stefan Ram  wrote:
> 
>  Since nicety is in the eyes of the beholder, I would not
>  hesitate to write a custom function in this case. Python
>  has the standard modules "pprint" and "json".
> 
>  main.py
> 
> import json
> d ={ 1:2, 'alpha': 'beta' }
> print( json.dumps( d, indent=4 ))
> 
>  output
> 
> {
>"1": 2,
>"alpha": "beta"
> }
> 

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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Mats Wichmann
On 6/9/22 11:52, Chris Angelico wrote:
> On Fri, 10 Jun 2022 at 03:44, Dave  wrote:
>>
>> Hi,
>>
>> Before I write my own I wondering if anyone knows of a function that will 
>> print a nicely formatted dictionary?
>>
>> By nicely formatted I mean not all on one line!
>>
> 
> https://docs.python.org/3/library/pprint.html
> 
> from pprint import pprint
> pprint(thing)
> 
> ChrisA


I might add the note that there was a recent thread on the Discuss board
about options for styling the pprint output (okay, it was me that
started that one...) - you can choose indent and compact (compact is the
not-all-on-one-line flag) but there might be some other choices missing.
haven't gotten around to following up on that...

https://discuss.python.org/t/pprint-styling-options/15947
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Avi Gross via Python-list
Dave,

Despite your other programming knowledge, I suspect you think this is the forum 
where people come to be tutored. Try here:

https://mail.python.org/mailman/listinfo/tutor

Yes, there are plenty of pretty printers available and you can build your own 
function fairly easily. A module like pprint may have what you want in 
pprint.pprint()  but you can write a function for yourself that takes a  
dictionary and loops through items and prints them one per line and, if you 
feel like it, also prints how many items there are and your own custom touches 
such as doing them alphabetically.
Consider using a search engine before posting. Throw in a few words like 
"python pretty print dictionary function" and refine that if it does not get 
you immediate results. It is free and easy and does not waste time for so many 
others who already know or don't care.
And consider reading a few books perhaps designed to teach python to people 
with some programming experience or taking a course on something like COURSERA 
as a part of your learning process and not depending on volunteers so much. 
Much of what you are asking is covered in fairly beginner and intermediate such 
books/courses.

I think I am now going to ignore messages from you for a while. Signal to noise 
ratio ...


-Original Message-
From: Dave 
To: python-list@python.org
Sent: Thu, Jun 9, 2022 6:43 am
Subject: Function to Print a nicely formatted Dictionary or List?

Hi,

Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!

Cheers
Dave

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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Chris Angelico
On Fri, 10 Jun 2022 at 03:44, Dave  wrote:
>
> Hi,
>
> Before I write my own I wondering if anyone knows of a function that will 
> print a nicely formatted dictionary?
>
> By nicely formatted I mean not all on one line!
>

https://docs.python.org/3/library/pprint.html

from pprint import pprint
pprint(thing)

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


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread MRAB

On 2022-06-09 11:43, Dave wrote:

Hi,

Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!


It's called "pretty-printing". Have a look at the 'pprint' module.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Larry Martell
On Thu, Jun 9, 2022 at 11:44 AM Dave  wrote:
>
> Hi,
>
> Before I write my own I wondering if anyone knows of a function that will 
> print a nicely formatted dictionary?
>
> By nicely formatted I mean not all on one line!

>>> import json
>>> d = {'John': 'Cleese', 'Eric': "Idle", 'Micheal': 'Palin'}
>>> print(json.dumps(d, indent=4))
{
"John": "Cleese",
"Eric": "Idle",
"Micheal": "Palin"
}
-- 
https://mail.python.org/mailman/listinfo/python-list


Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Dave
Hi,

Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!

Cheers
Dave

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


Re: how to distinguish return from print()

2022-05-25 Thread Meredith Montgomery
r...@zedat.fu-berlin.de (Stefan Ram) writes:

> Meredith Montgomery  writes:
> ...
>>def f(x):
>>return x + 1
> ...
>>>>> print("hello")
>
>   To me, what would make more sense would be:
>
>   Teacher:
>
> |>>> def r():
> |... return 7
> |...
> |>>> def p():
> |... print( 7 )
> |...
> |>>> r()
> |7
> |>>> p()
> |7
>
>   Pupil:
>
>   That was a very instructive example, teacher. Thank you!
>   But could you also show us some context where the calls 
>   to p and r show some difference?
>
>   Teacher:
>   
> |>>> print( r() )
> |7
> |>>> print( p() )
> |7
> |None
>
> |>>> x = r()
> |>>> x = p()
> |7
>
>   Pupil:
>
>   Now I'm confused. What's "None"?
>
>   Teacher:
>
>   ...

I did do this too.  I think that was helpful.  I told them --- a print
doesn't let you easily ``capture'' a value calculated in a procedure.
Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: F-string usage in a print()

2022-05-24 Thread Cameron Simpson
On 25May2022 00:13, Kevin M. Wilson  wrote:
>Cameron, I have a misunderstanding here, the 'f-string' is used when 
>the str() is not...isn't it!

No, f-strings (format strings) are just a convenient way to embed values 
in a string. The result is a string.

In days of yore the common formatting method was the % operator like C's 
printf() format. You could do stuff like this:

print("%s: length is %d items" % (thing, len(thing)))

which would print something like:

Thing5: length is 12 items

Ignore the print() itself, that's just how you might use this: format a 
string with 2 values, then print it out for a person to read.

You can do various things with %-formatting, but it is pretty limited 
and a bit prone to pairing things up incorrectly (human error making the 
"(thing, len(thing,len(thing)))" tuple) because those values are 
separates from the string itself.

The funky new thing is format strings, where you can write:

print(f"{thing}: length is {len(thing)} items")

Again ignore the print(), we're really just interested in the 
expression:

f"{thing}: length is {len(thing)} items"

which does the same thing as the %-format earlier, but more readably and 
conveniently.

I suspect you think they have another purpose. Whereas I suspect you're 
actaully trying to do something inappropriate for a number. If you've 
come here from another language such as PHP you might expect to go:

print(some_number + some_string)

In Python you need compatible types - so many accidents come from mixing 
stuff up.

You may know that print()'s operation is to take each expression you 
give it and call str() on that value, then print that string.

f-strings have a similar operation: each {expression} inside one is 
converted to a string for embedding in the larger format string; that is 
also done with str() unless you've added something special in the {} 
part.

Aside from output you should not expect to be adding strings and 
numbers; - it isn't normally a sensible thing to do. And when printing 
things, you need text (strings). But print() takes can of that by 
passing every value to str(), which returns a string (in a manner 
appropriate to the type of value). You only want f-strings or manual 
joining up if you don't want the default separator between items (a 
space).

Can you elaborate on _why_ you wanted an f-string? What were you doing 
at the time?

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: F-string usage in a print()

2022-05-24 Thread Cameron Simpson
On 24May2022 21:14, Kevin M. Wilson  wrote:
>future_value = 0
>for i in range(years):
># for i in range(months):
>   future_value += monthly_investment
>   future_value = round(future_value, 2)
>   # monthly_interest_amount = future_value * monthly_interest_rate
>   # future_value += monthly_interest_amount
>   # display the result
>   print(f"Year = ", years + f"Future value = \n", future_value)
>
>When joining a string with a number, use an f-string otherwise, code a
>str() because a implicit convert of an int to str causes a
>TypeError!Well...WTF! Am I not using the f-string function
>correctly...in the above line of code???

The short answer is that you cannot add (the "+" operator) a string to 
an integer in Python because one is a numeric value and one is a text 
value. You would need to convert the int to a str first if you really 
wanted to.  But in your code above, you don't need to.

Let's pick apart that print():

print(
f"Year = ",
years + f"Future value = \n",
future_value
)

Like any function, print()'s arguments are separate by commas. So you've 
got 3 expressions there. The problematic expression looks like this 
one:

years + f"Future value = \n"

You didn't supply a complete runnable example so we don't see "years" 
get initialised.  However, I assume it is an int because range() only 
accepts ints. You can't add an int to a str.

Now, print() converts all its arguments to strings, so there's no need 
for f-strings anywhere in this. I'd go:

    print("Year =", years, "Future value =", future_value)

myself. If you really want that newline, maybe:

print("Year =", years, "Future value =")
print(future_value)

Format strings are for embedding values inside strings, which you don't 
need to do in your code as written. And whether you wrote:

years + f"Future value = \n"

or:

years + "Future value = \n"

(because that string has no embedded values) it is still wrong because 
years is an int and the string is still a str.

You _could_ use an f-string to compute the whole print line in one go:

print(f"Year = {years} Future value = \n{future_value}")

but I can't see the point, personally. I've code from people who prefer 
that form though.

BTW, it helps people to help you if you supply a complete example. Your 
example code did not initialise years or monthly_investment, and so will 
not run for someone else. It also helps to winnow it down to the 
smallest example you can which still shows the problem. FOr yoru example 
you could have reduced things to this, perhaps:

years = 9
years + f"Future value = \n"

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: F-string usage in a print()

2022-05-24 Thread Mats Wichmann
On 5/24/22 15:14, Kevin M. Wilson via Python-list wrote:
> future_value = 0
> for i in range(years):
> # for i in range(months):
>future_value += monthly_investment
>future_value = round(future_value, 2)
># monthly_interest_amount = future_value * monthly_interest_rate
># future_value += monthly_interest_amount
># display the result
>print(f"Year = ", years + f"Future value = \n", future_value)When joining 
> a string with a number, use an f-string otherwise, code a str() because a 
> implicit convert of an int to str causes a TypeError!Well...WTF! Am I not 
> using the f-string function correctly...in the above line of code???


As noted elsewhere, your f-strings by themselves are fine, it isn't
complaining about those, though they're kind of silly as they don't do
any formatting that justifies entering them as f-strings. It's
complaining about this piece:

years + f"Future value = \n"

which is the second of the three comma-separated argument to print().
That's the int + string the error is grumping about.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: F-string usage in a print()

2022-05-24 Thread Paul Bryan
Try something like:

print(f"Year = {years}, Future value = {future_value}")

On Tue, 2022-05-24 at 21:14 +, Kevin M. Wilson via Python-list
wrote:
> future_value = 0
> for i in range(years):
> # for i in range(months):
>    future_value += monthly_investment
>    future_value = round(future_value, 2)
>    # monthly_interest_amount = future_value * monthly_interest_rate
>    # future_value += monthly_interest_amount
>    # display the result
>    print(f"Year = ", years + f"Future value = \n", future_value)When
> joining a string with a number, use an f-string otherwise, code a
> str() because a implicit convert of an int to str causes a
> TypeError!Well...WTF! Am I not using the f-string function
> correctly...in the above line of code???
> Caddy Man
> 
> Good sense makes one slow to anger, and it is his glory tooverlook an
> offense.
> 
> Proverbs 19:11
> 

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


Re: F-string usage in a print()

2022-05-24 Thread MRAB

On 2022-05-24 22:14, Kevin M. Wilson via Python-list wrote:

future_value = 0
for i in range(years):
# for i in range(months):
future_value += monthly_investment
future_value = round(future_value, 2)
# monthly_interest_amount = future_value * monthly_interest_rate
# future_value += monthly_interest_amount
# display the result
print(f"Year = ", years + f"Future value = \n", future_value)When joining a 
string with a number, use an f-string otherwise, code a str() because a implicit convert of an int 
to str causes a TypeError!Well...WTF! Am I not using the f-string function correctly...in the above 
line of code???


There's no implicit conversion. An f-string always gives you a string.

'years' is an int, f"Future value = \n" is a str, and you can't add an 
int and a str.


Maybe you meant this:

print(f"Year = {i}, Future value = {future_value}")

or this:

print(f"Year = {i + 1}, Future value = {future_value}")

These are equivalent to:

print("Year = {}, Future value = {}".format(i, future_value))

and:

print("Year = {}, Future value = {}".format(i + 1, future_value))
--
https://mail.python.org/mailman/listinfo/python-list


F-string usage in a print()

2022-05-24 Thread Kevin M. Wilson via Python-list
future_value = 0
for i in range(years):
# for i in range(months):
   future_value += monthly_investment
   future_value = round(future_value, 2)
   # monthly_interest_amount = future_value * monthly_interest_rate
   # future_value += monthly_interest_amount
   # display the result
   print(f"Year = ", years + f"Future value = \n", future_value)When joining a 
string with a number, use an f-string otherwise, code a str() because a 
implicit convert of an int to str causes a TypeError!Well...WTF! Am I not using 
the f-string function correctly...in the above line of code???
Caddy Man

Good sense makes one slow to anger, and it is his glory tooverlook an offense.

Proverbs 19:11

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


Re: how to distinguish return from print()

2022-05-22 Thread Chris Angelico
On Mon, 23 May 2022 at 09:23, Stefan Ram  wrote:
>   You are making it extra hard by wording the question in this
>   way. "What's the difference between the moon and liberty?". Uh ...
>
>   It's much easier to explain the moon and liberty separately.

"You can't tell the difference between a lump on the head and
margarine. The leadership of the Conservative Party is yours for the
asking!"
-- Grytpype Thynne, "The Last Goon Show of All"

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


how to distinguish return from print()

2022-05-22 Thread Meredith Montgomery
Students seeing a programming language for the first time and using
Python's REPL for the first time have asked me what is the difference
between a return statement and a print() call.  They got a point.

--8<---cut here---start->8---
def f(x):
return x + 1

>>> f(1)
2

>>> print("hello")
hello
--8<---cut here---end--->8---

There's no visual difference.

(*) My answer

The way I know how to answer the difference there is to explain how a
typical computer system works, which is a more or less long answer.  A
return statement is usually just another CPU instruction, while /print/
is a procedure that must eventually run a CPU instruction that
interrupts the CPU, passes control to the operating system which, in
turn, talks to the i/o devices in question (the video, for example) to
get the job finally done.  (We may expect a print() call, therefore, to
be usually much slower than a return statement.)

I also explain that if, say, math.sin(x) is going to print a message to
the screen...

>>> sin(pi/2)
calculating your sine... hang on...
1.0

... I might as well not use it because this will get mixed with my own
print() statements and I'll be surprised about who added that
calculating-your-sine message.  So adding print() statements to
procedures is, in practice, rare.  (To them it's the most typical
operation because they never do any serious programming and they learn
their first steps out on the Internet.  In my course, print() is only
allowed after at 10th homework, after 10 weeks.)

I also explain that if f(x) prints its answer to the screen instead of
returning it, it will be harder to capture the answer in a variable.
For example,

>>> def f(x):
...   print(x + 1)
... 
>>> f(1)
2
>>> y = f(1)
2
>>> y
>>> 
>>> y == None
True

I take this opportunity to remark that Python seems to always returns
something, even if it's the ``special'' value None.

(*) The REPL

I also explain that the REPL is just another program.  Its purpose
happens to be to [r]ead, [e]val, [p]rint and [l]oop, which is why we get
to see return values printed to the screen.

(*) My insatisfaction

I wish I had simpler answers.  Explaining about operating systems, the
CPU, system calls...  I wish there was an easier way to clarify such
things.  You guys might have ideas.

I'm thinking about showing them the code for the simplest toy-REPL so
that we can perhaps demystify the REPL.  I think they see the REPL as
part of the programming language, so I think it might help to figure out
that nothing happens unless code is written to make it happen.  If
something gets displayed on the screen, there is definitely some i/o
going on and print() is the one initiating that i/o, while return is
just another ``arithmetic'' operation such as addition.

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


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-12-21 Thread boB Stepp

On 21/12/22 12:14PM, Python wrote:

On 30/11/2021 12.31, Cameron Simpson wrote:

On 30Nov2021 10:59, DL Neil  wrote:

...


I've nominated Kitty as
Fedora's default terminal. We'll see how it goes with work-loads beyond
raising the flag...


I'd like to hear how that goes down the track. If I find myself on a
Linux desktop again a good terminal emulator would be very welcome.



(given that @A-R has brought this thread back-to-life)


I have been surprised/shocked/horrified/annoyed to discover that the
(Linux) clipboard is not accessible from "Kitty".


Huh?  I use kitty and copy to and from the clipboard all the time.
1) ctrl+shift+c Copy to clipboard
2) ctrl+shift+v Paste from the clipboard
3) Using mouse to select text automatically copies it to the primary 
clipboard.
4) Middle-click of mouse to paste from the primary clipboard.


--
Wishing you only the best,
boB Stepp

Speeches are like steer horns -- a point here, a point there and a lot of bull
in between.
-- E. Anderson
--
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-12-21 Thread dn via Python-list
On 30/11/2021 12.31, Cameron Simpson wrote:
> On 30Nov2021 10:59, DL Neil  wrote:
...

>> I've nominated Kitty as
>> Fedora's default terminal. We'll see how it goes with work-loads beyond
>> raising the flag...
> 
> I'd like to hear how that goes down the track. If I find myself on a 
> Linux desktop again a good terminal emulator would be very welcome.


(given that @A-R has brought this thread back-to-life)


I have been surprised/shocked/horrified/annoyed to discover that the
(Linux) clipboard is not accessible from "Kitty".

Go on, I dare you to remind me that good-old 'dumb-terminals' didn't
have 'clipboards'...
(neither did they have to cope with Unicode, emoticons, or national flags!)


Accordingly, having developed an idea in the REPL (running within
Kitty), could not later copy-paste into a Python module or tutorial text
(nor, next time the situation arises, to be able to illustrate an answer
to a question posted 'here').

Am somewhat in disbelief, and my fingers feel slightly singed. Grump!
(or its seasonal variation: "Grinch")


Am open to further non-terminal, terminal suggestions...

(during my post-op recovery period, am hoping to experiment with another
Linux distro (and Window Manager), which may alter the playing-field...)


Meantime, casting-off the terminal-Grinch, compliments of the season to
you...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyCharm settings - per: print('\N{flag: Mauritius}') not supported in py3.9

2021-12-21 Thread Abdur-Rahmaan Janhangeer
Yet another unicode issue XD

Kind Regards,

Abdur-Rahmaan Janhangeer
about  | blog

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


PyCharm settings - per: print('\N{flag: Mauritius}') not supported in py3.9

2021-12-01 Thread dn via Python-list
On 29/11/2021 10.08, dn via Python-list wrote:
> On 29/11/2021 02.18, Chris Angelico wrote:
>> On Mon, Nov 29, 2021 at 12:10 AM Abdur-Rahmaan Janhangeer
>>  wrote:
>>
>> Flags are actually constructed from multiple codepoints. What you want
>> is to insert each codepoint separately. You can see them listed in the
>> second column of the table you linked to.
>>
> "\U0001F1F2\U0001F1FA"
>> '🇲🇺'
>>
>> To do this with names, you need the names of those two codepoints:
>>
>> '\U0001f1f2' REGIONAL INDICATOR SYMBOL LETTER M
>> '\U0001f1fa' REGIONAL INDICATOR SYMBOL LETTER U
>>
> "\N{REGIONAL INDICATOR SYMBOL LETTER M}\N{REGIONAL INDICATOR SYMBOL 
> LETTER U}"
>> '🇲🇺'
> 
> 
> Don't use Emojis that often. The colored circles (U+1F534 etc) display
> in full, glorious, technicolor.
> 
> However, when trying the above, with our local flag in (Fedora Linux,
> Gnome) Terminal or PyCharm's Run terminal; the two letters "N" and "Z"
> are shown with dotted-outlines. Similarly, the Mauritius' flag is shown
> as "M" and "U".


Investing a bit of time/waiting for a meeting, found a number of Issues
lodged with JetBrains relating to emoji-support/display:-

Among the most recent advice is to add a "Fallback font" which is known
to include (colored!) emojis.

Thus (this includes personal settings):

File > Settings > Editor > Font
Font = IBM Plex Mono
drop down > Typography Settings
Fallback font = Twemoji

After which, patriotic-pride may be expressed!


However, the Issues (that is to say, those which I had time/energy to
read) indicate that there may still be differences between Linux, Mac,
Windows, and that 'franken-thing' which is Linux on top of Windows but
we don't label it "Linux" so that people still think it is "Windows".


Further wrinkles (drifting OT!):

Fedora 33's Gnome Font Viewer shows:
Emoji One
Noto Color Emoji
Twemoji

- don't ask me the why/when/where of Twemoji
- the other two were added via dnf (yum) today

Neither shows in PyCharm's drop-down list of choices - even after
stop/start (which doesn't appear strictly necessary, per above, but...).


Performed:

fc-cache -fv

and the listing verifies their presence, and ensures all is compos-mentis.

In Writer, all three appear (without prefix). Still only the one appears
in PyCharm. (sigh...)


PS thanks to the OP! Certainly opened my eyes and befuddled (what's left
of) my brain. Was planning to use the aforementioned 'colored circles'
in a PUG coding exercise, but have now amended to require coders to
'wave the flag'. Hopefully they will find such slightly more amusing...
Salute!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-29 Thread Cameron Simpson
On 30Nov2021 10:59, DL Neil  wrote:
>Fedora names it as rxvt-unicode.
>Installed v9.26
>Text is too small for these old eyes.

Fair enough. There are resources, but not worth it unless you really 
want the app.

>No menu bar and no context menus.

Um, yes. The (hardware, serial) terminals we had a uni didn't have such 
niceties, and therefore we should not want them.

>Unable to copy-paste (the flag codes) into that window.
>Removed.

Fair enough.

>I choose not to even try to remember the difficulties of working with
>small screens over-laying one another and 'getting lost' in the pile!

Aye. Tiling is very nice.

>I'm a lazy toad. Thus the idea that the IDE will allow me to 'press a
>(single) button' to repeat the last-run test/execute the code, without
>me having to commit a Save and to jump between panels/windows/screens,
>is seductive.

I once had a vi macro bound to ";" for "^W:!!^M", which autosaves the 
current file and reran the last shell command. Used it a lot in the 
single-terminal days. I unbound it several years ago though.

>I've nominated Kitty as
>Fedora's default terminal. We'll see how it goes with work-loads beyond
>raising the flag...

I'd like to hear how that goes down the track. If I find myself on a 
Linux desktop again a good terminal emulator would be very welcome.

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-29 Thread dn via Python-list
On 30/11/2021 10.19, Cameron Simpson wrote:
> On 29Nov2021 22:25, DL Neil  wrote:
 Probably a font issue. Not many fonts support the flags.
>>>
>>> Agree about the font support. Some terminal emulators make an effort to
>>> have fallback fonts for when your preferred font lacks a glyph. IIRC
>>> urxvt is such a terminal on Linux.
>>
>> Not sure about this. Most other applications on this PC will display the
>> two countries' flags, as desired, eg Writer, web-browser, even xed
>> (basic text editor).
> 
> Seem Stefan Ram's advice, which points out that you can tell if this is 
> a font problem (no flag glyph) or a combining problem (2 glyphs 
> presented instead of one). I had not considered that.

@Stefan's advice preceded by report that two glyphs were printed (not
one): "the two letters "N" and "Z" are shown with dotted-outlines"
(I think, the UTF-16 decoding)


>> rxvt: won't compile, gave-up fighting unfamiliar requirements
> 
> See if there's a package for urxvt, which was the "unicode" flavour of 
> rxvt (long ago - rxvt if probably supposed to be unicode capable these 
> days, surely).

Fedora names it as rxvt-unicode.
Installed v9.26
Text is too small for these old eyes.
No menu bar and no context menus.
Unable to copy-paste (the flag codes) into that window.
Removed.


>> Kitty: works!
> 
> Yay!
> 
>> Kitty is not something I've come-across before. Its write-up says
>> «
>> Kitty is a free, open-source, and fast, feature-rich, GPU accelerated
>> terminal emulator for Linux, that supports all present-day terminal
>> features, such as Unicode, true color, text formatting, bold/italic
>> fonts, tiling of multiple windows and tabs, etc.
> 
> A tiling terminal emulator can be a great thing. I'm on a Mac with 
> iTerm, which:
> - has tabs
> - has panes (split the view into multiple panels, each running a 
>   terminal)
> 
> My personal dev desktop tends to use a full screen iTerm split 
> vertically into 2 panes: an editor on the left (vim, itself split 
> vertically into 2 vim windows) and a shell on the right; sometimes 
> several shells (right hand pane further split horizontally).
> 
> Then, since I tend to keep per-branch checkouts around, tabs for the 
> things I'm working on, each configured as above. Then I just switch tabs 
> for the different areas.


Yes, a good way to work. Neatly explained.

I choose not to even try to remember the difficulties of working with
small screens over-laying one another and 'getting lost' in the pile!

My desktop/dev.svr features two screens: one in 'portrait mode' and the
other 'landscape'. The former is very good for code-listings. The latter
for execution-display, pytest reports, etc. As you describe, each can be
sub-divided when needs-arise. A neat feature is that "Tool Windows" can
be tucked-away, and only 'pulled-out' when required, eg am not looking
at Sourcery's assessments right now (unless it highlights the commission
of some 'crime' as I type) but will check prior to (or as part of) git
commit. The Tool Window's name/label in the 'dock' also forms a reminder
that I shouldn't (totally) neglect my responsibilities!

These are managed within the IDE - sadly, PyCharm's terminal/console
fails the 'flag test', as reported yesterday. (am not sure if one might
be able to select which terminal emulator to use ...)

I'm a lazy toad. Thus the idea that the IDE will allow me to 'press a
(single) button' to repeat the last-run test/execute the code, without
me having to commit a Save and to jump between panels/windows/screens,
is seductive.

Don't tell my trainees! Every course sees three or four who 'cry for
help' because making some change in their choice of editor/IDE does not
result in similar within the web-browser. Did you forget to save the
source, Luke? That's not to say there won't be considerably more who
manage to diagnose the problem without admitting such to 'the outside
world'!


There are times when there is no need to (wait quite a while to) boot-up
a whole IDE, eg running a utility program. I've nominated Kitty as
Fedora's default terminal. We'll see how it goes with work-loads beyond
raising the flag...
Salute!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-29 Thread Cameron Simpson
On 29Nov2021 22:25, DL Neil  wrote:
>>> Probably a font issue. Not many fonts support the flags.
>>
>> Agree about the font support. Some terminal emulators make an effort to
>> have fallback fonts for when your preferred font lacks a glyph. IIRC
>> urxvt is such a terminal on Linux.
>
>Not sure about this. Most other applications on this PC will display the
>two countries' flags, as desired, eg Writer, web-browser, even xed
>(basic text editor).

Seem Stefan Ram's advice, which points out that you can tell if this is 
a font problem (no flag glyph) or a combining problem (2 glyphs 
presented instead of one). I had not considered that.

>rxvt: won't compile, gave-up fighting unfamiliar requirements

See if there's a package for urxvt, which was the "unicode" flavour of 
rxvt (long ago - rxvt if probably supposed to be unicode capable these 
days, surely).

>Kitty: works!

Yay!

>Kitty is not something I've come-across before. Its write-up says
>«
>Kitty is a free, open-source, and fast, feature-rich, GPU accelerated
>terminal emulator for Linux, that supports all present-day terminal
>features, such as Unicode, true color, text formatting, bold/italic
>fonts, tiling of multiple windows and tabs, etc.

A tiling terminal emulator can be a great thing. I'm on a Mac with 
iTerm, which:
- has tabs
- has panes (split the view into multiple panels, each running a 
  terminal)

My personal dev desktop tends to use a full screen iTerm split 
vertically into 2 panes: an editor on the left (vim, itself split 
vertically into 2 vim windows) and a shell on the right; sometimes 
several shells (right hand pane further split horizontally).

Then, since I tend to keep per-branch checkouts around, tabs for the 
things I'm working on, each configured as above. Then I just switch tabs 
for the different areas.

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-29 Thread dn via Python-list
On 29/11/2021 12.06, Cameron Simpson wrote:
> On 29Nov2021 09:19, Chris Angelico  wrote:
>> On Mon, Nov 29, 2021 at 8:10 AM dn via Python-list
>>  wrote:
>>> However, when trying the above, with our local flag in (Fedora Linux,
>>> Gnome) Terminal or PyCharm's Run terminal; the two letters "N" and "Z"
>>> are shown with dotted-outlines. Similarly, the Mauritius' flag is shown
>>> as "M" and "U".
>>>
>>> Whereas here in email (Thunderbird) or in a web-browser, the flags
>>> appear, as desired.
>>>
>>> Is this a terminal short-coming (locale charmap -> UTF-8 - which brings
>>> to mind the old UCS-4 questions), a font issue, or what (to fix)?
>>
>> Probably a font issue. Not many fonts support the flags.
> 
> Agree about the font support. Some terminal emulators make an effort to 
> have fallback fonts for when your preferred font lacks a glyph. IIRC 
> urxvt is such a terminal on Linux.


Not sure about this. Most other applications on this PC will display the
two countries' flags, as desired, eg Writer, web-browser, even xed
(basic text editor).

Accordingly, took @Cameron's advice. Leading to:

Gnome Terminal: won't display "\U0001F1F3\U0001F1FF" (etc)
Terminator: won't display
Tabby: doesn't seem to load from (rpm) repo
RoxTerm: no choice of fonts, won't display
rxvt: won't compile, gave-up fighting unfamiliar requirements
Terminology: offers choice of fonts, but still fails

Kitty: works!


Kitty is not something I've come-across before. Its write-up says
«
Kitty is a free, open-source, and fast, feature-rich, GPU accelerated
terminal emulator for Linux, that supports all present-day terminal
features, such as Unicode, true color, text formatting, bold/italic
fonts, tiling of multiple windows and tabs, etc.

Kitty is written in C and Python programming languages, and it is one of
few terminal emulators with GPU support
»


Yes, the one that 'works', is using the same fonts as (say) Writer, and
the original (Gnome) Terminal that fails.


Please don't take this as a scientific survey. I didn't spend any time
investigating - either the s/w worked or it didn't! However, a terminal
is doing a simple job (at the user-level), so there's not much to them
in terms of knobs to twiddle or levers to pull.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Cameron Simpson
On 29Nov2021 09:19, Chris Angelico  wrote:
>On Mon, Nov 29, 2021 at 8:10 AM dn via Python-list
> wrote:
>> However, when trying the above, with our local flag in (Fedora Linux,
>> Gnome) Terminal or PyCharm's Run terminal; the two letters "N" and "Z"
>> are shown with dotted-outlines. Similarly, the Mauritius' flag is shown
>> as "M" and "U".
>>
>> Whereas here in email (Thunderbird) or in a web-browser, the flags
>> appear, as desired.
>>
>> Is this a terminal short-coming (locale charmap -> UTF-8 - which brings
>> to mind the old UCS-4 questions), a font issue, or what (to fix)?
>
>Probably a font issue. Not many fonts support the flags.

Agree about the font support. Some terminal emulators make an effort to 
have fallback fonts for when your preferred font lacks a glyph. IIRC 
urxvt is such a terminal on Linux.

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Chris Angelico
On Mon, Nov 29, 2021 at 8:10 AM dn via Python-list
 wrote:
> However, when trying the above, with our local flag in (Fedora Linux,
> Gnome) Terminal or PyCharm's Run terminal; the two letters "N" and "Z"
> are shown with dotted-outlines. Similarly, the Mauritius' flag is shown
> as "M" and "U".
>
> Whereas here in email (Thunderbird) or in a web-browser, the flags
> appear, as desired.
>
> Is this a terminal short-coming (locale charmap -> UTF-8 - which brings
> to mind the old UCS-4 questions), a font issue, or what (to fix)?

Probably a font issue. Not many fonts support the flags.

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


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread dn via Python-list
On 29/11/2021 02.18, Chris Angelico wrote:
> On Mon, Nov 29, 2021 at 12:10 AM Abdur-Rahmaan Janhangeer
>  wrote:
> 
> Flags are actually constructed from multiple codepoints. What you want
> is to insert each codepoint separately. You can see them listed in the
> second column of the table you linked to.
> 
 "\U0001F1F2\U0001F1FA"
> '🇲🇺'
> 
> To do this with names, you need the names of those two codepoints:
> 
> '\U0001f1f2' REGIONAL INDICATOR SYMBOL LETTER M
> '\U0001f1fa' REGIONAL INDICATOR SYMBOL LETTER U
> 
 "\N{REGIONAL INDICATOR SYMBOL LETTER M}\N{REGIONAL INDICATOR SYMBOL LETTER 
 U}"
> '🇲🇺'


Don't use Emojis that often. The colored circles (U+1F534 etc) display
in full, glorious, technicolor.

However, when trying the above, with our local flag in (Fedora Linux,
Gnome) Terminal or PyCharm's Run terminal; the two letters "N" and "Z"
are shown with dotted-outlines. Similarly, the Mauritius' flag is shown
as "M" and "U".

Whereas here in email (Thunderbird) or in a web-browser, the flags
appear, as desired.

Is this a terminal short-coming (locale charmap -> UTF-8 - which brings
to mind the old UCS-4 questions), a font issue, or what (to fix)?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Abdur-Rahmaan Janhangeer
Greetings,


But why is it so?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Chris Angelico
On Mon, Nov 29, 2021 at 12:29 AM Abdur-Rahmaan Janhangeer
 wrote:
>
> Greetings,
>
> I get you but why do the short names work for some and not for
> others?
>

Which ones work? The ones that can be identified by a single
codepoint? Look at the specification for Python's \N escapes.

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


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Abdur-Rahmaan Janhangeer
Greetings,

I get you but why do the short names work for some and not for
others?

Kind Regards,

Abdur-Rahmaan Janhangeer
about  | blog

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


Re: print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Chris Angelico
On Mon, Nov 29, 2021 at 12:10 AM Abdur-Rahmaan Janhangeer
 wrote:
> I found the whole CLDR short name here:
> https://unicode.org/emoji/charts/full-emoji-list.html
>
> However when i do
>
> >>> print('\N{flag: Mauritius}')
>   File "", line 1
> print('\N{flag: Mauritius}')
>^
> i get
>
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
> position 0-18: unknown Unicode character name
>
> So is it that Python3.9 does not support it or what is the issue here?

Flags are actually constructed from multiple codepoints. What you want
is to insert each codepoint separately. You can see them listed in the
second column of the table you linked to.

>>> "\U0001F1F2\U0001F1FA"
'🇲🇺'

To do this with names, you need the names of those two codepoints:

'\U0001f1f2' REGIONAL INDICATOR SYMBOL LETTER M
'\U0001f1fa' REGIONAL INDICATOR SYMBOL LETTER U

>>> "\N{REGIONAL INDICATOR SYMBOL LETTER M}\N{REGIONAL INDICATOR SYMBOL LETTER 
>>> U}"
'🇲🇺'

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


print('\N{flag: Mauritius}') not supported in py3.9

2021-11-28 Thread Abdur-Rahmaan Janhangeer
Mike Driscoll printed this on Twitter

>>> print('\N{Sauropod}')
🦕

Using py3.9 i got the above.

I found the whole CLDR short name here:
https://unicode.org/emoji/charts/full-emoji-list.html

However when i do

>>> print('\N{flag: Mauritius}')
  File "", line 1
print('\N{flag: Mauritius}')
   ^
i get

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 0-18: unknown Unicode character name

So is it that Python3.9 does not support it or what is the issue here?
Thanks

Kind Regards,

Abdur-Rahmaan Janhangeer
about <https://compileralchemy.github.io/> | blog
<https://www.pythonkitchen.com>
github <https://github.com/Abdur-RahmaanJ>
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Beginner problem, please help. Building a simple menu + lists , cannot print list

2021-10-11 Thread Chris Angelico
On Tue, Oct 12, 2021 at 9:13 AM Felix Kjellström
 wrote:
>
> Hello! Please see the link to the code I have uploaded to my account at 
> replit.com
>
> https://replit.com/join/lftxpszwrv-felixkjellstrom

Unfortunately, it's not public. Are you able to put the code on GitHub
as a repository or gist, or in some other public hosting?
Alternatively, can you make it short enough to simply include here in
your post?

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


Beginner problem, please help. Building a simple menu + lists , cannot print list

2021-10-11 Thread Felix Kjellström
Hello! Please see the link to the code I have uploaded to my account at 
replit.com

https://replit.com/join/lftxpszwrv-felixkjellstrom

Problem:

When you select the menu option "Add buyer", you can enter three values. See 
code line 5, "def Add_buyer ():"

Then, you use the arrow keys to select the menu option "See list of buyers". 
When you do that the values you just entered should be printed. See code line 
23, "def See_list_of_buyers ():

The problem is that the list is DON'T gets printed.

Problem:

When you select the menu option "Add buyer", you can enter three values. See 
code line 5, "def Add_buyer ():"

Then, you use the arrow keys to select the menu option "See list of buyers". 
When you do that the values you just entered should be printed. See code line 
23, "def See_list_of_buyers ():

The problem is that the list is DON'T gets printed.

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


Re: Neither pdb or print() displays the bug [FIXED]

2021-06-08 Thread Rich Shepard

On Tue, 1 Jun 2021, Rich Shepard wrote:


I'm stuck with neither approach (pdb, print()) working. I moved the
database code to a separate module, datasource.py, and when I run the
activitytypes.py module (using pdb and having entered print() statements
at various places in both the datasource and activities modules all I get
is a small, empty window with the window title. The QSize() statement is
never reached.


Found and fixed the problem. Qt5 added support for PostgreSQL-12 in
Qt5-5.15.0. I upgraded both Qt5 and PyQt5 to 5.15.2 and now the tables
display the rows in the one column of the table.

Thanks for all the suggestions,

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


Re: Neither pdb or print() displays the bug

2021-06-06 Thread Rich Shepard

On Sun, 6 Jun 2021, Fabio Zadrozny wrote:


Hint: you should be able to use https://pypi.org/project/pytest-qt/ to
unit-test a PyQt application...


Fabio,

Thank you for confirming this. I hadn't remembered the name so your URL is
really helpful.

Regards,

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


Re: Neither pdb or print() displays the bug

2021-06-06 Thread Fabio Zadrozny
Em qua., 2 de jun. de 2021 às 09:34, Rich Shepard 
escreveu:

> On Wed, 2 Jun 2021, Peter Otten wrote:
>
> > Do you have unit tests? Those are an excellent tool to ensure that the
> > components of an application work as expected and that those components
> > have well-defined interfaces. Debugging a failing unittest is usually
> > easier than to debug a complex application. While I don't know if there
> is
> > a convenient way to test the GUI everything else should run reliably
> > *before* connecting it with the GUI.
>
> Peter,
>
> I believe there is a way to apply unit tests to PyQt and I'll certainly
> learn to take this testing-while-developing approach.
>

Hint: you should be able to use https://pypi.org/project/pytest-qt/ to
unit-test a PyQt application...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Neither pdb or print() displays the bug

2021-06-02 Thread Rich Shepard

On Wed, 2 Jun 2021, Peter Otten wrote:


Do you have unit tests? Those are an excellent tool to ensure that the
components of an application work as expected and that those components
have well-defined interfaces. Debugging a failing unittest is usually
easier than to debug a complex application. While I don't know if there is
a convenient way to test the GUI everything else should run reliably
*before* connecting it with the GUI.


Peter,

I believe there is a way to apply unit tests to PyQt and I'll certainly
learn to take this testing-while-developing approach.

Thanks,

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


Re: Neither pdb or print() displays the bug

2021-06-02 Thread Peter Otten

On 01/06/2021 23:32, Rich Shepard wrote:

On Tue, 1 Jun 2021, Ethan Furman wrote:


Well, you only had two logging statements in that code -- logging is like
print: if you want to see it, you have to call it:


Ethan,

Got it, thanks.

I believe


Do you have unit tests? Those are an excellent tool to ensure that the 
components of an application work as expected and that those components 
have well-defined interfaces. Debugging a failing unittest is usually 
easier than to debug a complex application.
While I don't know if there is a convenient way to test the GUI 
everything else should run reliably *before* connecting it with the GUI.


my problem is with the datasource module. I'm focused on 
making it

work (using logging to confirm that it is doing so). Will report results
when they're available.

Regards,

Rich



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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Alan Gauld via Python-list
On 01/06/2021 21:18, Rich Shepard wrote:
> On Sun, 30 May 2021, Cameron Simpson wrote:
> 
>> I've only just started with pdb. As of Python 3.7 there's a builtin
>> function named breakpoint() which drops you into the debugger.


> I'm stuck with neither approach (pdb, print()) working. 


> The activitytypes.py module:
> 

> class ATMainWindow(qtw.QMainWindow):
> 
>  def __init__(self):
>  super().__init__()
> 
>  # Model/View here.
>  self.model = qts.QSqlTableModel(db=db) # for single table
>  self.model.setTable('activitytypes')
>  self.model.select()
> 
>  self.table = qtw.QTableView()
>  self.table.setModel(self.model)
> 
>  self.setFixedSize(qtc.QSize(800, 600))

Assuming this is the line you want to examine set a beakpoint just above
it using the function that Cameron mentioned

(Or just set a breakpoint on the init() from pdb...

Trying to use step/next to debug an event driven application
is next to impossible. set breakpoints on the methods that
get triggered by events then generate the event to reach
the breakpoint.

Or, as in this case, on the init if you want to examine
objects as they are created.

As a general rule if you have to hit next/step more
than half a dozen times in a row you are probably making
extra work for yourself!


>> $/development/business_tracker/activitytypes.py(29)()
> -> window = ATMainWindow()
> (Pdb) n
> False
>> $/development/business_tracker/activitytypes.py(30)()
> -> window.show()
> (Pdb) n
>> $/development/business_tracker/activitytypes.py(32)()
> -> app.exec_()
> (Pdb) n
> n
>> $/development/business_tracker/activitytypes.py(32)()->None
> -> app.exec_()
> (Pdb) n

I'm not sure why you got that twice.
I'd expect you to only see it once.

> 
> and there it sits. No (Pdb) prompt, nothing. And no printed statements.

It's waiting while the app runs and for you to terminate it.

> I'd appreciate recommendations on the process to find where the bug lives
> since I can't seem to find it with print() or line-by-line in pdb.

Use breakpoints, don't try to step through the code from the
beginning - there lies madness!

And for event handlers that get called a lot use conditional
breakpoints so that you only stop when you want to.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Rich Shepard

On Tue, 1 Jun 2021, Dennis Lee Bieber wrote:


I suspect you really should be stepping INTO the calls, not just
invoking the functions completely and going to the next LOCAL statement.



$ /development/business_tracker/activitytypes.py(1)()

-> import sys
(Pdb) s

$ /development/business_tracker/activitytypes.py(2)()

-> import logging
(Pdb) s
--Call--

(978)_find_and_load()

(Pdb) s

Now I'll go learn what this means.

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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Rich Shepard

On Tue, 1 Jun 2021, Ethan Furman wrote:


Well, you only had two logging statements in that code -- logging is like
print: if you want to see it, you have to call it:


Ethan,

Got it, thanks.

I believe my problem is with the datasource module. I'm focused on making it
work (using logging to confirm that it is doing so). Will report results
when they're available.

Regards,

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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Ethan Furman

On 6/1/21 1:42 PM, Rich Shepard wrote:

> When I run it this is the output:
> $ python activitytypes.py 2021-06-01 13:39:10,219 -DEBUG - Start of Program
> 2021-06-01 13:39:15,229 -DEBUG - End of Program

Well, you only had two logging statements in that code -- logging is like 
print: if you want to see it, you have to call it:

logging.info('start of xx procedure')
logging.info('spam = %s', spam) # note the comma and not actual 
%-interpolation

> Obviously I have much to learn about using python's logging capabilities.
> I'll keep looking.

I'm certainly not an expert, but this is how I do it:

from logging import INFO, getLogger, Formatter, handlers

logger = getLogger()
logger.setLevel(INFO)
_handler = handlers.TimedRotatingFileHandler(
virtualenv / 'var/log/openerp/continuous_sync_records.log',
when='midnight',
backupCount=30,
)
_formatter = Formatter('%(asctime)s %(funcName)-25s %(message)s')
_handler.setFormatter(_formatter)
logger.addHandler(_handler)
del _handler, _formatter

and then in my code:

logger.info('failure converting %r to %r', target_bmp_file, target_png_file)

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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Rich Shepard

On Tue, 1 Jun 2021, Ethan Furman wrote:


Sounds like a console issue. Try using `logging` with a file... you could
even use `print` with a file if you wanted to.


Ethan,

Not before using logging I found a reference/example page
<https://devopslearning.medium.com/debugging-python-code-logging-pdb-a8ca08a6475e>
and modified the module to this:

# activitytypes.py
import sys
import logging

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5 import QtSql as qts

from datasource import db

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s -%(levelname)s - 
%(message)s')
logging.debug("Start of Program")

class ATMainWindow(qtw.QMainWindow):

def __init__(self):
super().__init__()

# Model/View here.
self.model = qts.QSqlTableModel(db=db) # for single table
self.model.setTable('activitytypes')
self.model.select()

self.table = qtw.QTableView()
self.table.setModel(self.model)

self.setMinimumSize(qtc.QSize(800, 600))
self.setCentralWidget(self.table)


if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
window = ATMainWindow()
window.show()
#sys.exit(app.exec())
app.exec_()

logging.debug("End of Program")

When I run it this is the output:
$ python activitytypes.py 
2021-06-01 13:39:10,219 -DEBUG - Start of Program

2021-06-01 13:39:15,229 -DEBUG - End of Program

Obviously I have much to learn about using python's logging capabilities.
I'll keep looking.

Thanks,

Rich




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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Rich Shepard

On Tue, 1 Jun 2021, Rich Shepard wrote:


The QSize() statement is never reached.


Correction: the window is 800 x 600, but it's still empty.

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


Re: Neither pdb or print() displays the bug

2021-06-01 Thread Ethan Furman

On 6/1/21 1:18 PM, Rich Shepard wrote:

> I'd appreciate recommendations on the process to find where the bug lives
> since I can't seem to find it with print() or line-by-line in pdb.

Sounds like a console issue.  Try using `logging` with a file... you could even 
use `print` with a file if you wanted to.

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


Neither pdb or print() displays the bug

2021-06-01 Thread Rich Shepard

On Sun, 30 May 2021, Cameron Simpson wrote:


I've only just started with pdb. As of Python 3.7 there's a builtin
function named breakpoint() which drops you into the debugger. I've never
been a big debugger person, historicly using print() and equivalent.
However, this makes it very easy to insert this call into a piece of code
instead of having to invoke one's programme in a special way.


I'm stuck with neither approach (pdb, print()) working. I moved the database
code to a separate module, datasource.py, and when I run the
activitytypes.py module (using pdb and having entered print() statements at
various places in both the datasource and activities modules all I get is a
small, empty window with the window title. The QSize() statement is never
reached.

The activitytypes.py module:

import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5 import QtSql as qts

from datasource import db

class ATMainWindow(qtw.QMainWindow):

def __init__(self):
super().__init__()

# Model/View here.
self.model = qts.QSqlTableModel(db=db) # for single table
self.model.setTable('activitytypes')
self.model.select()

self.table = qtw.QTableView()
self.table.setModel(self.model)

self.setFixedSize(qtc.QSize(800, 600))
self.setCentralWidget(self.table)


if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
window = ATMainWindow()
window.show()
#sys.exit(app.exec())
app.exec_()

Running the module in pdb and using 'next' to step through it produces this
result:


$/development/business_tracker/activitytypes.py(29)()

-> window = ATMainWindow()
(Pdb) n
False

$/development/business_tracker/activitytypes.py(30)()

-> window.show()
(Pdb) n

$/development/business_tracker/activitytypes.py(32)()

-> app.exec_()
(Pdb) n
n

$/development/business_tracker/activitytypes.py(32)()->None

-> app.exec_()
(Pdb) n

and there it sits. No (Pdb) prompt, nothing. And no printed statements.

I'd appreciate recommendations on the process to find where the bug lives
since I can't seem to find it with print() or line-by-line in pdb.

TIA,

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


Re: @unittest.skip doesn't print anything in Python <= 3.7

2021-02-15 Thread אורי
Hi Terry,

Shai Berger found the bug and replied in Stack Overflow.

Thanks,
Uri.
אורי
u...@speedy.net


On Fri, Feb 12, 2021 at 11:36 PM Terry Reedy  wrote:

> On 2/11/2021 3:25 PM, אורי wrote:
> > Hi,
> >
> >
> https://stackoverflow.com/questions/66161394/unittest-skip-doesnt-print-anything-in-python-3-7
> >
> > We are using Django with unittest. Some tests are skipped with the
> > @unittest.skip decorator. But if I run the tests with Python 3.6 or 3.7,
> I
> > get a number of tests passed (Ran 993 tests / OK), and if I run the same
> > tests with Python 3.8, I get the same number of tests but with some tests
> > skipped (Ran 993 tests / OK (skipped=4)).
>
> ...
>
> > I think the skipped tests are skipped in all Python versions, but in
> Python
> > 3.6 and 3.7 there is no output about them being skipped. Is it a bug?
>
> Perhaps you have discover a bug in 3.7 that was fixed in 3.8.  Each new
> version comes with a few hundred bug fixes, not just the new features,
> although only the latter are featured in the new version announcement.
>
> If you are really concerned, find What's New in 3.8 and look changelog,
> linked in the first paragraph, for 'unittest' issues.
>
> --
> Terry Jan Reedy
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: @unittest.skip doesn't print anything in Python <= 3.7

2021-02-12 Thread Terry Reedy

On 2/11/2021 3:25 PM, אורי wrote:

Hi,

https://stackoverflow.com/questions/66161394/unittest-skip-doesnt-print-anything-in-python-3-7

We are using Django with unittest. Some tests are skipped with the
@unittest.skip decorator. But if I run the tests with Python 3.6 or 3.7, I
get a number of tests passed (Ran 993 tests / OK), and if I run the same
tests with Python 3.8, I get the same number of tests but with some tests
skipped (Ran 993 tests / OK (skipped=4)).


...


I think the skipped tests are skipped in all Python versions, but in Python
3.6 and 3.7 there is no output about them being skipped. Is it a bug?


Perhaps you have discover a bug in 3.7 that was fixed in 3.8.  Each new 
version comes with a few hundred bug fixes, not just the new features, 
although only the latter are featured in the new version announcement.


If you are really concerned, find What's New in 3.8 and look changelog, 
linked in the first paragraph, for 'unittest' issues.


--
Terry Jan Reedy


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


@unittest.skip doesn't print anything in Python <= 3.7

2021-02-11 Thread אורי
Hi,

https://stackoverflow.com/questions/66161394/unittest-skip-doesnt-print-anything-in-python-3-7

We are using Django with unittest. Some tests are skipped with the
@unittest.skip decorator. But if I run the tests with Python 3.6 or 3.7, I
get a number of tests passed (Ran 993 tests / OK), and if I run the same
tests with Python 3.8, I get the same number of tests but with some tests
skipped (Ran 993 tests / OK (skipped=4)). I would like to know if the same
tests were also skipped with Python 3.6 and 3.7, or only with Python 3.8?
And why do I get the skipped output only with Python 3.8? And is the number
993 including the skipped tests or not including them? Is one of the
outputs incorrect? Because it doesn't make sense that the output is
different for different versions of Python and I don't understand the
reason for this difference. I didn't find it documented in the
documentation.

Our code is open source, and you can see for example a skipped test here.

*Update:* I added 4 more tests with the decorator @unittest.skip. When I
run all the tests with Python 3.8, I get this output: Ran 997 tests / OK
(skipped=8) (with an s for every skipped test, like before). But if I run
the tests with Python 3.6 or 3.7, I get this output: Ran 997 tests / OK and
there are no s in the output, like before (I get 997 dots). Although I have
4 more tests than before.

The tests I added raise an exception, so if they would not be skipped they
would fail.

I think the skipped tests are skipped in all Python versions, but in Python
3.6 and 3.7 there is no output about them being skipped. Is it a bug?

אורי
u...@speedy.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print the output of my code in Markdown using variable (not the value)

2020-08-15 Thread Mats Wichmann
On 8/15/20 11:00 AM, Michio Suginoo wrote:
> Hi,
> 
> I am still at an early stage of my personal Python evolution.
> 
> I am coding Python3 in Jupyter Notebook (Anaconda environment).
> 
> I want to print the output of my code in a 'markdown'.
> I want to use the variable in the 'markdown' rather than typing the output.
> This would save my time every time the value changes for whatever the
> reason might be.
> 
> Please advise me how to do it.

Just a gentle suggestion... show a sample of what you're trying to
achieve, and if possible some code that you've tried.

This might be a place to look:

https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Markdown
-- 
https://mail.python.org/mailman/listinfo/python-list


print the output of my code in Markdown using variable (not the value)

2020-08-15 Thread Michio Suginoo
Hi,

I am still at an early stage of my personal Python evolution.

I am coding Python3 in Jupyter Notebook (Anaconda environment).

I want to print the output of my code in a 'markdown'.
I want to use the variable in the 'markdown' rather than typing the output.
This would save my time every time the value changes for whatever the
reason might be.

Please advise me how to do it.

Thanks
Best

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


Re: Can a print overwrite a previous print ?

2020-05-08 Thread Cameron Simpson

On 08May2020 09:36, Sir Real  wrote:

On Fri, 8 May 2020 16:25:52 +0200, ast  wrote:

Suppose we want that:

print("abcdef"); print("ghi")

produces:

ghidef

The 2nd print overwrites the first one.
Is it feasible ?


On a terminal, yes. This is a display issue.


It should since the progress bar tdqh seems to do that

try:
from tkdm import tkdm
for i in tqdm(range(100_000_000)):
pass
It produces a progress bar like this:
100%|???|
1/1 [00:56<00:00, 1781611.52it/s]



print('abcdef', end='\r'); print('ghi', end='')


Aye, though that is the (hated by me) rewrite-the-whole-line brute force 
approach.


I've got a module "cs.upd" on PyPI which does this with minimal 
overwrites if you want something eaier on the eyes. Doubtless there are 
others.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Can a print overwrite a previous print ?

2020-05-08 Thread ast

Hello


Suppose we want that:

print("abcdef"); print("ghi")

produces:

ghidef

The 2nd print overwrites the first one.
Is it feasible ?

It should since the progress bar tdqh seems to do that

try:

from tkdm import tkdm

for i in tqdm(range(100_000_000)):
pass

It produces a progress bar like this:
100%|███| 
1/1 [00:56<00:00, 1781611.52it/s]

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


Re: Can a print overwrite a previous print ?

2020-05-08 Thread Sir Real via Python-list
On Fri, 8 May 2020 16:25:52 +0200, ast  wrote:

>Hello
>
>
>Suppose we want that:
>
>print("abcdef"); print("ghi")
>
>produces:
>
>ghidef
>
>The 2nd print overwrites the first one.
>Is it feasible ?
>
>It should since the progress bar tdqh seems to do that
>
>try:
>
>from tkdm import tkdm
>
>for i in tqdm(range(100_000_000)):
> pass
>
>It produces a progress bar like this:
>100%|???????| 
>1/1 [00:56<00:00, 1781611.52it/s]


print('abcdef', end='\r'); print('ghi', end='')

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


Re: print() ignores context ?

2020-05-05 Thread Greg Ewing

On 1/05/20 8:33 pm, R.Wieser wrote:


getcontext().rounding=ROUND_HALF_UP

print(round(1.5))
print(round(2.5))


If you're talking about getcontext() from the decimal module,
that only affects operations with Decimals, not regular floats.
Python doesn't provide a way to change the rounding mode for
floats.

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


Re: "min( arg1, arg2, *args )" vs. "print( value, ... )"?

2020-04-09 Thread Peter J. Holzer
On 2020-04-08 08:50:07 +0200, Luuk wrote:
> On 6-4-2020 22:57, Stefan Ram wrote:
> >The documentation ("help" under CPython 3.9) for "min" reads
> >(simplified):
> > 
> > min( arg1, arg2, *args )
> > 
> >, for "print" it reads (simplified):
> > 
> > print( value, ... ).
> > 
> >The caller can place an arbitrary number of arguments at the
> >place of "value, ..." or of "*args", respectively.
> > 
> >So, from the point of view of the caller: is there any
> >difference between "args, ..." and "*args" when he reads
> >it in the documentation?
> 
> `arg1, arg2, *args` is just a smart way to say you need at least 2 args.

min(arg1, arg2, *args) is Python syntax.

min(arg1, arg2, args, ...) isn't. It is kind of C-like, but not really.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "min( arg1, arg2, *args )" vs. "print( value, ... )"?

2020-04-07 Thread Luuk

On 6-4-2020 22:57, Stefan Ram wrote:

   The documentation ("help" under CPython 3.9) for "min" reads
   (simplified):

min( arg1, arg2, *args )

   , for "print" it reads (simplified):

print( value, ... ).

   The caller can place an arbitrary number of arguments at the
   place of "value, ..." or of "*args", respectively.

   So, from the point of view of the caller: is there any
   difference between "args, ..." and "*args" when he reads
   it in the documentation?




`arg1, arg2, *args` is just a smart way to say you need at least 2 args.

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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-07 Thread Luca

On 4/6/2020 11:05 PM, Luca wrote:

On 4/6/2020 8:51 PM, Reto wrote:

out = df.to_csv(None)
new = pd.read_csv(io.StringIO(out), index_col=0)


Thank you, brother. It works



BTW, a little gotcha (I write this in case someone gets here in the 
future through Google or something)


"""
import pandas as pd
import numpy as np
import io
df = pd.DataFrame(10*np.random.randn(3,4))
df = df.astype(int)
out = df.to_csv(None)

# out == ',0,1,2,3\n0,9,4,-5,-2\n1,16,12,-1,-5\n2,-2,8,0,6\n'

new = pd.read_csv(io.StringIO(out), index_col=0)

#gotcha
type(df.iloc[1,1]) # numpy.int32
type(new.iloc[1,1]) # numpy.int64
"""

new == out will return a dataframe of False

0   1   2   3
0   False   False   False   False
1   False   False   False   False
2   False   False   False   False

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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Luca

On 4/6/2020 8:51 PM, Reto wrote:

out = df.to_csv(None)
new = pd.read_csv(io.StringIO(out), index_col=0)


Thank you, brother. It works

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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Reto
On Mon, Apr 06, 2020 at 06:29:01PM -0400, Luca wrote:
> so, given a dataframe, how do I make it print itself out as CSV?

read the docs of to_csv...

> And given CSV data in my clipboard, how do I paste it into a Jupiter cell
> (possibly along with a line or two of code) that will create a dataframe out
> of it?

```python
import pandas as pd
import io
df = pd.DataFrame(data=range(10))
out = df.to_csv(None)
new = pd.read_csv(io.StringIO(out), index_col=0)
```

That'll do the trick... any other serialization format works similarly.
you can copy out to wherever, it's just csv data.

Cheers,
Reto
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Luca

On 4/6/2020 3:03 PM, Christian Gollwitzer wrote:





CSV is the most sensible option here. It is widely supported by 
spreadsheets etc. and easily copy/pasteable.


Thank you Christian.

so, given a dataframe, how do I make it print itself out as CSV?

And given CSV data in my clipboard, how do I paste it into a Jupiter 
cell (possibly along with a line or two of code) that will create a 
dataframe out of it?



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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Christian Gollwitzer

Am 06.04.20 um 17:17 schrieb Luca:

On 4/6/2020 4:08 AM, Reto wrote:

Does this help?


Thank you, but not really. What I am trying to achieve is to have a way 
to copy and paste small yet complete dataframes (which may be the result 
of previous calculations) between a document (TXT, Word, GoogleDoc) and 
Jupiter/IPython.


Did I make sense?



CSV is the most sensible option here. It is widely supported by 
spreadsheets etc. and easily copy/pasteable.


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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Luca

On 4/6/2020 4:08 AM, Reto wrote:

Does this help?


Thank you, but not really. What I am trying to achieve is to have a way 
to copy and paste small yet complete dataframes (which may be the result 
of previous calculations) between a document (TXT, Word, GoogleDoc) and 
Jupiter/IPython.


Did I make sense?

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


Re: print small DataFrame to STDOUT and read it back into dataframe

2020-04-06 Thread Reto
On Sat, Apr 04, 2020 at 07:00:23PM -0400, Luca wrote:
> dframe.to_string
> 
> gives:
> 
>  0  a0  b0  c0  d0
> 1  a1  b1  c1  d1
> 2  a2  b2  c2  d2
> 3  a3  b3  c3  d3>

That's not the output of to_string.
to_string is a method, not an attribute which is apparent by the

> 

comment in your output.
You need to call it with parenthesis like `dframe.to_string()`

> Can I evaluate this string to obtain a new dataframe like the one that
> generated it?

As for re-importing, serialize the frame to something sensible first.
There are several options available, csv, json, html... Take your pick.

You can find all those in the dframe.to_$something namespace
(again, those are methods, make sure to call them).

Import it again with pandas.read_$something, choosing the same serialization 
format
you picked for the output in the first place.

Does this help?

Cheers,
Reto
-- 
https://mail.python.org/mailman/listinfo/python-list


print small DataFrame to STDOUT and read it back into dataframe

2020-04-04 Thread Luca



possibly a stupid question. Let's say I have a (small) dataframe:

import pandas as pd
dframe = pd.DataFrame({'A': ['a0','a1','a2','a3'],
'B': ['b0','b1','b2','b3'],
'C': ['c0','c1','c2','c3'],
'D': ['d0','d1','d2','d3']}, index=[0,1,2,3])

Is there a way that I can ask this dataframe to "print itself" in a way 
that I can copy that output and easily rebuild the original dataframe 
with index, columns and all?


dframe.to_string

gives:



Can I evaluate this string to obtain a new dataframe like the one that 
generated it?


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


Re: Paper Print Help

2020-02-20 Thread Rhodri James

On 20/02/2020 15:08, Duram wrote:

On 19/02/2020 12:17, Rhodri James wrote:

On 19/02/2020 14:22, Duram via Python-list wrote:
I have a drawing in a .gif file with (a,b) pixels and want to 
paperprint it in a position (x,y), what would be the code?


What have you tried?


Nothing, I did not find the module that make to print to the paper


Please don't reply to me directly; if it's a question worth asking in 
public then it's worth answering in public too!


OK, let's backtrack a bit.  First off, what operating system are you using?

Second, do you have this GIF file in any sort of program at the moment, 
or do you want advice on how to write a program to handle the image?  I 
suspect your question is a bit too specific at the moment, and you have 
some mistaken assumptions about how images and (most especially) 
printing work.


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: Paper Print Help

2020-02-19 Thread Rhodri James

On 19/02/2020 14:22, Duram via Python-list wrote:
I have a drawing in a .gif file with (a,b) pixels and want to paperprint 
it in a position (x,y), what would be the code?


What have you tried?

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Paper Print Help

2020-02-19 Thread Duram via Python-list
I have a drawing in a .gif file with (a,b) pixels and want to paperprint 
it in a position (x,y), what would be the code?

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


Re: Print statement

2020-01-28 Thread Frank Millman

On 2020-01-28 12:14 PM, L A Smit wrote:

Please help me with this.

squares =input("\nSquares: ")

print(float((squares) *float(.15)) *(1.3))

Cant print answer.

   print(float((squares) * float(.15)) *(1.3))
TypeError: can't multiply sequence by non-int of type 'float'



You have some superfluous brackets around 'squares' and '1.3', which 
hinder readability.


Remove them and you get -

float(squares * float(.15)) * 1.3

Now you can see that you have the brackets in the wrong place - you are 
trying to multiply 'squares', which at this stage is still a string, by 
float(.15).


You can multiply a string by an integer, but not by a float -

>>> 'abc' * 3
'abcabcabc'
>>>

>>> 'abc' * 1.5
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can't multiply sequence by non-int of type 'float'
>>>

You probably meant
float(squares) * float(.15)

or more simply
float(squares) * .15

HTH

Frank Millman

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


Print statement

2020-01-28 Thread L A Smit

Please help me with this.

squares =input("\nSquares: ")

print(float((squares) *float(.15)) *(1.3))

Cant print answer.

  print(float((squares) * float(.15)) *(1.3))
TypeError: can't multiply sequence by non-int of type 'float'

Thx

L Smit

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


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-05 Thread Pieter van Oostrum
Chris Angelico  writes:

> On Tue, Nov 5, 2019 at 5:43 PM dieter  wrote:
>> I suppose that "isinstance" (at least under Python 2) does not
>> behave exactly as stated in PEP 3119. Instead, "isinstance"
>> first directly checks for the instance to be an instance of the
>> class *AND ONLY IF THIS FAILS* calls the class' "__instancecheck__".
>
> PEP 3119 is specifically about Python 3.0; I don't know how much, if
> any, was backported into Python 2.

Yes, it has been there since Python 2.6.

I looked in the implementation, and isinstance(inst, cls) first checks if the 
class of ins is cls, then the result is True.
There are a few other shortcut cases, and only at the end the __instancecheck__ 
method is called.

You can check this with the original example:

In [88]: class MA(type):
...:   def __instancecheck__(cls, inst):
...: print "MA", cls, inst
...: 
...: class AM(list): __metaclass__ = MA
...: class AM2(AM): pass
...: 
...: am = AM2()

In [89]: isinstance(am, AM)
MA  []
Out[89]: False

It returns False because __instancecheck__ returns None

Same for Python3:

In [8]: class MA(type):
   ...:   def __instancecheck__(cls, inst):
   ...: print ("MA", cls, inst)
   ...: 
   ...: class AM(list, metaclass = MA): pass
   ...: class AM2(AM): pass
   ...: 
   ...: am = AM2()

In [9]: isinstance(am, AM)
MA  []
Out[9]: False

-- 
Pieter van Oostrum 
WWW: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-05 Thread Rhodri James

On 04/11/2019 22:23, Peter J. Holzer wrote:

On 2019-11-04 14:54:23 +, Rhodri James wrote:

On 04/11/2019 14:33, Veek M wrote:

__metaclass__ = whatever; # is python2.x syntax


But not Python3: see PEP 3115


Doesn't "X is python2.x syntax" imply "X is not python3 syntax"?


Not necessarily, the OP might have (and apparently was) assuming that it 
was also Python3 syntax.  Also it gave me an opportunity to point him to 
the appropriate PEP.  That said, we've reached the limits of my 
knowledge here and I'm bowing out of the discussion.


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Chris Angelico
On Tue, Nov 5, 2019 at 5:43 PM dieter  wrote:
> I suppose that "isinstance" (at least under Python 2) does not
> behave exactly as stated in PEP 3119. Instead, "isinstance"
> first directly checks for the instance to be an instance of the
> class *AND ONLY IF THIS FAILS* calls the class' "__instancecheck__".

PEP 3119 is specifically about Python 3.0; I don't know how much, if
any, was backported into Python 2.

I strongly recommend using Python 3 when probing features like this.
Not everything is supported on the legacy branch of Python.

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


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread dieter
Veek M  writes:
I simplify your code to demonstrate what goes on:
>>> class MA(type):
...   def __instancecheck__(cls, inst):
... print "MA", cls, inst
... 
>>> class AM(list): __metaclass__ = MA
... 
>>> am = AM()
>>> isinstance(am, AM)
True

As you can see, even with a class (rather than a tuple)
as second argument to "isinstance", "MA.__instancecheck__"
is not called.

I suppose that "isinstance" (at least under Python 2) does not
behave exactly as stated in PEP 3119. Instead, "isinstance"
first directly checks for the instance to be an instance of the
class *AND ONLY IF THIS FAILS* calls the class' "__instancecheck__".

As PEP 3119 suggests, "__instancecheck__" has been introduced
to support abstract base classes. The example given there
is an abstract base class "Sequence" and concrete derived classes
"list" and "tuple". For this use case, it is okay when
"isinstance(inst, cls)" returns "True" whenever "inst" is a "cls"
object and that "cls.__instancecheck__" is used only to result in
"True" also for other cases.


> 1. Why do I get True whenever i tuple the 
> isinstance(f, (Bar, Foo))
> (and why don't the print's run)
>
> The docs say that you can feed it a tuple and that the results are OR'd
>
> 
> The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
> isinstance(x, A) or isinstance(x, B) or ... (etc.).
> -
> which implies that the metaclasses are called for each class?
>
>
> class MyzMeta(type):
> def __instancecheck__(cls, other):
> print('MyzzMeta', other)
> return 0
>
>
> class MyMeta(MyzMeta, object):
> def __instancecheck__(cls, other):
> print('MyMeta')
> print(cls, other)
> return 0
>
> 
> class Foo(list):
> __metaclass__ = MyzMeta
> pass
>
> class Miaow(object):
> pass
>
> class Bar(Foo, Miaow):
> __metaclass__ = MyMeta
> pass
>
>
> f = Foo()
> b = Bar()
>
> print(isinstance(f, (Bar, Foo)))
> raise SystemExit
>
> if isinstance(f, (Bar, Foo)):
> print('success')

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


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Peter J. Holzer
On 2019-11-04 14:54:23 +, Rhodri James wrote:
> On 04/11/2019 14:33, Veek M wrote:
> > __metaclass__ = whatever; # is python2.x syntax
> 
> But not Python3: see PEP 3115

Doesn't "X is python2.x syntax" imply "X is not python3 syntax"?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Rhodri James

On 04/11/2019 14:33, Veek M wrote:


Aha.  You're trying to fix up the metaclass after the fact, which is not
the right way to do it.  If you change the class definitions to:


__metaclass__ = whatever; # is python2.x syntax


But not Python3: see PEP 3115


then you get the prints from MyMeta.__instancecheck__().  The
isinstance() still returns True, though, and I don't know why.  Then
again, your definition of MyMeta is really weird.


weird how..?
(I'm just trying to figure out what's going on with __instancecheck__ -
no further higher purpose :p)

example, when we do: isinstance(x, (A, B, C))
you expect from the docs that
A.__instancecheck__(cls, x) is passed but x = []
also, B and C.__instancecheck__ is not called when I return False

Also if I interchange (Bar, Foo), expecting that Foo.__instancecheck__
will be called, it's completely bypassed


That must be what's responsible for the True result.  Logically the 
problem must be to do with your MyzMeta class then.  I have no idea what.


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Veek M
> 
> Aha.  You're trying to fix up the metaclass after the fact, which is not
> the right way to do it.  If you change the class definitions to:
> 
__metaclass__ = whatever; # is python2.x syntax

> then you get the prints from MyMeta.__instancecheck__().  The
> isinstance() still returns True, though, and I don't know why.  Then
> again, your definition of MyMeta is really weird.

weird how..?
(I'm just trying to figure out what's going on with __instancecheck__ - 
no further higher purpose :p)

example, when we do: isinstance(x, (A, B, C))
you expect from the docs that
A.__instancecheck__(cls, x) is passed but x = []
also, B and C.__instancecheck__ is not called when I return False

Also if I interchange (Bar, Foo), expecting that Foo.__instancecheck__ 
will be called, it's completely bypassed
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Rhodri James

On 04/11/2019 11:30, Veek M wrote:

1. Why do I get True whenever i tuple the
isinstance(f, (Bar, Foo))
(and why don't the print's run)


I'm not very familiar with metaclasses, but I can answer the second part 
of your question.




The docs say that you can feed it a tuple and that the results are OR'd


The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
-
which implies that the metaclasses are called for each class?


class MyzMeta(type):
 def __instancecheck__(cls, other):
 print('MyzzMeta', other)
 return 0


class MyMeta(MyzMeta, object):
 def __instancecheck__(cls, other):
 print('MyMeta')
 print(cls, other)
 return 0

 
class Foo(list):

 __metaclass__ = MyzMeta
 pass

class Miaow(object):
 pass

class Bar(Foo, Miaow):
 __metaclass__ = MyMeta
 pass



Aha.  You're trying to fix up the metaclass after the fact, which is not 
the right way to do it.  If you change the class definitions to:


class Foo(list, metaclass=MyzMeta):
pass

class Bar(Foo, Miaow, metaclass=MyMeta):
pass

then you get the prints from MyMeta.__instancecheck__().  The 
isinstance() still returns True, though, and I don't know why.  Then 
again, your definition of MyMeta is really weird.





f = Foo()
b = Bar()

print(isinstance(f, (Bar, Foo)))



--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


__instancecheck__ metaclasses, how do they work: why do I get True when I tuple, why doesn't print run?

2019-11-04 Thread Veek M
1. Why do I get True whenever i tuple the 
isinstance(f, (Bar, Foo))
(and why don't the print's run)

The docs say that you can feed it a tuple and that the results are OR'd


The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
-
which implies that the metaclasses are called for each class?


class MyzMeta(type):
def __instancecheck__(cls, other):
print('MyzzMeta', other)
return 0


class MyMeta(MyzMeta, object):
def __instancecheck__(cls, other):
    print('MyMeta')
print(cls, other)
return 0


class Foo(list):
__metaclass__ = MyzMeta
pass

class Miaow(object):
pass

class Bar(Foo, Miaow):
__metaclass__ = MyMeta
    pass


f = Foo()
b = Bar()

print(isinstance(f, (Bar, Foo)))
raise SystemExit

if isinstance(f, (Bar, Foo)):
print('success')
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >