Last active
August 19, 2022 18:11
-
-
Save Kilo59/f055b2863351675e7f8d89ddd040c9ff to your computer and use it in GitHub Desktop.
Fun with Python id()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ############## | |
# at what number does this error? | |
# 0? 100,000? never? | |
# ############## | |
try: | |
for i, n in enumerate(range(0, 100000)): | |
assert i is n, f"{i} is {n}" | |
except AssertionError as e: | |
print(f"Error on -> {e}") | |
# ### | |
# str | |
# ### | |
foo1 = "foo" | |
foo2 = "foo" | |
print(f"foo1\t id:{id(foo1)}") | |
print(f"foo2\t id:{id(foo2)}") | |
assert foo1 is foo2 | |
bar = "bar" | |
print(f"bar\t id:{id(bar)}") | |
assert foo1 is not bar | |
# ############ | |
# id shadowing | |
# ############ | |
def fake_id(x): | |
print(f"fake_id called with {x}") | |
return "fake_id" | |
def my_func(id): | |
print(f"id = {id.__name__}()") | |
assert foo1 is not bar | |
print("end of my_func") | |
my_func(fake_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related reading
https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python/79198#79198
https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for/15667328#15667328