Skip to content

Instantly share code, notes, and snippets.

@bensimner
Last active August 2, 2022 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bensimner/7d593144662efc4bb880104bf110cb95 to your computer and use it in GitHub Desktop.
Save bensimner/7d593144662efc4bb880104bf110cb95 to your computer and use it in GitHub Desktop.
Python weirdos
x = []
y = x
x.append(42)
print(y)
def f(x):
x.append(42)
y = []
z = y
f(y)
print(z)
x = 1
def f():
print(x)
x = 2
f()
for i in range(10):
pass
print(i)
e = 1
try:
1/0
except ZeroDivisionError as e:
pass
print(e)
def f(i, x=[]):
x.append(i)
print(x)
f(1)
f(2)
f(3)
funcs = []
for i in range(10):
def f():
return i
funcs.append(f)
for g in funcs:
print(g())
x = 1
def f():
x = 2
print(eval("[x for i in range(10)]"))
f()
x = 1
class C:
x = 2
class D:
print(x)
class C:
pass
c = C()
c.__dict__["x"] = 42
print(c.x)
class C:
def f(self):
return self
print(C.f(42))
print(C().f())
class C:
x = []
def insert(self):
self.x.append(42)
def show(self):
print(self.x)
c1 = C()
c2 = C()
c1.insert()
c2.show()
x = 1
class C:
x = 2
def __init__(self):
self.x = 3
def f(self):
return x
def g(self):
return self.x
def h(self):
return type(self).x
c = C()
print(c.f())
print(c.g())
print(c.h())
class C:
def __getattribute__(self, attr):
if attr == "__int__":
return (lambda _: 42)
def __int__(self):
return 1
c = C()
print(int(c))
class D:
def __get__(self, instance, owner=None):
if instance is None:
return 1
else:
return 2
def __set__(self, instance, value):
instance.__dict__["d"] = value
class C:
d = D()
c = C()
print(C.d)
print(c.d)
c.d = 42
print(c.d)
L = [[1], [2], [3] ]
L[1] += L.pop(0)
print(L)
x = 1
class C:
x = 2
print([x for _ in range(1)])
print([0xfor x in (1, 2, 3)])
def f():
try:
return 1
except:
return 2
else:
return 3
finally:
return 4
print(f())
class C:
__slots__ = ["x", "y"]
class D(C):
pass
d = D()
d.x = 1
d.y = 2
d.z = 3
print(vars(d))
class Base:
def __init__(self, *args):
pass
b = Base()
class D(b):
pass
from .a import b
print(b)
print(a)
d = d["a"] = {}
print(d)
class MyDesc:
def outside(self):
return 13
def inside(self):
return 42
def __get__(self, instance, owner=None):
if instance is None:
return self.outside
return self.inside
class C:
f = classmethod(MyDesc())
print(C.f())
print(C().f())
class C:
@property
def foo(self):
return 42
def __getattribute__(self, attr):
print("GET ATTR", attr)
return super().__getattribute__(attr)
c = C()
print(c.foo)
x = "a"
print(f"{x=}")
print(f"{x=:}")
x = 1
class C:
x = x
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment