How well do you know Python?

Chris Angelico rosuav at gmail.com
Tue Jul 5 05:21:47 EDT 2016


On Tue, Jul 5, 2016 at 6:36 PM, Peter Otten <__peter__ at web.de> wrote:
> What will
>
> $ cat foo.py
> import foo
> class A: pass
> print(isinstance(foo.A(), A))
> $ python -c 'import foo'
> ...
> $ python foo.py
> ...
>
> print?

I refuse to play around with isinstance and old-style classes.
Particularly when circular imports are involved. Run this under Python
3 and/or explicitly subclass object, and then I'd consider it. :)

> It looks like
>
> $ python3 -c 'print({1, 2})'
> {1, 2}
> $ python3 -c 'print({2, 1})'
> {1, 2}
>
> will always print the same output. Can you construct a set from two small
> integers where this is not the case? What's the difference?

Given that the display (iteration) order of sets is arbitrary, I'm not
sure what the significance would ever be, but my guess is that the
display order would be the same for any given set, if constructed this
way. But it sounds as if you know of a set that behaves differently.

> What happens if you replace the ints with strings? Why?

Then hash randomization kicks in, and you can run the exact same line
of code multiple times and get different results. It's a coin toss.

rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'2', '1'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'2', '1'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'2', '1'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'2', '1'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}
rosuav at sikorsky:~$ python3 -c 'print({"1", "2"})'
{'1', '2'}

ChrisA



More information about the Python-list mailing list