type annotation vs working code
Karsten Hilbert
Karsten.Hilbert at gmx.net
Sat Sep 30 18:25:11 EDT 2023
Am Sun, Oct 01, 2023 at 09:04:05AM +1300 schrieb dn via Python-list:
> >class WorkingSingleton(Borg):
> >
> > def __init__(self):
> > print(self.__class__.__name__, ':')
> > try:
> > self.already_initialized
> > print('already initialized')
> > return
> >
> > except AttributeError:
> > print('initializing')
> >
> > self.already_initialized = True
> > self.special_value = 42
> >Where's the error in my thinking (or code) ?
>
> What is your thinking?
> Specifically, what is the purpose of testing self.already_initialized?
The purpose is to check whether the singleton class has been
... initialized :-)
The line
self.already_initialized = True
is misleading as to the fact that it doesn't matter at all
what self.already_initialized is set to, as long as is
exists for the next time around.
> Isn't it generally regarded as 'best practice' to declare (and define a value for) all
> attributes in __init__()? (or equivalent) In which case, it will (presumably) be defined
> as False; and the try-except reworded to an if-else.
I fail to see how that can differentiate between first-call
and subsequent call.
> Alternately, how about using hasattr()? eg
>
> if hasattr( self.already_initialized, 'attribute_name' ):
That does work. I am using that idiom in other children of
Borg. But that's besides the point. I was wondering why it
does not work the same way with and without the type
annotation.
> try:
> self.already_initialized
>
> line is flagged by the assorted linters, etc, in my PyCharm as:
>
> Statement seems to have no effect.
Well, the linter simply cannot see the purpose, which is
test-of-existence.
> Question: is it a legal expression (without the typing)?
It borders on the illegal, I suppose, as the self-
introspection capabilities of the language are being
leveraged to achieve a legal purpose.
Which seems akin constructs for generating compatibility
between versions.
It seems the answer is being pointed to in Matts response.
It just mightily surprised me.
Karsten
--
GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B
More information about the Python-list
mailing list