Re: bool and int

2023-01-28 Thread Chris Angelico
On Sun, 29 Jan 2023 at 11:27, rbowman  wrote:
>
> On Fri, 27 Jan 2023 21:35:11 -0800 (PST), Grant Edwards wrote:
>
> > In Unix shells, a return code of 0 is true and non-0 is false.
>
> That carries over to some C functions like strcmp() although it's more
> complex. strcmp() returns the value of subtracting the nth character of
> string b from string a if the value is not 0. For matching strings, the
> result is 0 for all character positions.
>
> This plays nicely with sorting functions but naive programmers assume it's
> a boolean and strcmp("foo", "foo") should return 1 or true when the
> strings match.
>
> Returning 0 for success gives you much more latitude in return values.

That's not really about booleans, it's more like "imagine subtracting
one string from another". You can compare two integers by subtracting
one from another; you'll get a number that's less than zero, zero, or
greater than zero, just like with strcmp. And yes, that plays
perfectly with sorting functions. So when you want to compare strings,
what do you do? You make something that subtracts one string from
another.

It's "String Compare", not "Are Strings Equal", so it doesn't return a
boolean. Zero for equal makes very good sense, even though a "strings
equal" function would return zero for non-equal.

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


Re: RE: RE: bool and int

2023-01-28 Thread Dino



you have your reasons, and I was tempted to stop there, but... I have to 
pick this...


On 1/26/2023 10:09 PM, avi.e.gr...@gmail.com wrote:

  You can often borrow
ideas and code from an online search and hopefully cobble "a" solution
together that works well enough. Of course it may suddenly fall apart.


also carefully designed systems that are the work of experts may 
suddenly fall apart.


Thank you for all the time you have used to address the points I raised. 
It was interesting reading.


Dino

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


Re: bool and int

2023-01-28 Thread rbowman
On Fri, 27 Jan 2023 21:35:11 -0800 (PST), Grant Edwards wrote:

> In Unix shells, a return code of 0 is true and non-0 is false.

That carries over to some C functions like strcmp() although it's more 
complex. strcmp() returns the value of subtracting the nth character of 
string b from string a if the value is not 0. For matching strings, the 
result is 0 for all character positions.

This plays nicely with sorting functions but naive programmers assume it's 
a boolean and strcmp("foo", "foo") should return 1 or true when the 
strings match.

Returning 0 for success gives you much more latitude in return values.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-27 Thread Grant Edwards
On 2023-01-27, Mark Bourne  wrote:

> So Python is even flexible enough to be made to deal with insane 
> situations where False is 2!

IIRC, in VMS DCL even numbers were false and odd numbers were true.

In Unix shells, a return code of 0 is true and non-0 is false.

Though that's not really the same environment that Python lives in...


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


Re: bool and int

2023-01-27 Thread Chris Angelico
On Sat, 28 Jan 2023 at 11:45, Greg Ewing  wrote:
>
> On 26/01/23 6:10 am, Chris Angelico wrote:
> > And that's a consequence of a system wherein there is only one concept
> > of "success", but many concepts of "failure". Whoever devised that
> > system was clearly a pessimist :)
>
> Murphy's Law for Unix: If something can go wrong, it will go
> wrong 255 times out of 256.
>

Murphy's Law for people working with small integers: "255 out of 256"
will, just when you least expect it, change into "255 out of 0".

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


Re: bool and int

2023-01-27 Thread Mark Bourne

avi.e.gr...@gmail.com wrote:
...

Interestingly, I wonder if anyone has
designed an alternate object type that can be used mostly in place of
Booleans but which imposes changes and restrictions so trying to add a
Boolean to an integer, or vice versa, results in an error. Python is
flexible enough to do that and perhaps there already is a module out there


Not exactly what you describe, but I did once write a subclass of int 
for use in an SNMP interface, where true is represented as 1 and false 
as 2.  I don't recall the exact details offhand, but it involved 
overriding __bool__ so that a value of 1 returned True and anything else 
False.  The way it was used should have ensured that it only ever had 
the value 1 or 2, but doing it this way round (rather than e.g. 2 being 
False and anything else True) meant that if it somehow got the value 0, 
that would also be treated as False.  I think it also overrode __init__ 
(or perhaps __new__) to covert a bool True or False to 1 or 2 (rather 
than 1 or 0) for its own value, so it could be initialised from either 
an int or a bool and correctly converted in either direction via int() 
or bool().


So Python is even flexible enough to be made to deal with insane 
situations where False is 2!


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


Re: bool and int

2023-01-27 Thread Greg Ewing

On 26/01/23 6:10 am, Chris Angelico wrote:

And that's a consequence of a system wherein there is only one concept
of "success", but many concepts of "failure". Whoever devised that
system was clearly a pessimist :)


Murphy's Law for Unix: If something can go wrong, it will go
wrong 255 times out of 256.

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


Re: bool and int

2023-01-27 Thread Rob Cliffe via Python-list



On 24/01/2023 04:22, Dino wrote:


$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b = True
>>> isinstance(b,bool)
True
>>> isinstance(b,int)
True
>>>


That immediately tells you that either
    bool is a subclass of int
    int is a subclass of bool
    bool and int are both subclasses of some other class
In fact the first one is true.
This is not a logical necessity, but the way Python happens to be designed.
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list


RE: RE: bool and int

2023-01-26 Thread avi.e.gross
[Dino has a deliberately invalid email address so sending him anything
privately is not an option.]

Dino,

I would agree with you that for some purposes, you do NOT need to dig deep
into a language to get fairly routine things done. You can often borrow
ideas and code from an online search and hopefully cobble "a" solution
together that works well enough. Of course it may suddenly fall apart. An
example is code written that assumes 4 specific files exist in the current
directory and unconditionally reads them and does stuff and eventually
overwrites some other file with new data. OOPS, what does the program do it
one or more files do not exist in the current directory under those exact
names? Does it check if they exist and exit gracefully, or start throwing
error messages as the code blindly proceeds on trying to change variables
that were never created and so on, and then end with perhaps an emptied file
and ruin lots of things?

Too many examples you get from the internet are a bit like that. They often
just tell you how to do something specific but leave out lots of details
that are a good idea for many kinds of code. And some adjustments you make
may break things and produce a result you trust but that is actually wrong. 

So if you find something you don't like about the language, guess what. You
have very little standing if you never learned much more than what it took
to copy some code.  You are likely to be told things by others ranging from
suggesting you need to do it another way or that the language is doing
exactly what was designed and suggestions you go back to school and get a
proper education and then the answer may be obvious.

It truly does NOT matter what YOU think should happen unless you point to
documentation that says something else should have happened.

I will skip a lengthier reply but am thinking how some languages use a
boxing/unboxing approach to wrap native "objects" like an integer. In many
cases, your program is allowed to treat this as either a wrapped object or
unboxed as needed and the compiler or interpreter keeps making changes
behind the scenes so you see it as needed. In a sense, Booleans are a
restricted form of integer and are viewed one of several ways. Python goes
many steps further and has a concept of truthy that maps practically
anything to True or False.

The bottom line is not that Python or any language is wrong or right or
great or horrible. It is that based on your own admission, you have not
taken steps to understand more than you have to and thus are in a weak
position to argue anything. Not because any of us are smarter in some sense,
but because some of us do study more intensively and come ready to
re-evaluate our ideas when we encounter others. What Python does in the
situation discussed is pretty much what an assortment of languages include
many C-based ones do. If it happens that your background is limited, fine.
Many of us here have been exposed to the ideas in 5 or a dozen or literally
hundreds of languages and variants and are well aware that some languages
treat Booleans differently. But note we are posting on this forum so we
generally don't find it that objectionable the way Python has chosen. 

We welcome well-intentioned discussions and the question is not at all
stupid. But our answers may not be being seen as reasonable and that can be
of some concern. The answer remains that the language was designed this way
and many are happy with the design. Interestingly, I wonder if anyone has
designed an alternate object type that can be used mostly in place of
Booleans but which imposes changes and restrictions so trying to add a
Boolean to an integer, or vice versa, results in an error. Python is
flexible enough to do that and perhaps there already is a module out there
...


-Original Message-
From: Python-list  On
Behalf Of Dino
Sent: Thursday, January 26, 2023 9:26 AM
To: python-list@python.org
Subject: Re: RE: bool and int


Wow. That was quite a message and an interesting read. Tempted to go deep
and say what I agree and what I disagree with, but there are two
issues: 1) time 2) I will soon be at a disadvantage discussing with people
(you or others) who know more than me (which doesn't make them right
necessarily, but certainly they'll have the upper-hand in a discussion).

Personally, in the first part of my career I got into the habit of learning
things fast, sometimes superficially I confess, and then get stuff done
hopefully within time and budget. Not the recommended approach if you need
to build software for a nuclear plant. An OK approach (within reason) if you
build websites or custom solutions for this or that organization and the
budget is what it is. After all, technology moves sooo fast, and what we
learn in detail today is bound to be old and possibly useless 5 years down
the road.

Also, I argue that there is value in having familiarity with lots of
different technologies (front-end and b

Re: bool and int

2023-01-26 Thread Chris Angelico
On Fri, 27 Jan 2023 at 06:32, Dino  wrote:
>
> On 1/25/2023 5:42 PM, Chris Angelico wrote:
>
> >
> > Try this (or its equivalent) in as many languages as possible:
> >
> > x = (1 > 2)
> > x == 0
> >
> > You'll find that x (which has effectively been set to False, or its
> > equivalent in any language) will be equal to zero in a very large
> > number of languages. Thus, to an experienced programmer, it would
> > actually be quite the opposite: having it NOT be a number would be the
> > surprising thing!
>
> I thought I had already responded to this, but I can't see it. Weird.
>
> Anyway, straight out of the Chrome DevTools console:
> 
> x = (1>2)
> false
>
> x == 0
> true
>
> typeof(x)
> 'boolean'
>
> typeof(0)
> 'number'
>
> typeof(x) == 'number'
> false
>
> So, you are technically correct, but you can see that JavaScript - which
> comes with many gotchas - does not offer this particular one.
>

That's not what I said, though! What you did in JS was the equivalent of this:

>>> type(True) == type(1)
False

which isn't the same as an isinstance check. Instead, try *exactly
what I said*. You'll find that false is equal to zero and true is
equal to one, just like it is in Python.

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


Re: bool and int

2023-01-26 Thread Ben Bacarisse
Chris Angelico  writes:

> On Thu, 26 Jan 2023 at 08:19, Dino  wrote:
>>
>> On 1/23/2023 11:22 PM, Dino wrote:
>> >  >>> b = True
>> >  >>> isinstance(b,bool)
>> > True
>> >  >>> isinstance(b,int)
>> > True
>> >  >>>
>>
>> ok, I read everything you guys wrote. Everyone's got their reasons
>> obviously, but allow me to observe that there's also something called
>> "principle of least surprise".
>>
>> In my case, it took me some time to figure out where a nasty bug was
>> hidden. Letting a bool be a int is quite a gotcha, no matter how hard
>> the benevolent dictator tries to convince me otherwise!
>>
>
> Try this (or its equivalent) in as many languages as possible:
>
> x = (1 > 2)
> x == 0
>
> You'll find that x (which has effectively been set to False, or its
> equivalent in any language) will be equal to zero in a very large
> number of languages. Thus, to an experienced programmer, it would
> actually be quite the opposite: having it NOT be a number would be the
> surprising thing!

I think the programmer's experience would have to have been rather
narrow to be surprised by x not being treated as a number.  I started
with Fortran, Lisp, Pascal and two variants of Algol so I started out
un-surprised by Boolean being a non-arithmetic type.  To be surprised by
x (above) /not/ being treated as a number, an experienced programmer
would have had to have avoided a lot of strictly typed languages.

I've just tried Scheme, Haskell, Common Lisp, Ada, Algol-68, go, ML,
Rust, Ruby, Java, Lua, Prolog and Fortran and they all either say "no
way!" or give false for x == 0.  Of course these are not random choices,
but it shows that Python's design is very far from universal.

But then this is not a numbers game, anyway.  A programmer need only to
have used one or two languages that are rather more strict about types
to find such a thing unsurprising in future.

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


Re: bool and int

2023-01-26 Thread 2QdxY4RzWzUUiLuE
On 2023-01-26 at 12:12:30 -0500,
Dino  wrote:

> On 1/25/2023 5:42 PM, Chris Angelico wrote:
> 
> > 
> > Try this (or its equivalent) in as many languages as possible:
> > 
> > x = (1 > 2)
> > x == 0
> > 
> > You'll find that x (which has effectively been set to False, or its
> > equivalent in any language) will be equal to zero in a very large
> > number of languages. Thus, to an experienced programmer, it would
> > actually be quite the opposite: having it NOT be a number would be the
> > surprising thing!
> 
> I thought I had already responded to this, but I can't see it. Weird.
> 
> Anyway, straight out of the Chrome DevTools console:
> 
> x = (1>2)
> false
> 
> x == 0
> true
> 
> typeof(x)
> 'boolean'
> 
> typeof(0)
> 'number'
> 
> typeof(x) == 'number'
> false
> 
> So, you are technically correct, but you can see that JavaScript - which
> comes with many gotchas - does not offer this particular one.

When you start a new language, try to start from the beginning.  Yes,
you know other languages, to varying degrees, and the language you are
learning is very likely similar, at least superficially, in some way or
another, to one of those other languages.  Use that existing knowledge
to the extent that it is useful; be prepared to forget everything you
know.

Python's choice of type hierarchy is not at all uncommon, and it's only
a gotcha if you come in with a predetermined idea of how certain things
"should" work.  I've already noted that writing FORTRAN in any language
is a meme.

For a completely different take on booleans, take a look at Python's
logical "and" and "or" operators (*not* the arithmetic "|" and "&"
operators), which only sometimes return an actual boolean value.  Then
compare them to the "any" and "all" builtins, which came along much
later.  Idiomatic Python uses the right tool for the job *in Python*,
whether or not that same tool is or isn;'t the right tool for the same
job in some other language.

Python is like Lisp in that it (Python) has strong dynamic typing.  From
my Common Lisp REPL:

CL-USER> (let ((x (< 1 2)))
   (cons x (type-of x)))
(T . BOOLEAN)

CL-USER> (let ((x (> 1 2)))
   (cons x (type-of x)))
(NIL . NULL)

In English, the canonical "true" value in Lisp is T, and its type is
BOOLEAN.  Likewise, the canonical "false" value in Lisp is NIL, and its
type is NULL.  Out of the box, Lisp will not convert T or NIL to a
number.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-26 Thread Dino

On 1/25/2023 5:42 PM, Chris Angelico wrote:



Try this (or its equivalent) in as many languages as possible:

x = (1 > 2)
x == 0

You'll find that x (which has effectively been set to False, or its
equivalent in any language) will be equal to zero in a very large
number of languages. Thus, to an experienced programmer, it would
actually be quite the opposite: having it NOT be a number would be the
surprising thing!


I thought I had already responded to this, but I can't see it. Weird.

Anyway, straight out of the Chrome DevTools console:

x = (1>2)
false

x == 0
true

typeof(x)
'boolean'

typeof(0)
'number'

typeof(x) == 'number'
false

So, you are technically correct, but you can see that JavaScript - which 
comes with many gotchas - does not offer this particular one.



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


Re: bool and int

2023-01-26 Thread Chris Angelico
On Fri, 27 Jan 2023 at 03:31, rbowman  wrote:
>
> On Thu, 26 Jan 2023 04:10:30 +1100, Chris Angelico wrote:
>
>
> > BASIC was like that too, although it (at least, the versions I used in
> > my childhood) didn't have "True" and "False", you just got the actual
> > values -1 and 0. They were the other way around compared to what you're
> > saying here though.
>
> I've see header files from people with boolean envy that are something
> like
>
> #define FALSE  0
> #define TRUE ~FALSE
>

Yeah, that's the same logic that BASIC uses: false is zero, and true
is the all-ones integer (which, interpreted as a two's complement
signed number, is -1).

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


Re: RE: bool and int

2023-01-26 Thread Dino



Wow. That was quite a message and an interesting read. Tempted to go 
deep and say what I agree and what I disagree with, but there are two 
issues: 1) time 2) I will soon be at a disadvantage discussing with 
people (you or others) who know more than me (which doesn't make them 
right necessarily, but certainly they'll have the upper-hand in a 
discussion).


Personally, in the first part of my career I got into the habit of 
learning things fast, sometimes superficially I confess, and then get 
stuff done hopefully within time and budget. Not the recommended 
approach if you need to build software for a nuclear plant. An OK 
approach (within reason) if you build websites or custom solutions for 
this or that organization and the budget is what it is. After all, 
technology moves sooo fast, and what we learn in detail today is bound 
to be old and possibly useless 5 years down the road.


Also, I argue that there is value in having familiarity with lots of 
different technologies (front-end and back-end) and knowing (or at 
lease, having a sense) of how they can all be made play together with an 
appreciation of the different challenges and benefits that each domain 
offers.


Anyway, everything is equivalent to a Turing machine and IA will screw 
everyone, including programmers, eventually.


Thanks again and have a great day

Dino

On 1/25/2023 9:14 PM, avi.e.gr...@gmail.com wrote:

Dino,

There is no such things as a "principle of least surprise" or if you insist
there is, I can nominate many more such "rules" such as "the principle of
get out of my way and let me do what I want!"

Computer languages with too many rules are sometimes next to unusable in
practical situations.

I am neither defending or attacking choices Python or other languages have
made. I merely observe and agree to use languages carefully and as
documented.


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


Re: bool and int

2023-01-26 Thread rbowman
On Thu, 26 Jan 2023 04:10:30 +1100, Chris Angelico wrote:


> BASIC was like that too, although it (at least, the versions I used in
> my childhood) didn't have "True" and "False", you just got the actual
> values -1 and 0. They were the other way around compared to what you're
> saying here though.

I've see header files from people with boolean envy that are something 
like

#define FALSE  0
#define TRUE ~FALSE

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


RE: bool and int

2023-01-26 Thread avi.e.gross
Gerard,

I am sure there is. I have been on many forums that discuss programming
languages and since nothing is perfect and people differ in many ways, there
is always grumbling and comparison.

If we all agreed and there was only one of something, I suspect we still
would complain and that is precisely why there are generally many variations
as others like their own ideas better.

Python remains a quite decent and useful language, warts and especially
imagined warts and all.

Avi

-Original Message-
From: Python-list  On
Behalf Of Weatherby,Gerard
Sent: Thursday, January 26, 2023 5:52 AM
To: python-list@python.org
Subject: Re: bool and int

I can't help but wonder if there exists some Java forum /mailing list going
on about how horrible Python is.

From: Python-list  on
behalf of rbowman 
Date: Wednesday, January 25, 2023 at 12:25 PM
To: python-list@python.org 
Subject: Re: bool and int
*** Attention: This is an external email. Use caution responding, opening
attachments or clicking on links. ***

On Wed, 25 Jan 2023 06:53:44 -0500, 2QdxY4RzWzUUiLuE wrote:


> They used Java at my last job (as in, the last job I had before I 
> retired), and it was absolutely awful, for any number of reasons, the 
> gymnastics (on many levels) required to support "primitive types" 
> being one of them.

My first brush with Java was around '98 when it was first becoming popular.
To familiarize myself with the AWT I decided to write a simple IDE for the
AVR microcontrollers. What a disaster. The UI wasn't bad but the
instructions for 8-bit processors require a lot of bit fiddling that was
extraordinarily difficult in Java.

Then they came out with Swing and the assumption if the app ran with glacial
slowness you should get a faster machine.

The company I work for has one Java app created around 2000 as a cross
platform solution as people moved to Windows. Originally it ran as an applet
but when that window was slammed shut it became increasingly unwieldy.

For what I'm developing today I used either .NET C# or Python3. The .NET
UI's on Linux aren't quite there yet but back end applications are fine.
PyQt (PySide actually. If there is a way to screw up commercial licensing Qt
will find it) is fine.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-
list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZHaXF58tWtyogy37PB6b9DH-gIN
gbVLuU64V4RovArDpnC5jjiQ$<https://urldefense.com/v3/__https:/mail.python.org
/mailman/listinfo/python-list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZH
aXF58tWtyogy37PB6b9DH-gINgbVLuU64V4RovArDpnC5jjiQ$>
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: bool and int

2023-01-26 Thread Chris Angelico
On Thu, 26 Jan 2023 at 21:53, Weatherby,Gerard  wrote:
>
> I can’t help but wonder if there exists some Java forum /mailing list going 
> on about how horrible Python is.

Try https://www.reddit.com/r/ProgrammerHumor/ for plenty of people
whining about how horrible Python is.

But along the way, you'll also find people whining about ChatGPT,
reposting memes with minor updates, and sharing the very best (worst?)
of dad jokes.

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


Flamebait (was: Re: bool and int)

2023-01-26 Thread 2QdxY4RzWzUUiLuE
On 2023-01-26 at 10:52:06 +,
"Weatherby,Gerard"  wrote:

> I can’t help but wonder if there exists some Java forum /mailing list
> going on about how horrible Python is.

Not some of them.  *All* of them.  Here's the summary:

  - Dynamic Typing causes defects and makes non-toy software projects
impossible.

  - Python is slow.

  - Significant Whitespace [insert pejorative here].

  - Python allows code to exist outside of methods, and methods to exist
outside of classes.  What's a function?

  - There is no backwards compatibility.

Many, if not most, languages are created as improvements over others,
because those others have serious flaws (whether those flaws are real or
perceived).  And even at that, the earliest languages were created
because cores, wires, and machine languages were extremely painful.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-26 Thread Weatherby,Gerard
I can’t help but wonder if there exists some Java forum /mailing list going on 
about how horrible Python is.

From: Python-list  on 
behalf of rbowman 
Date: Wednesday, January 25, 2023 at 12:25 PM
To: python-list@python.org 
Subject: Re: bool and int
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

On Wed, 25 Jan 2023 06:53:44 -0500, 2QdxY4RzWzUUiLuE wrote:


> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

My first brush with Java was around '98 when it was first becoming
popular. To familiarize myself with the AWT I decided to write a simple
IDE for the AVR microcontrollers. What a disaster. The UI wasn't bad but
the instructions for 8-bit processors require a lot of bit fiddling that
was extraordinarily difficult in Java.

Then they came out with Swing and the assumption if the app ran with
glacial slowness you should get a faster machine.

The company I work for has one Java app created around 2000 as a cross
platform solution as people moved to Windows. Originally it ran as an
applet but when that window was slammed shut it became increasingly
unwieldy.

For what I'm developing today I used either .NET C# or Python3. The .NET
UI's on Linux aren't quite there yet but back end applications are fine.
PyQt (PySide actually. If there is a way to screw up commercial licensing
Qt will find it) is fine.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZHaXF58tWtyogy37PB6b9DH-gINgbVLuU64V4RovArDpnC5jjiQ$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZHaXF58tWtyogy37PB6b9DH-gINgbVLuU64V4RovArDpnC5jjiQ$>
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: bool and int

2023-01-25 Thread avi.e.gross
Like Chris, I appreciate precision when it matters but since I am not
writing a textbook here, I often talk more informally.

There are many variations on now variables or objects are treated
differently in certain languages and when I said "STRONG" I simply meant a
sort of opposite to "WEAK". I could have used any number of silly words like
"mighty typing" and most would have been meaningless.

As pyt...@bladeshadow.org points out, from some perspectives, Python plays
quite fast and lose about what a variable can refer to. It is not a bug but
a proud feature of the language that you can easily do all kinds of things
with a kind of polymorphism (and I do NOT want to hear how I misused that
term in some technical way).

I have been reading about the ways Python keeps amending the ways you can
tell a program about the types a variable can hold and it gets quite amusing
in some ways. First, almost anything you write has to be IGNORED at
run-time. You are sort of just slowing down things and making your program
text longer, albeit the byte-compiled files may toss much of that. The main
purpose if of static type checkers like mpy to badger you until you come up
with just the right incantation and even then, your program can have plenty
of bugs and fail at run-time. There is a rich and seemingly ever-growing new
set of quasi-language features for specifying more closely what a function
expects as arguments and what it might return and some are potentially very
useful except for the minor detail that at runtime, your suggestion that
your function takes only objects that implement some protocol such as
defining __lt__  is absolutely ignored. All that mpy can do is static
testing of what you CLAIM you want. 

I am not making fun, of course, but in code I develop, I have negligible
interest in using the optional typing system and checking at first. It can
truly slow things down and some of the constraints can turn out to be too
tight if you later find the method you used excludes lots of things people
would use it on. I prefer having working code before I mark it up to be less
legible but in a way that finds some possible errors, or maybe mainly forces
me to change the markup to something else. And, if I really want my code to
CATCH errors when running, the beginning of many functions will have to
contain active tests such as checking if it is one of the types I want it to
support or implements some protocol, and if not, handle the error
gracefully. Such code can be way more detailed or correct than the type
system or may be way worse but it can also in some sense be a
self-documentation that some can read easier than trying to enforce strong
typing.

If I was working on a large project with many people and the organization
had all kinds of protocols and rules, then sure, you follow them or leave.
But at some point you may ask the dumb question of why they are using Python
at all, rather than a much "safer" language designed to minimize any ability
to make many errors as the program refuses to run until highly polished?


-Original Message-
From: Python-list  On
Behalf Of Python
Sent: Wednesday, January 25, 2023 10:06 PM
To: python-list@python.org
Subject: Re: bool and int

On Wed, Jan 25, 2023 at 01:01:24PM +1100, Chris Angelico wrote:
> On Wed, 25 Jan 2023 at 12:43,  wrote:
> > Python has a different philosophy than some other languages with 
> > strong typing. In some of those, you would not be allowed to add or 
> > multiply at random but would need to convert parts of your 
> > calculation to all be the same, such as a 32-bit integer. You could 
> > still do things like I mention above but only after consciously 
> > mapping your Boolean to an actual zero or one of the kind wanted.
> 
> Python is strongly dynamically typed. You may be thinking of "static 
> typing" rather than "strong typing" here,

You often insist on this but frankly it does not jibe with the definitions
of "strongly typed language" that I was taught or that I still see used
commonly, including in literature and on sites that aim to teach people
about computer science, which basically amount to:

1. A language whose variables are defined by type, and can only hold
   that type, typically but not necessarily compiled.
2. A language which strongly enforces restrictions on mixing or
   operating on, and/or implicitly converting different data types,
   with the implication that the structure of types is well-defined
   and rigid.

Python conforms to neither--its VARIABLES are normally untyped (though the
object data they hold obviously is).  Object instances can have new fields
added to them on the fly, willy-nilly, and Python allows for any object
which has an interface--or rather only the portion of interface you care
about in the moment--like the one it expects, to be used in a given context,
i.e. duck typing.  Us

Re: bool and int

2023-01-25 Thread Python
On Wed, Jan 25, 2023 at 01:01:24PM +1100, Chris Angelico wrote:
> On Wed, 25 Jan 2023 at 12:43,  wrote:
> > Python has a different philosophy than some other languages with strong
> > typing. In some of those, you would not be allowed to add or multiply at
> > random but would need to convert parts of your calculation to all be the
> > same, such as a 32-bit integer. You could still do things like I mention
> > above but only after consciously mapping your Boolean to an actual zero or
> > one of the kind wanted.
> 
> Python is strongly dynamically typed. You may be thinking of "static
> typing" rather than "strong typing" here,

You often insist on this but frankly it does not jibe with the
definitions of "strongly typed language" that I was taught or that I
still see used commonly, including in literature and on sites that aim
to teach people about computer science, which basically amount to:

1. A language whose variables are defined by type, and can only hold
   that type, typically but not necessarily compiled.
2. A language which strongly enforces restrictions on mixing or
   operating on, and/or implicitly converting different data types,
   with the implication that the structure of types is well-defined
   and rigid.

Python conforms to neither--its VARIABLES are normally untyped (though
the object data they hold obviously is).  Object instances can have
new fields added to them on the fly, willy-nilly, and Python allows
for any object which has an interface--or rather only the portion of
interface you care about in the moment--like the one it expects, to be
used in a given context, i.e. duck typing.  Useful properties (when
used carefully!) but not intuitively consistent with the idea of
"strong typing" and potentially dangerous if care is not taken.  When
YOU say that Python is strongly typed, you're using some other
definition--one that is perhaps technically correct, but seemingly
quite a lot of people in the field--including active students, college
professors, and seasoned professionsals--are unaware of...

The above usages are common and widespread, widely accepted--which is
inherently what makes word usages correct--and you very obviously know
full well what people mean when they use them; so "correcting" people
who use them seems rather unhelpful (certainly without detailing what
you think it means), inappropriate, and arguably just simply wrong.
It seems to serve no purpose other than to make communication harder,
and possibly to irritate people.  I would encourage you to consider
ceasing the practice, so as to not needlessly detract from the
otherwise usually good info you routinely provide...

And FWIW if you want some references, a google search will return
voluminous examples of people using the term as I described--from
acadamia to business--but here are just a few: 

https://www.cs.cornell.edu/courses/cs1130/2012sp/1130selfpaced/module1/module1part4/strongtyping.html
https://courses.yarrahills.vic.edu.au/moodle/mod/book/view.php?id=18778=28
https://www.oreilly.com/library/view/mastering-c-and/9781785884375/ch02s02.html
https://www.postgresql.org/docs/current/typeconv-overview.html
https://www.sciencedirect.com/topics/computer-science/strongly-typed-language
https://www.techtarget.com/whatis/definition/strongly-typed

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


RE: bool and int

2023-01-25 Thread avi.e.gross
Chris,

We generally agree albeit I have a question in python with the concept of
being truthy that results in either a Boolean value that boils down to 0 and
1 but in some cases may boil down to the last evaluated argument which
remains in a form that may not be either a Boolean or an integer. I think
this can happen with something like a short-circuit OR. 

Assuming I vaguely remember something real and actual, you can end up with a
variable holding either a Boolean or almost anything and should not use it
in an arithmetical capacity directly but perhaps only use bool(thing) ...

Avi

-Original Message-
From: Python-list  On
Behalf Of Chris Angelico
Sent: Wednesday, January 25, 2023 5:43 PM
To: python-list@python.org
Subject: Re: bool and int

On Thu, 26 Jan 2023 at 08:19, Dino  wrote:
>
> On 1/23/2023 11:22 PM, Dino wrote:
> >  >>> b = True
> >  >>> isinstance(b,bool)
> > True
> >  >>> isinstance(b,int)
> > True
> >  >>>
>
> ok, I read everything you guys wrote. Everyone's got their reasons 
> obviously, but allow me to observe that there's also something called 
> "principle of least surprise".
>
> In my case, it took me some time to figure out where a nasty bug was 
> hidden. Letting a bool be a int is quite a gotcha, no matter how hard 
> the benevolent dictator tries to convince me otherwise!
>

Try this (or its equivalent) in as many languages as possible:

x = (1 > 2)
x == 0

You'll find that x (which has effectively been set to False, or its
equivalent in any language) will be equal to zero in a very large number of
languages. Thus, to an experienced programmer, it would actually be quite
the opposite: having it NOT be a number would be the surprising thing!

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

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


RE: bool and int

2023-01-25 Thread avi.e.gross
t the numerical value in ASCII of the letter 'A' is one less
than of the next letter, 'B' and so on to 'Z'. They are contiguous but note
upper and lower cases letters are not back to back. So a piece of code that
says that if a character is between the numerical representation of 'A' and
halfway to the end, then add 13, and if it is higher, then add 13 and
subtract 26 (or obviously just subtract 13) to slide it circularly back, is
a valid way to do the permutation. But it involves adding what may seem to
be a 32-bit integer containing a number like 13 or 26  to an 8-bit character
resulting in an 8-bit character. Should that be illegal?

Well, in a sense it is illegal and you should be forced to create something
of type char that holds whatever 13 is, which probably is a
control-character and then either use operations that add or subtract 8-bit
items, OR you may widen the character to 32 bits and do the math with a
32-bit representation of 13/26 then narrow the result back into eight bits.
But lots of systems know how to automate this for you or even do it more
efficiently than you might have done on your own and do it differently on
different computer architectures. One goal of programming is to make life as
easy as possible for a programmer to be productive or make fewer errors and
so on.  Sometimes not being surprised is a valid goal. But a language like
Python may not lean the way you think. 

I once bashed my head at languages like PASCAL and even C as it often took
some work to do things like process a list of heterogenous contents
including perhaps some I may have no idea about at compile time. You
sometimes needed to convince the compiler to loosen up on rules such as by
declaring a union of several types. Python often does not care what anything
is and just passes it on. You, as the writer of a function may have to check
things like whether what you were passed is hashable or is of a numeric
type. You may simply take any argument(s) and coerce them into a new list
object to guarantee that whatever it is can now handle what lists supply.
This means you are often free to use the function with arguments that are
tuples or iterators and not just lists. Yes, someone using the function may
yet surprise you and you may want to write defensive code that checks
up-front and stops if called in an unexpected way. But you can write the
main function fairly quickly while assuming no surprises and bullet-proof it
later once it seems to work for what you want. The alternative is to keep
fighting with a compiler (or a static checker like mpy) before anything gets
done.

The surprise there is when they fire you from your job for not seeming to do
much for many months.

Having said that, I have had many surprises in many languages such as some
that help you so much that they handle 3 + "two" for you and return 5 or
maybe "five" rather than suggest you may have name an error and meant 3 +
int(english_number_to_string("two")) or perhaps "3" + "two" ...

I am surprised how this message got this long! Aaargh!





-Original Message-
From: Python-list  On
Behalf Of Dino
Sent: Wednesday, January 25, 2023 3:33 PM
To: python-list@python.org
Subject: Re: bool and int

On 1/23/2023 11:22 PM, Dino wrote:
>  >>> b = True
>  >>> isinstance(b,bool)
> True
>  >>> isinstance(b,int)
> True
>  >>>

ok, I read everything you guys wrote. Everyone's got their reasons
obviously, but allow me to observe that there's also something called
"principle of least surprise".

In my case, it took me some time to figure out where a nasty bug was hidden.
Letting a bool be a int is quite a gotcha, no matter how hard the benevolent
dictator tries to convince me otherwise!



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

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


Re: bool and int

2023-01-25 Thread Chris Angelico
On Thu, 26 Jan 2023 at 08:19, Dino  wrote:
>
> On 1/23/2023 11:22 PM, Dino wrote:
> >  >>> b = True
> >  >>> isinstance(b,bool)
> > True
> >  >>> isinstance(b,int)
> > True
> >  >>>
>
> ok, I read everything you guys wrote. Everyone's got their reasons
> obviously, but allow me to observe that there's also something called
> "principle of least surprise".
>
> In my case, it took me some time to figure out where a nasty bug was
> hidden. Letting a bool be a int is quite a gotcha, no matter how hard
> the benevolent dictator tries to convince me otherwise!
>

Try this (or its equivalent) in as many languages as possible:

x = (1 > 2)
x == 0

You'll find that x (which has effectively been set to False, or its
equivalent in any language) will be equal to zero in a very large
number of languages. Thus, to an experienced programmer, it would
actually be quite the opposite: having it NOT be a number would be the
surprising thing!

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


Re: bool and int

2023-01-25 Thread Dino

On 1/23/2023 11:22 PM, Dino wrote:

 >>> b = True
 >>> isinstance(b,bool)
True
 >>> isinstance(b,int)
True
 >>>


ok, I read everything you guys wrote. Everyone's got their reasons 
obviously, but allow me to observe that there's also something called 
"principle of least surprise".


In my case, it took me some time to figure out where a nasty bug was 
hidden. Letting a bool be a int is quite a gotcha, no matter how hard 
the benevolent dictator tries to convince me otherwise!




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


Re: bool and int

2023-01-25 Thread Dennis Lee Bieber
On Tue, 24 Jan 2023 20:16:31 -0500, Mike Baskin 
declaimed the following:

>Will all of you please stop sending me emails
>

Nobody is sending "you" emails deliberately (unless they have a poorly
[to me] set up client that sends to the list AND the person who wrote the
message they replied to) -- they are sending them to a Python mailing list.
The mailing list only sends them to /subscribed/ users.

Read the headers in the message for instructions...

List-Id: General discussion list for the Python programming language
 
List-Unsubscribe: ,
 
List-Archive: 
List-Post: 
List-Help: 
List-Subscribe: ,
 


-- 
Wulfraed Dennis Lee Bieber AF6VN
wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-25 Thread rbowman
On Wed, 25 Jan 2023 06:53:44 -0500, 2QdxY4RzWzUUiLuE wrote:


> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

My first brush with Java was around '98 when it was first becoming 
popular. To familiarize myself with the AWT I decided to write a simple 
IDE for the AVR microcontrollers. What a disaster. The UI wasn't bad but 
the instructions for 8-bit processors require a lot of bit fiddling that 
was extraordinarily difficult in Java.

Then they came out with Swing and the assumption if the app ran with 
glacial slowness you should get a faster machine.

The company I work for has one Java app created around 2000 as a cross 
platform solution as people moved to Windows. Originally it ran as an 
applet but when that window was slammed shut it became increasingly 
unwieldy.

For what I'm developing today I used either .NET C# or Python3. The .NET 
UI's on Linux aren't quite there yet but back end applications are fine. 
PyQt (PySide actually. If there is a way to screw up commercial licensing 
Qt will find it) is fine.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-25 Thread Chris Angelico
On Thu, 26 Jan 2023 at 03:19, <2qdxy4rzwzuui...@potatochowder.com> wrote:
> > Strongly disagree. There is PLENTY of practical value in using
> > booleans as numbers. This is nothing to do with counting bytes, and
> > everything to do with how useful it is in practice.
>
> IMO, the difference in readability between
>
> autothrust_last_dv *= AT_mode == AT.Idle;
>
> and
>
> if(AT_mode != AT.Idle)
> autothrust_last_dv = 0;
>
> outweighs the practicality, whether C, C#, Java, or Python (ignoring the
> insignificant differences in syntax).

Yeah, that example was completely synthetic and not really a good
showcase. But what often comes up is either multiplying a string by a
boolean (equivalent to "have this string if this is true") or
subscripting something with a boolean.

> I could argue that the only reason the first one is readable at all is
> that we've both been exposed to languages where fanatics assume that
> True is 1 and False is 0.

I'm fine with any definition as long as it's dependable.

> I've also written low-level code with
> hardware fanatics who insist that True is 0 and False is -1 (or 255,
> depending on how much math they know).

BASIC was like that too, although it (at least, the versions I used in
my childhood) didn't have "True" and "False", you just got the actual
values -1 and 0. They were the other way around compared to what
you're saying here though.

> In a posix shell script (or a
> program that knows it might be run inside such a script), 0 is "true"
> and non-zero is "false."

And that's a consequence of a system wherein there is only one concept
of "success", but many concepts of "failure". Whoever devised that
system was clearly a pessimist :)

> My point here is that you have to understand
> how to work within whatever environment you're using, and that future
> programmers (and future you!)  will have to deal with your choices
> regardless of their background, biases, and preferences.

That's always the case, though.

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


Re: bool and int

2023-01-25 Thread 2QdxY4RzWzUUiLuE
On 2023-01-25 at 23:11:37 +1100,
Chris Angelico  wrote:

> On Wed, 25 Jan 2023 at 22:55, <2qdxy4rzwzuui...@potatochowder.com> wrote:

> > So, I think what you're trying to say is that you prefer the razor sharp
> > quality of truthiness to the zen of explicit being better than implicit.
> 
> Not sure what you mean here. If you want to bring this back to the Zen
> of Python, I would reference "practicality beats purity". We can do
> arithmetic on integers and floats without having to explicitly cast
> one to the other, because there's really no point in distinguishing
> them. We can do that with booleans and other types, too.

My point was that we all have our own preferences and biases, and in
this case, I think you and I lean in opposite directions, and Python is
big enough for both of us.

> > To bring this back to Python (sorry), blurring the line between booleans
> > and integers is an old machine language trick, born of the days when we
> > measured memory in bytes (and large sums of cash!) rather than gigs[0].
> > In Python3, there's no more reason to use a boolean value as integer
> > (whether to accumulate values or to test a value against zero) as there
> > is to use a string (e.g., from an HTML form) as an integer.
> 
> Strongly disagree. There is PLENTY of practical value in using
> booleans as numbers. This is nothing to do with counting bytes, and
> everything to do with how useful it is in practice.

IMO, the difference in readability between

autothrust_last_dv *= AT_mode == AT.Idle;

and

if(AT_mode != AT.Idle)
autothrust_last_dv = 0;

outweighs the practicality, whether C, C#, Java, or Python (ignoring the
insignificant differences in syntax).

Maintainability, too:  as soon as there's something else to do when
AT_mode isn't AT.Idle, I'm going to rewrite the first one as the second
one anyway.  (No, I won't mess up the braces.)

I could argue that the only reason the first one is readable at all is
that we've both been exposed to languages where fanatics assume that
True is 1 and False is 0.  I've also written low-level code with
hardware fanatics who insist that True is 0 and False is -1 (or 255,
depending on how much math they know).  In a posix shell script (or a
program that knows it might be run inside such a script), 0 is "true"
and non-zero is "false."  My point here is that you have to understand
how to work within whatever environment you're using, and that future
programmers (and future you!)  will have to deal with your choices
regardless of their background, biases, and preferences.

> C# is a pain to work with because it fails on these points of
> practicality. I'm morbidly curious as to how C# fanatics justify this
> sort of thing, given that so many languages just DTRT without needing
> to be told.

They say that Perl is practical.  ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-25 Thread Thomas Passin

On 1/25/2023 6:53 AM, 2qdxy4rzwzuui...@potatochowder.com wrote:

They used Java at my last job (as in, the last job I had before I
retired), and it was absolutely awful, for any number of reasons, the
gymnastics (on many levels) required to support "primitive types" being
one of them.


In my one serious java program, a Tomcat application, I use a small 
amount of Java for the servlets and startup filters, and Jython for the 
heart of the computing.  Thank goodness for Jython!

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


Re: bool and int

2023-01-25 Thread Chris Angelico
On Wed, 25 Jan 2023 at 22:55, <2qdxy4rzwzuui...@potatochowder.com> wrote:
>
> On 2023-01-25 at 12:14:50 +1100,
> Chris Angelico  wrote:
>
> > On Wed, 25 Jan 2023 at 10:32, <2qdxy4rzwzuui...@potatochowder.com> wrote:
>
> > > The usual complaint is that some people write FORTRAN no matter what
> > > language they're actually using.  Are you writing Python in C#?  ;-)
>
> > But the way I have to write it in C# is a messed-up version of C:
>
> There's your problem:  C# isn't C, it's Java.  Java looks like C, too,
> but it isn't C, either.
>
> > So the problem isn't that I'm trying to write Python in C#, but that
> > I'm trying to write code that would work on pretty much *any other
> > C-family language*, but doesn't work on C#. I could use those
> > techniques in plenty of C-derived and C-inspired languages, but no
> > not in C#, despite looking very much C-inspired. Unfortunately the
> > truth is that C# is not *actually* C-inspired; it's really Microsoft
> > Java, so it has all the stupidities of Java:
>
> There.  Even ChrisA agrees with me.  ;-)
>
> So, I think what you're trying to say is that you prefer the razor sharp
> quality of truthiness to the zen of explicit being better than implicit.

Not sure what you mean here. If you want to bring this back to the Zen
of Python, I would reference "practicality beats purity". We can do
arithmetic on integers and floats without having to explicitly cast
one to the other, because there's really no point in distinguishing
them. We can do that with booleans and other types, too.

> To bring this back to Python (sorry), blurring the line between booleans
> and integers is an old machine language trick, born of the days when we
> measured memory in bytes (and large sums of cash!) rather than gigs[0].
> In Python3, there's no more reason to use a boolean value as integer
> (whether to accumulate values or to test a value against zero) as there
> is to use a string (e.g., from an HTML form) as an integer.

Strongly disagree. There is PLENTY of practical value in using
booleans as numbers. This is nothing to do with counting bytes, and
everything to do with how useful it is in practice.

> > But this is hardly a Python-versus-C# thing; it's Java versus most of
> > the rest of the world, and C# feigns to be part of the C style while
> > retaining the limitations of Java.
>
> IMO, the problem started when Java tried to be too much like C to
> attract (or should I say "trap"?) C developers.

Maybe. No idea. In any case, Java's restrictiveness is VERY different
from the way Python works (for instance, operator overloading, the way
strings are handled, etc), and I don't think people here want the
shackles of Java.

> > (My apologies if the Java entries look synthetic. It's because they
> > are, and that's a consequence of me not having ANY reason to write
> > Java code in, like, ever. In fact, I had to go and install a JDK just
> > to confirm that Java really did have these limitations.)
>
> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

Yeah. "Primitive types" being different from "boxed types" is an
unnecessary and arbitrary distinction, like between types and classes,
or old-style classes and those that subclass object. Neither is needed
in modern Python, neither is beneficial.

Keeping bool as a subclass of int has never been in dispute. Nor has
the treatment of other types in a boolean context. I can't find
anything in the Python 3000 proposals that ever even suggested
changing either; the best I can find is this reference in PEP 285
which rejected the notions:

"""
Should we strive to eliminate non-Boolean operations on bools in the
future, through suitable warnings, so that for example True+1 would
eventually (in Python 3000) be illegal?

=> No.

Should we strive to require that Boolean operations (like “if”, “and”,
“not”) have a bool as an argument in the future, so that for example
“if []:” would become illegal and would have to be written as “if
bool([]):” ???

=> No!!!
"""

See: https://peps.python.org/pep-0285/

C# is a pain to work with because it fails on these points of
practicality. I'm morbidly curious as to how C# fanatics justify this
sort of thing, given that so many languages just DTRT without needing
to be told.

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


Re: bool and int

2023-01-25 Thread 2QdxY4RzWzUUiLuE
On 2023-01-25 at 12:14:50 +1100,
Chris Angelico  wrote:

> On Wed, 25 Jan 2023 at 10:32, <2qdxy4rzwzuui...@potatochowder.com> wrote:

> > The usual complaint is that some people write FORTRAN no matter what
> > language they're actually using.  Are you writing Python in C#?  ;-)

> But the way I have to write it in C# is a messed-up version of C:

There's your problem:  C# isn't C, it's Java.  Java looks like C, too,
but it isn't C, either.

> So the problem isn't that I'm trying to write Python in C#, but that
> I'm trying to write code that would work on pretty much *any other
> C-family language*, but doesn't work on C#. I could use those
> techniques in plenty of C-derived and C-inspired languages, but no
> not in C#, despite looking very much C-inspired. Unfortunately the
> truth is that C# is not *actually* C-inspired; it's really Microsoft
> Java, so it has all the stupidities of Java:

There.  Even ChrisA agrees with me.  ;-)

So, I think what you're trying to say is that you prefer the razor sharp
quality of truthiness to the zen of explicit being better than implicit.

To bring this back to Python (sorry), blurring the line between booleans
and integers is an old machine language trick, born of the days when we
measured memory in bytes (and large sums of cash!) rather than gigs[0].
In Python3, there's no more reason to use a boolean value as integer
(whether to accumulate values or to test a value against zero) as there
is to use a string (e.g., from an HTML form) as an integer.

[0] I remember meetings where the agenda was to allocate memory (yes, at
design time) for a particular value, and the answer was along the lines
of "you can have these five bits, and this would have taken a lot less
time had you told us sooner that you needed that value to persist across
input messages."

> But this is hardly a Python-versus-C# thing; it's Java versus most of
> the rest of the world, and C# feigns to be part of the C style while
> retaining the limitations of Java.

IMO, the problem started when Java tried to be too much like C to
attract (or should I say "trap"?) C developers.

> (My apologies if the Java entries look synthetic. It's because they
> are, and that's a consequence of me not having ANY reason to write
> Java code in, like, ever. In fact, I had to go and install a JDK just
> to confirm that Java really did have these limitations.)

They used Java at my last job (as in, the last job I had before I
retired), and it was absolutely awful, for any number of reasons, the
gymnastics (on many levels) required to support "primitive types" being
one of them.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-24 Thread rbowman
On Wed, 25 Jan 2023 12:14:50 +1100, Chris Angelico wrote:


> So the problem isn't that I'm trying to write Python in C#, but that I'm
> trying to write code that would work on pretty much *any other C-family
> language*, but doesn't work on C#. I could use those techniques in
> plenty of C-derived and C-inspired languages, but no not in C#,
> despite looking very much C-inspired. Unfortunately the truth is that C#
> is not *actually* C-inspired; it's really Microsoft Java, so it has all
> the stupidities of Java:

I have the installation media for Visual J++ around here someplace. It 
lasted for a few years before Sun sued for non-compliance. There 
definitely is some of its DNA in C#. 

I prefer C# to C++ but it does have annoyances. It's only a warning that 
can be pragma'd but

string foo;  

complaining that foo may be null unless you shut it up with

string? foo;

can be frustrating. It has a germ of a good idea for structs (classes) 
where some of the members are optional. 

The bool hoops definitely are another sore point after a few decades of C.

I can switch gears for Python but the first day or two is painful. I was 
getting a bit frustrated until I remembered the range() thing. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-24 Thread Grant Edwards
On 2023-01-25, Mike Baskin via Python-list  wrote:

> Will all of you please stop sending me emails

Oh dear.

You might want to try unsubscribing from the list.

Telling everybody to stop using the mailing list and newsgroup is a bit silly.

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


Re: bool and int

2023-01-24 Thread Chris Angelico
On Wed, 25 Jan 2023 at 12:43,  wrote:
> Python has a different philosophy than some other languages with strong
> typing. In some of those, you would not be allowed to add or multiply at
> random but would need to convert parts of your calculation to all be the
> same, such as a 32-bit integer. You could still do things like I mention
> above but only after consciously mapping your Boolean to an actual zero or
> one of the kind wanted.

Python is strongly dynamically typed. You may be thinking of "static
typing" rather than "strong typing" here, and there are plenty of
strongly statically typed languages that allow you to do arithmetic on
booleans (with them usually behaving as if False is 0 and True is 1,
although not always).

> I worry a tad more about the other direction where something like an integer
> containing a number like 12 is used in a context where it gets downgraded to
> a True/False and later may inadvertently be used as a "1" as the conversion
> is not anticipated. There is data loss there more than in the case of a
> Boolean becoming a 1.

Well, yes, but that's no different from a float like 6.25 getting
downgraded to an integer 6. There's a reason that most languages
upcast silently but don't downcast without being asked to.

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


RE: bool and int

2023-01-24 Thread avi.e.gross
Python yet again is being asked why something is the way it is and not as
someone insists it should be. It is a tool to be used the way it SAYS it
works so the bug is perhaps in the user and their expectations.

It is what it is and would break lots of things if changed without much
thought. Every other language I know has similar detractors asking why it is
the way it is.

A useful example where the use of Booleans as 0/1 is commonly used is to
find how many of something satisfy some criteria, such as how many items in
a list are numbers greater than 65 representing test scores that "passed".
It could also be a numpy type of array or a column of a data.frame and so
on. The common method is to create a Boolean data structure (often
implicitly) that is then viewed as a bunch of 0's and 1's and you can count
them to see how many are True (meaning they qualify) or calculate a
percentage simply by taking a mean of the 0/1 values.

There are other ways, but some also use sums of Booleans to calculate things
like any() or all() and I am sure many other things. Yes, all these can be
done another way if Booleans were not allowed to be viewed as very small
integers.

So only use a Boolean in relatively pure situations where arithmetic as a
zero or one is meaningful. In other places, maybe don't. The reality though
is that if you have 10 apples and you get another one if you flip a coin and
it lands on heads. Then 10 + Boolean would indeed be 11. If you have five
losing flips (or tickets or whatever) then 5 * Boolean indeed is a zero. 

Python has a different philosophy than some other languages with strong
typing. In some of those, you would not be allowed to add or multiply at
random but would need to convert parts of your calculation to all be the
same, such as a 32-bit integer. You could still do things like I mention
above but only after consciously mapping your Boolean to an actual zero or
one of the kind wanted. 

I worry a tad more about the other direction where something like an integer
containing a number like 12 is used in a context where it gets downgraded to
a True/False and later may inadvertently be used as a "1" as the conversion
is not anticipated. There is data loss there more than in the case of a
Boolean becoming a 1.

-Original Message-
From: Python-list  On
Behalf Of 2qdxy4rzwzuui...@potatochowder.com
Sent: Tuesday, January 24, 2023 6:31 PM
To: python-list@python.org
Subject: Re: bool and int

On 2023-01-25 at 08:58:06 +1100,
Chris Angelico  wrote:

> On Wed, 25 Jan 2023 at 08:22, MRAB  wrote:
> > For backwards compatibility, bool was made a subclass of int.
> 
> Plus, it's really REALLY handy in quite a lot of situations.
> 
> > > C# is pickier, which I guess is a good thing.
> >
> 
> Nope, not a good thing. Actually a highly frustrating thing on those 
> occasions when I have to write C# code.

The usual complaint is that some people write FORTRAN no matter what
language they're actually using.  Are you writing Python in C#?  ;-)

There's a sweet spot somewhere that includes dynamic typing, high powered
global type inference and optimization systems, a thriving community, and a
metric [boatload] of rock solid libraries.

And an alomost fanatical devotion to the Pope.  :-/
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: bool and int

2023-01-24 Thread David
On Wed, 25 Jan 2023 at 12:19, Mike Baskin via Python-list
 wrote:

> Will all of you please stop sending me emails

Hi. We don't have the power to do that.
Because this is a public list, which works by
people adding and removing themselves.
You, or perhaps someone messing with you,
added your email address to it.
So you have to remove yourself. The link to do
that is at the bottom of every message. See here:
  https://mail.python.org/mailman/listinfo/python-list
Go to the bottom, enter your email address, click
the button next to it named "Unsubscribe or edit options"
and follow the instructions.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-24 Thread Chris Angelico
On Wed, 25 Jan 2023 at 12:20, Mike Baskin via Python-list
 wrote:
>
> Will all of you please stop sending me emails

Learn to manage your own mailing list subscription. HINT: Look at the
*ENTIRE* email, not just the bit up the top that makes you angry.

> Sent from my iPhone

Ahh, I see the problem here. You probably can't even read the entire
email. Good luck. If you can find the link, you can unsubscribe from
the mailing list, although you still probably won't be able to stop
yourself from being a constant advertisement bragging "Oh I am the
greatest, I use default iPhone apps, ain't I awesome".

Forgive me for thinking that it's utterly lame. There's probably a
good reason for bragging about iPhone usage on EVERY SINGLE EMAIL, but
I've just never seen it.

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


Re: bool and int

2023-01-24 Thread Mike Baskin via Python-list
Will all of you please stop sending me emails

Sent from my iPhone

> On Jan 24, 2023, at 2:59 PM, rbowman  wrote:
> 
> On Mon, 23 Jan 2023 23:22:00 -0500, Dino wrote:
> 
>> $ python Python 3.8.10 (default, Mar 15 2022, 12:22:08)
>> [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license"
>> for more information.
> b = True isinstance(b,bool)
>> True
> isinstance(b,int)
>> True
> 
> 
>> WTF!
> 
> 
 b = True
 isinstance(b, bool)
> True
 isinstance(b, int)
> True
 c = b + 10
 print(c)
> 11
 b = False
 c = b + 10
 print(c)
> 10
> 
> 
> bool is a subtype of integer. I never dug that deep into Python's guts but 
> I assume it goes back to boolean being an afterthought in C. Some people 
> fancy it up with #defines but I always use int.  0 is false, anything else 
> is true.
> 
> C# is pickier, which I guess is a good thing. 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


Re: bool and int

2023-01-24 Thread Chris Angelico
On Wed, 25 Jan 2023 at 10:32, <2qdxy4rzwzuui...@potatochowder.com> wrote:
>
> On 2023-01-25 at 08:58:06 +1100,
> Chris Angelico  wrote:
>
> > On Wed, 25 Jan 2023 at 08:22, MRAB  wrote:
> > > For backwards compatibility, bool was made a subclass of int.
> >
> > Plus, it's really REALLY handy in quite a lot of situations.
> >
> > > > C# is pickier, which I guess is a good thing.
> > >
> >
> > Nope, not a good thing. Actually a highly frustrating thing on those
> > occasions when I have to write C# code.
>
> The usual complaint is that some people write FORTRAN no matter what
> language they're actually using.  Are you writing Python in C#?  ;-)

Well, let's see. If I were writing C code, I would write:

if (state & PRELAUNCH)

If I were writing Python, it would probably be very different, but it
depends on the API. Could be:

if "PreLaunch" in state:

But the way I have to write it in C# is a messed-up version of C:

if ((state & StartState.PreLaunch) > 0) {

because bool and int are fundamentally different. Using the C style results in:

VelocimeterModule.cs(37,8): error CS0029: Cannot implicitly convert
type `PartModule.StartState' to `bool'

Here's another example. If I were writing C, I would write:

if (TimeWarp_CurrentRateIndex)

Python?

if TimeWarp.CurrentRateIndex:

C#?

if (TimeWarp.CurrentRateIndex > 0)

And, again, if I do it C style, I get:

VelocimeterModule.cs(261,17): error CS0029: Cannot implicitly convert
type `int' to `bool'

I'm pretty sure I've had a case where I wanted to use a boolean in an
arithmetic context, too, but it's less obvious from the final code, so
I can't give an example. So this is synthetic:

autothrust_last_dv *= AT_mode == AT.Idle;

VelocimeterModule.cs(252,4): error CS0019: Operator `*=' cannot be
applied to operands of type `double' and `bool'

So the problem isn't that I'm trying to write Python in C#, but that
I'm trying to write code that would work on pretty much *any other
C-family language*, but doesn't work on C#. I could use those
techniques in plenty of C-derived and C-inspired languages, but no
not in C#, despite looking very much C-inspired. Unfortunately the
truth is that C# is not *actually* C-inspired; it's really Microsoft
Java, so it has all the stupidities of Java:

int x = 3 + (args.length > 1);
test.java:4: error: bad operand types for binary operator '+'

if (args.length) System.out.println("There are args!");
test.java:6: error: incompatible types: int cannot be converted to boolean

But this is hardly a Python-versus-C# thing; it's Java versus most of
the rest of the world, and C# feigns to be part of the C style while
retaining the limitations of Java.

(My apologies if the Java entries look synthetic. It's because they
are, and that's a consequence of me not having ANY reason to write
Java code in, like, ever. In fact, I had to go and install a JDK just
to confirm that Java really did have these limitations.)

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


Re: bool and int

2023-01-24 Thread 2QdxY4RzWzUUiLuE
On 2023-01-25 at 08:58:06 +1100,
Chris Angelico  wrote:

> On Wed, 25 Jan 2023 at 08:22, MRAB  wrote:
> > For backwards compatibility, bool was made a subclass of int.
> 
> Plus, it's really REALLY handy in quite a lot of situations.
> 
> > > C# is pickier, which I guess is a good thing.
> >
> 
> Nope, not a good thing. Actually a highly frustrating thing on those
> occasions when I have to write C# code.

The usual complaint is that some people write FORTRAN no matter what
language they're actually using.  Are you writing Python in C#?  ;-)

There's a sweet spot somewhere that includes dynamic typing, high
powered global type inference and optimization systems, a thriving
community, and a metric [boatload] of rock solid libraries.

And an alomost fanatical devotion to the Pope.  :-/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-24 Thread Chris Angelico
On Wed, 25 Jan 2023 at 08:22, MRAB  wrote:
> For backwards compatibility, bool was made a subclass of int.

Plus, it's really REALLY handy in quite a lot of situations.

> > C# is pickier, which I guess is a good thing.
>

Nope, not a good thing. Actually a highly frustrating thing on those
occasions when I have to write C# code.

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


Re: bool and int

2023-01-24 Thread MRAB

On 2023-01-24 20:32, Weatherby,Gerard wrote:

https://peps.python.org/pep-0285/

From: Python-list  on behalf of 
rbowman 
Date: Tuesday, January 24, 2023 at 3:01 PM
To: python-list@python.org 
Subject: Re: bool and int


bool is a subtype of integer. I never dug that deep into Python's guts but
I assume it goes back to boolean being an afterthought in C. Some people
fancy it up with #defines but I always use int.  0 is false, anything else
is true.

bool was introduced early in Python 2. Before then 0 and 1 were used for 
false and true, like in C, which also gained 'false' and 'true'.


For backwards compatibility, bool was made a subclass of int.


C# is pickier, which I guess is a good thing.


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


Re: bool and int

2023-01-24 Thread Weatherby,Gerard
https://peps.python.org/pep-0285/

From: Python-list  on 
behalf of rbowman 
Date: Tuesday, January 24, 2023 at 3:01 PM
To: python-list@python.org 
Subject: Re: bool and int


bool is a subtype of integer. I never dug that deep into Python's guts but
I assume it goes back to boolean being an afterthought in C. Some people
fancy it up with #defines but I always use int.  0 is false, anything else
is true.

C# is pickier, which I guess is a good thing.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!hdxuMNsprOXvH5ouxGfbGLLq6wuXs-_gOESRVYUxDsHYCmlrpv9ru-WYMziYU4FRdum02bS6DfRnNDnCNQ$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!hdxuMNsprOXvH5ouxGfbGLLq6wuXs-_gOESRVYUxDsHYCmlrpv9ru-WYMziYU4FRdum02bS6DfRnNDnCNQ$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bool and int

2023-01-24 Thread Weatherby,Gerard
Booleans work exactly the way the language documentation says they work:

Booleans (bool<https://docs.python.org/3/library/functions.html#bool>)
These represent the truth values False and True. The two objects representing 
the values False and True are the only Boolean objects. The Boolean type is a 
subtype of the integer type, and Boolean values behave like the values 0 and 1, 
respectively, in almost all contexts, the exception being that when converted 
to a string, the strings "False" or "True"are returned, respectively.

https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

From: Python-list  on 
behalf of Dino 
Date: Tuesday, January 24, 2023 at 3:04 PM
To: python-list@python.org 
Subject: bool and int
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
 >>> b = True
 >>> isinstance(b,bool)
True
 >>> isinstance(b,int)
True
 >>>

WTF!

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jPbvUX9ZXFGYt-q850YI6aQ7ET7BwbF-LIT4XT7MKKwF9OSOgqnaHdM4MbQ7p6YaRCYJYXZ4-XiT3Sko$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jPbvUX9ZXFGYt-q850YI6aQ7ET7BwbF-LIT4XT7MKKwF9OSOgqnaHdM4MbQ7p6YaRCYJYXZ4-XiT3Sko$>
-- 
https://mail.python.org/mailman/listinfo/python-list


bool and int

2023-01-24 Thread Dino



$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b = True
>>> isinstance(b,bool)
True
>>> isinstance(b,int)
True
>>>

WTF!

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


Re: bool and int

2023-01-24 Thread rbowman
On Mon, 23 Jan 2023 23:22:00 -0500, Dino wrote:

> $ python Python 3.8.10 (default, Mar 15 2022, 12:22:08)
> [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license"
> for more information.
>  >>> b = True isinstance(b,bool)
> True
>  >>> isinstance(b,int)
> True
>  >>>
>  >>>
> WTF!


>>> b = True
>>> isinstance(b, bool)
True
>>> isinstance(b, int)
True
>>> c = b + 10
>>> print(c)
11
>>> b = False
>>> c = b + 10
>>> print(c)
10


bool is a subtype of integer. I never dug that deep into Python's guts but 
I assume it goes back to boolean being an afterthought in C. Some people 
fancy it up with #defines but I always use int.  0 is false, anything else 
is true.

C# is pickier, which I guess is a good thing. 
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread SilentGhost

New submission from SilentGhost michael.mischurow+...@gmail.com:

According to docs
(http://docs.python.org/3.1/reference/datamodel.html#object.__bool__)
__bool__ can return 1 or 0 instead of True or False.
However, when I ran the following code:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit
(Intel)] on win32
 class Spam():
def __bool__(self):
return 1


 if Spam():
print('ham')

I got the following error:

Traceback (most recent call last):
  File pyshell#72, line 1, in module
if Spam():
TypeError: __bool__ should return bool or int, returned int

So, do I misunderstand the docs or is it an error in them?

--
assignee: georg.brandl
components: Documentation, Interpreter Core
messages: 90181
nosy: SilentGhost, georg.brandl
severity: normal
status: open
title: TypeError: __bool__ should return bool or int, returned int
type: behavior
versions: Python 3.1

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread Antoine Pitrou

Antoine Pitrou pit...@free.fr added the comment:

It's not only the docs, the error message is self-contradictory as well.

--
assignee: georg.brandl - 
nosy: +pitrou
priority:  - normal
stage:  - needs patch
versions: +Python 3.2

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread Amaury Forgeot d'Arc

Amaury Forgeot d'Arc amaur...@gmail.com added the comment:

Probably a misguided merge. Here is a patch that updates the error 
message, and the documentation.

--
keywords: +needs review, patch
nosy: +amaury.forgeotdarc
Added file: http://bugs.python.org/file14460/bool.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread Amaury Forgeot d'Arc

Changes by Amaury Forgeot d'Arc amaur...@gmail.com:


--
stage: needs patch - patch review

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread Eric Smith

Eric Smith e...@trueblade.com added the comment:

The patch looks good to me. In particular, removing the test for
using_len looks correct.

The assignment of result = -1 after PyErr_Format isn't needed, but
doesn't hurt (and it was already there, anyway).

--
keywords:  -needs review
nosy: +eric.smith

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue6428] TypeError: __bool__ should return bool or int, returned int

2009-07-06 Thread Amaury Forgeot d'Arc

Amaury Forgeot d'Arc amaur...@gmail.com added the comment:

fixed in r73868 (py3k) and r73869 (3.1)
Thanks for the report!

--
resolution:  - fixed
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6428
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



C++ to python with boost.python: Exposing virtual bool operator()(int )=0

2006-03-29 Thread Pedro
Hello pythonians! ;-D ,

I have a little problem when I expose (assisted by boost.python) classes 
with virtual functions, specially with operator().
In the C++ code below I test two different implementations of a member 
function of A that
takes as an argument the abstract class Base (see Option 1 / Option 2):
- Both compile without problems
- Only the second works in python (see python program below).

It seems like if the problem is in the way I expose operator()... but I 
do not understand it very well
Any clue about why this is happening?I would appreciate any comment on this.
Thank you very much in advance. :-D

Pedro.


//...
// C++ code..
//...
#include boost/python.hpp
#define OPTION1
//#undef OPTION1

struct Base
{
virtual ~Base() {}
virtual int f() = 0;// Like in 
Boost.python tutorial
virtual int g(int) = 0;   // With 1 argument
virtual bool operator()(int ii) =0;//  __call__ - type function
};

class A{
private:
int v_;
public: A(int v): v_(v){}
   #ifdef OPTION1
/* Option 1 */ int fun(Base c) const { return 
c(v_)?(c.g(v_)+c.f()):33; }
#else
/* Option 2 */ int fun(Base c) const { return (c.g(v_)+c.f()); }
#endif
};

//:::BOOST::PYTHON in 
action:::
using namespace boost::python;

struct BaseWrap : Base, wrapperBase
{
int f(){return callint(this-get_override(f).ptr());}
int g(int ii){return callint(this-get_override(g).ptr(),ii);}
bool operator()(int ii){ return 
callbool(this-get_override(operator()).ptr(),ii);}
};

BOOST_PYTHON_MODULE(test2py)
{
class_A(A,initint())
.def(fun,A::fun);

class_BaseWrap, boost::noncopyable(Base)
.def(f, pure_virtual(Base::f))
.def(g, pure_virtual(Base::g))
.def(__call__, pure_virtual(Base::operator())) ;
};


//...
// Python code...
//...

from test2py import *


## Extension of C++ class in python
class Derived(Base):
def f(self):
return 44
def g(self,n):
return n
def __call__(self, v):
return (v23)


d=Derived()
print d.f()
print d.g(3)
print is 2023 and 2423, d(20), d(24)


a=A(20)
print a.fun(d)

b=A(24)
print b.fun(d)


//..
// Executing Python code..
//.


With Option 1 IS NOT WORKING!!
...
int fun(Base c) const { return c(v_)?(c.g(v_)+c.f()):33; }
...

 
44
3
is 2023 and 2423 True False
Traceback (most recent call last):
  File d:\My_Documents\src\pysource\test.py, line 29, in ?
print a.fun(d)
TypeError: 'NoneType' object is not callable


With Option 2 IS WORKING!!
...
int fun(Base c) const { return (c.g(v_)+c.f()); }
...

 
44
3
is 2023 and 2423 True False
64
68
 


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