Weak Type Ability for Python

Alan Gauld learn2program at gmail.com
Thu Apr 13 20:13:56 EDT 2023


On 14/04/2023 00:25, avi.e.gross at gmail.com wrote:

> Is there any concept in Python of storing information in some way, such as
> text, and implementing various ideas or interfaces so that you can query if
> the contents are willing and able to be viewed in one of many other ways?

Are you talking about something like a C union type (or a Pascal
variant record)? I'm not aware of any such feature in Python but
have often thought it would be a nice to have for the rare cases
where its useful.

> Or it may be storing text in some format but the object is willing to
> transform the text into one of several other formats when needed. The text
> may also have attributes such as whether it is in English or Hungarian or is
> mixed-language.

Or are you meaning something like an extension to the
struct module that can interpret a bytestring in any way
defined by a format string?

> basis. But do some languages have some support within the language itself?

The closest to what you seem to mean is, I think, the C union
type, at least in my experience. But you have to define all
the ways you can interpret the type up front in the type
definition.

> My reason for asking, is based on the discussion. If I want to use plus with
> an integer and a string, it may be reasonable for the interpreter to ask one
> or the other operand if they are able to be seen another way.

You can achieve that in a slightly different way in Tcl which
allows you to redefine all the operators (commands in Tcl-speak)
in the language so redefining plus is easy. Doing it based on
type is more tricky but doable.

> Unfortunately, if they BOTH are flexible, how do you decide whether to add
> them as numbers or concatenate them as strings?

Yes, that's where it becomes a designer's arbitrary choice.

-- 
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




More information about the Python-list mailing list