#esoteric-python
1 messages ยท Page 92 of 1
e^w<(w+n<6)>n^s if there are only these letters?
no, this is ugly
@vestal solstice isn't that the point?
challenge: make a program that outputs hello, world! (exactly like that) such that each character in the code only appears once. if that's too difficult, try without the comma in the string.
i don't know if it's possible, and i have my doubts
So, that excludes lambdas, defining then calling a function, returns, more than one call, quoted strings, more than one attribute access, defining a class unless you can find a tuple of types somewhere, try...
else and elif, exponentiation...
haha yikes, that is a lot of restrictions.
Not sure if you can with a print
You can't import sys or os for write-type functions.
You can't .encode without some shenanigans.
You can't use variables.
Perhaps Python 2 can get closer, with the print statement.
That frees up a call to try and get the string from somewhere.
I wonder if it's cheating to use a different encoding for the file.
Can't think of a way that'd make this possible with unique everything, maybe with some funky source file encoding
I'm inclined to call this one impossible without encoding machinations. It does give me another challenge idea: I wonder how much you could do with only brackets, space and lowercase ASCII letters.
Could try the smallest amount of unique chars/codepoints
A scoring mechanism could be taking each codepoint in the file, counting the instances of it and multiplying the results together.
That way the fewer duplicates, the better.
If you don't repeat characters, you get a score of 1, and if you repeat you get 2. If you repeat one character twice, that's pretty bad. If you repeat two characters once, that's worse.
i think repeating one character twice should be worse
a reasonable scoring to me would be to add 1 for each character, then 2 for each first duplicate, then 3 for the next, and so on
so "hello" would get (1 + 1 + 1 + 2 + 1) == 6
that makes dunders very expensive
!e import hello
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!eval
def hidden_w(keyword, counter=0):
return ''.join(c if (i < counter or c == ' ') else '.' for i, c in enumerate(keyword))
for c in range(11):
print(hidden_w("house boat", c))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | ..... ....
002 | h.... ....
003 | ho... ....
004 | hou.. ....
005 | hous. ....
006 | house ....
007 | house ....
008 | house b...
009 | house bo..
010 | house boa.
011 | house boat
@fiery hare It's been fixed :)
@sick hound yay
i think repeating one character twice should be worse
@brisk zenithprint('Hello, world!')is a valid solution then
Oh wait no
!charinfo o
You are not allowed to use that command here. Please use the #bot-commands channel instead.
:D
Can't even use the Unicode point, it starts with two zeros
haha yeah
Or we need to use another o
i mean, i said the word "exactly" on purpose :D
but also there's three l's and two quotes
And the freakin' l
I don't know what is so fun about these but they just are...
def complexify(func, layers=5):
new_func = func
for _ in range(layers-1):
new_func = lambda *args, func=new_func, **kwargs: (
lambda *args2, **kwargs2: func(*args, *args2,
**kwargs, **kwargs2))
return new_func
# tests | | |
# V V V
def print_args(*args, **kwargs):
print(args, kwargs)
yeet = complexify(print_args)
yeet(2)(3)(d=2)(a=5)()```
Have you guys read this? It's pretty funny, but also interesting: https://norvig.com/python-iaq.html
I was nonplussed and confused by the factorial bit until I realised I had code ligatures on.
It just looked like assert 0โ 1.
Hi
this channel scares me
:)
don't be scared, we can play a game of tic-tac-toe if you'd like:
from itertools import*;m,p,q,r,s,l,a=dict(enumerate("276951438")),[[],[]],0,print,' โ โ ','โโผโโผโ','XO';b=[*map(list,[s,l,s,l,s])];f=lambda:r('\n'.join(map(''.join,b)));f()
while m:
i=int(input(a[q]+' move: '))-1;p[q]+=[int(m.pop(i))];b[~(i//3*2)][i%3*2]=a[q];f()
if any(sum(d)==15for d in combinations(p[q],3)):r(a[q]+' wins');break
q^=1
else:r('Draw')
tf is that monster
It's tic-tac-toe
nah, I don't think this has any relation to TensorFlow
xd
The code is quite amazing, the string "276951438" seems random at first but I never thought it's also used for validating the winning pattern
Esoteric Python is interesting
explanation is here: https://github.com/salt-die/golfs/blob/master/tictactoe.py
Thank you!
@zealous widget do you have a one line version of this bad boi? 
I don't
thought it's not that far from one, if you can redo the while loop to some comp
execute code in a __name__=='__main__' from a different file without starting a new process
with open('my_code.py', 'r') as code:
exec(dedent(code.read().partition('__name__ == "__main__":')[-1])
I guess you could also do exec with __name__ as a local
Hello. Excuse me if this is the wrong place to ask, please direct me if so.
I need to create a non linear ruler image using a function. An example would be exp(11.78*x-99.64)/(x+230)). I would have a baseline x=1,2,3.... and then based on x place hashmarks for certain values of x(2,6,13).
Does anyone have an idea for how to create such an ruler?
This is for creating a slide ruler for those interested.
not really the right channel, but there isn't a topical one for this
you could use something like PIL directly, I suppose.
okey thanks
Is there a way to select all elements of a frozenset that have a given hash, without iterating through the whole frozenset?
Pretty amazing way to do it
@snow beacon maybe sth like
class Hashy:
def __init__(self, hash_)
self.hash=hash_
def __hash__(self):
return self.hash
def __eq__(self, _):
return True
elems = o_set -(o_set|Hashy(target_hash))
Can't test cause phone, but it should work
I don't think the final set operation is right either. It'll end up with an empty set. Maybe o_set - (o_set - {Hashy(target_hash)}).
Ah right
I can't decide if I want to use something like this in proper code or not.
A better way may be to make eq check hash
A possible issue: even if Hashy(...) thinks it's equal to something, the thing might not think it's equal to Hashy(...).
That would be a valid class at that point
I don't think Python makes any guarantees about what checks what's equality for set operations.
==
I like your solution though. There I was thinking about ctypes and all.
And == guarantees hash equality
a == Hashy(0) and Hashy(0) == a might give different results though.
No, == is always commutative, it checks both sides
!e
class U:
def __eq__( self, _ ):
return True
print(1==U(), U()==1)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
True True
It seems to work fine for integers, but if I define a class that always compares unequal, then it depends on the order.
Huh
I wrote one of the hash-equality classes and a class that always compares False with its hash equal to 0. Looks like for in, it runs element.__eq__ for each element in the set.
With a & b it runs __eq__ on elements of a.
Same with |.
== isn't always commutative
a - b, the important one, checks a, which is not the one we want.
At least it's deterministic. I had my fears.
In [65]: ANYTHING == NOTHING, NOTHING == ANYTHING
Out[65]: (True, False)
Weird, a ^ b seems to check b's __eq__.
Amusingly you can have a & b == a ^ b for non-empty sets.
o_set ^ (o_set ^ {hash_eq}) should do it, then.
Or I suppose o_set & (o_set ^ (o_set ^ {hash_eq})) in case nothing hashes to what you want.
It seems to work fine for integers, but if I define a class that always compares unequal, then it depends on the order.
@snow beacon that make sense, int is probably returningNotImplementedfor objects other than int or float, so it will delegate the check to the other class, while if you class always return False, only the first check will be ran (I might be misunderstanding this though)
>>> 1 .__eq__('a')
NotImplemented``` yup
That's why it's important to return NotImplemented. Python itself will raise the TypeError if both do so.
Yup
That is useful.
def f(_: (x := lambda func: lambda arg: func(arg + 1)) = 1):
@x
def a(b):
print(b) # 2
a(1)
f()
i = 2
def f() -> (g := lambda: print(i)):
i = 1
g() # not 1,this is 2
f() # 2
Prints... 2?
correct!
makes sense since g's namespace does not use f's locals
but like... why would one use that?
Because one would use the rest of the code in this channel? 
.
@snow beacon i'm curious about your interest in objects that hash the same. that doesn't sound what hashes are normally used for.
My goal was to use a regular frozenset of key/value pairs to implement a mapping with less than linear time complexity.
sets are already constant-time
Dicts and frozensets divide their objects into hash buckets, which is how they find things so quickly. The hard part is that the value half of the key/value pair won't compare equal without some massaging.
i don't understand what you are trying to make. it sounds like a dictionary. how is it different?
It's an immutable dictionary.
There is an implementation of them built on regular dicts, but I wanted to built something immutable from the ground up.
Frozensets and tuples all the way down, for the most part.
i see
I put what I have on PyPI this evening, but what I don't have is that O(log(n)) indexing.
Using set operations is fast because it's in C, but it's probably O(n) and makes my code look like someone made spaghetti out of confetti.
did you try wrapping your key/value tuples in a class that implements __hash__ and __eq__ as you need?
I currently wrap my values in a class, so that they can be hashable.
frozenset({(key, HashBox(value))})
doesn't that give you O(1) lookup?
For __contains__, but if I want __getitem__ I need to make sure I'm getting back the value in the set, not the one I use to compare.
i see
It's unfortunate that .remove() doesn't return what it removes.
Not that it's implemented on frozensets anyway.
def __getitem__(self, key_to_find):
contents = self._get_contents()
same_hash_object = HashEqObject(DEFAULT_HASH)
same_hash_set = frozenset({(key_to_find, same_hash_object)})
#trick relying on non-commutative edge cases of set operations
#fast but not a good idea
equal_contents = contents & (contents ^ (contents ^ same_hash_set))
#equal_contents is all contents that match the key.
for key, box in equal_contents:
if key == key_to_find:
return box.contents
raise KeyError(key_to_find)```I'm ruminating about whether to put this beast into my code, or to keep it just iterating through pairs.
I don't strictly need the if statement, but it makes the code seem more intelligible.
why not do something like
@dataclass
class Item:
k: Hashable
v: Any
def __hash__(self):
return hash(self.k)
def __eq__(self, other):
return self.k == other.k
```and have the frozenset contain those
then you can just use Item(k, None) as the search
If you just iterate through pairs, it's just O(n), right?
@snow beacon what about this hack
wait a moment
!e
class Probe:
def __init__(self, k):
self.k = k
self.last_equality_check = None
def __eq__(self, other):
if not isinstance(other, (Pair, Probe)):
return NotImplemented
self.last_equality_check = other
return self.k == other.k
def __hash__(self):
return hash(Pair(self.k, None))
class Pair:
def __init__(self, k, v):
self.k = k
self.v = v
def __hash__(self):
return hash(hash(self.k) + 42000)
def __eq__(self, other):
if not isinstance(other, Pair):
return NotImplemented
return self.k == other.k
def __repr__(self):
return f"Pair({self.k!r}, {self.v!r})"
frozendict = frozenset([
Pair("hello", 1),
Pair("world", 2),
Pair("abc", 3),
])
def get_value_from_frozendict(fd, key):
probe = Probe(key)
if probe not in fd:
raise KeyError(key)
return probe.last_equality_check.v
print(get_value_from_frozendict(frozendict, "hello"))
print(get_value_from_frozendict(frozendict, "world"))
print(get_value_from_frozendict(frozendict, "abc"))
print(get_value_from_frozendict(frozendict, "aaaaa"))
@formal sandal :x: Your eval job has completed with return code 1.
001 | 1
002 | 2
003 | 3
004 | Traceback (most recent call last):
005 | File "<string>", line 49, in <module>
006 | File "<string>", line 43, in get_value_from_frozendict
007 | KeyError: 'aaaaa'
behold
amortized O(1) lookup
the probe remembers the last object it was compared to
I like this trick, and may corrupt it for my aims.
@snow beacon If you just want an efficient immutable dict, you can get one :)
https://github.com/MagicStack/immutables
I thought I did, but a part of me wants to make one myself. For any actual projects I'll probably use that or frozendict.
!e
class Hah:
def __init__(s, k, p=None):
s.p = p
s.k = k
def __getattr__(s, k):
return Hah(k, s)
def __str__(h):
if h.p is None:
return h.k
return str(h.p)+h.k
H = Hah("H")
print(
H.e.l.l.o._.W.o.r.l.d
)
@pine wagon :white_check_mark: Your eval job has completed with return code 0.
Hello_World
import sys; print(a:=sys.argv[1])
for x in range(int(sys.argv[2])-1):print(a:=a[1:]+a[0])``` how do i make this shorter?
this is what it does
Does this work?python import sys;v=sys.argv;p=print;p(a:=v[1]) for()in-~int(v[2])*[()]:p(a:=a[1:]+a[0])
nope,
import sys;v=sys.argv;p=print;p(a:=v[1])
for _ in-~int(v[2])*[0]:p(a:=a[1:]+a[0])```How about now?
Oh, I got the - and ~ round the wrong way.
import sys;v=sys.argv;p=print;p(a:=v[1])
for _ in~-int(v[2])*[0]:p(a:=a[1:]+a[0])```
might save some subscripting if you unpack argv at the start
import sys;_,f,s,*r=sys.argv;p=print;p(a:=f)
for _ in~-int(s)*[0]:p(a:=a[1:]+a[0])```
I don't think this is shorter.
You might not need the ,*r. I haven't tested any of this.
why do you have a:=f
import sys;_,g,a=sys.argv
for i in range(int(g)):print(a[i:]+a[:i])
longer right?
You might need another thing to unpack into.
sys.argv[0] is generally the script name.
true
Does that work for a>len(g)?
That one, yes.
nope
works until g == len(a)
fix:
import sys;_,g,a=sys.argv;l=len(a)
for i in range(int(g)):print(a[i%l:]+a[:i%l])
80 char
import sys;_,a,t=sys.argv
for i in range(int(t)):print(a[i:]+a[:i])
Perhaps some % is in order?
Oh, I didn't see that message.
hmmm, py import sys;_=sys.argv;print(a:=_[1]) for x in range(int(_[2])-1):print(a:=a[1:]+a[0]) this is what i got
My brain is still grappling with Rust and misses things.
mine is 85 currently
nvm mine is fine
which one? @grizzled cloak lemme try that
import sys;_,a,g=sys.argv;l=len(a)
for i in range(int(g)):print(a[i%l:]+a[:i%l])
arg order is reversed here i think
so myfile.py 7 spiralmeplz~
SpiralMePlz
piralMePlzS
iralMePlzSp
ralMePlzSpi
alMePlzSpir
lMePlzSpira
MePlzSpiral
ePlzSpiralM
PlzSpiralMe
lzSpiralMeP
zSpiralMePl
SpiralMePlz
piralMePlzS
iralMePlzSp
ralMePlzSpi
my output
it should be only 7
Is there no other way to get inputs?
nah
import sys;_,a,g=sys.argv
for()in[[]]*int(g):print(a);a=a[1:]+a[0]
```66
why [[]] and not [] @proper vault ?
[]*85 is just [], which does not contain 85 elements
okh but i did't understand
i understood everything else
but not [[]]*int(g)
is this the same as []*int(g)
[[],[],[],[],[]] is what you get, each element of which you unpack into 0 variables
!e
print( float("iNfInItY") )
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
inf
Damn this was a Lil error that stopped my execution
use #bot-commands for messing with the bot please
Uh oh... Sorry I'll keep that in mind!
!e
import sys;_,a,g=sys.argv
for()in[[]]*int(g):print(a);a=a[1:]+a[0]
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: not enough values to unpack (expected 3, got 1)
pog
Can !e be passed command line arguments?
Don't think you can, it passes the evaled string after -c
Can this hcf be function be more compacted?
a=lambda x,y:a(y,x%y) if y else x
a=lambda x,y:(a(y,x%y),x)[not y]
๐
Makes sensee
Eh
ZeroDivisionError: integer division or modulo by zero
!e
a=lambda x,y:(a(y,x%y),x)[not y]
a(100,3)
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | ZeroDivisionError: integer division or modulo by zero
doesn't that result in infinite recursion?
It actually shudnt but a(y,x%y) is causing an error
if y is 0 then not y will be 1 then (a(y,x%y),x)[1] will be x which stops the recursion
as in, a(y,x%y) still has to be evaluated in that case, no?
Yess thats why the error occurs
it makes sense cause using the tuple in that method means that a(y,x%y) is always execed
which means that the recursion never exits
so i want to make a code which takes a input int, and then converts it into a list, for example if the input it is 5 then the list will be [1,2,3,4,5] and on that i need to perform this function,(sum of even number squares) - (sum of odd number squares). how do i do this in lambda and short
!e
x = lambda n: sum(map(lambda e: e**2, range(2, n+1, 2))) - sum(map(lambda e: e**2, range(1, n+1, 2)))
print(x(5))
@cedar herald :white_check_mark: Your eval job has completed with return code 0.
-15
it should get this output ```py
For k = 5, the output should be
appleBoxes(k) = -15.
There are 1 + 3 * 3 + 5 * 5 = 35 yellow apples and 2 * 2 + 4 * 4 = 20 red apples, making the answer 20 - 35 = -15.```
oh i tried that but failed
lemme see where i went wrong
is there anyway to get that shorter?
With only the standard Python libraries? Not too sure
i tried making short but doesn't work then
With only the standard Python libraries? Not too sure
@cedar herald yes with only standard ones
((b := lambda x: print(x))
,(sqrt := __import__("math").sqrt)
,(i := lambda k: int(k))
,(c := lambda n: i(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))))
,[b(c(x)) for x in range(20)]
)
yes
it takes too much time @cedar herald 57 seconds,
i tried to get it down, but wasn't successful
is it really necessary that you do it in one line?
nah, just one functino @cedar herald
i tried reducing your solution and making it more efficient but it doesn't happen
by friend got it 36, oof
don't use one line then
def fn(n):
result = 0
for x in range(1, n+1):
if x % 2 == 0:
result += x * x
else:
result -= x * x
return result
this was my first solution, i need to keep it short but efficient
or only very short
why though?
we are having a challenge to who gets it the most down
then it's kinda pointless if I helped you xD
If this beats your friend then I win, not you ๐
!e
import itertools
x = lambda n: sum(v * v * c for v, c in zip(range(1, n+1), itertools.cycle([-1, 1])))
print(x(5))
@cedar herald :white_check_mark: Your eval job has completed with return code 0.
-15
s=lambda n:sum((i*i)*((-1)**(i%2))for i in range(1,n+1))
they want it to be fast, I wonder whether the repeated computation of i%2 would be faster than simply cycling through the list
if you want it to be fast use closed form solution
In [32]: evens=lambda n:2*n*(n+1)*(2*n+1)//3
...: odds=lambda n:n*(2*n+1)*(2*n-1)//3
In [33]: evens(2) - odds(3)
Out[33]: -15
no loops
it needs to be one-line and small
it can still be small
40 what?
also that closed form solution is the fastest but it might be considered cheating by your friend, idk
what did you use
i just removed unwanted things from salt-die's solution
lambda n:sum(i*i*((-1)**(i%2))for i in range(1,n+1))
lambda n:sum(i*i*((-1)**i)for i in range(1,n+1)) should work just as well.
You might not need the brackets around ((-1)**i).
Instead of (-1)**(i%2) you can do 1-(i%2)*2
Not sure if you can remove the last two parenthesis though but maybe... You'll have to check
And if you want it to be faster i&2 could be better ^^
And if you want it to be faster
i&2could be better ^^
@copper thunder what do you mean by this
I meant replacing the i%2 by a i&1, since it is the same operation but may be faster
Btw it is &1 not &2
okay lemme try that
I hope CPython is already applying this optimisation
It would be pretty stupid not to
I hope so, but it's worth trying
this is much slower
Unh
oh k
And it needs parenthesis around (1-2*(i&1))
Also you could drop the 1, in the range since when i=0 it adds nothing to the sum
even that doesn't work @vestal solstice
x=lambda n:sum(i*i*(-1)**(i%2)for i in range(1,n+1)) this is current code,
i didn' get what you said
(1-2*(i&1)) there is no 1, and 2?
x=lambda n:sum(i*i*(1-i%2*2)for i in range(n+1))
Though computing the exact solution directly would solve it faster and in less code, but I won't do it for you if it is a challenge with your friend
Can this go any shorter?: ''.join([re.sub(r'\S', f'||{l}||', l) for l in m]) where m is a string and l is a letter in that string (spaces should be ignored)
You can get rid of the list comp and use a generator expression I think (without any [])
You can also remove spaces after commas
sum(re.sub(r'\S',f'||{l}||',l) for l in m)?
I don't know I've never used that before
for a in d:
for b in a:
e += (b + ' | ')
e += 'txt'
Can i make this 1 line?
Wait, you can sum() strings instead of joining?
Thatโs awesome, enever thought about that
Eh?
TypeError: sum() can't sum strings [use ''.join(seq) instead]
right yeah
I just tried out something, had no idea if it was going to work
sry
I personally got TypeError: unsupported operand type(s) for +: 'int' and 'str'
Even though I wasn't doing any calculations ๐ค
Thats when u put strings inside a list and use sum() on it
If you do sum('a','b','c') it will raise my error
sum(['a','b','c']) raises ur error
I see
def decorator(func):
def warp_func(k):
print('---------')
func(k)
print('---------')
return warp_func
@decorator
def name(j):
print(j)
mn=decorator(name)
mn('dhrumil') ``` can i get this in one line?
You want a oneline decorator?
decorator = lamda f: lambda: (print('โโโ'), f(), print('โโโ'))[1]```I think?
inner lambda needs a param
decorator = lambda f:lambda *a,**k:(print('-'*9),f(*a,**k),print('-'*9))[1]```
^ that will pass all args and kwargs into the wrapped function
don't you also need to print the output otherwis functions that just return a value with have 2 lines printed
decorator = lambda f:lambda *a,**k:(print('-'*9),f(*a,**k),print('-'*9))[1]
@decorator
def foo():
return 1
x = foo()
---------
---------```
it involves expanding the decorator but you can get it to this
!e ```py
decorator = lambda f:lambda *a,**k:((print('-'*9),print(o := f(*a,**k)),print('-'*9)), o)[1]
@decorator
def foo():
return 1
x = foo()
print(f"output: {x}")```
@vague hearth :white_check_mark: Your eval job has completed with return code 0.
001 | ---------
002 | 1
003 | ---------
004 | output: 1
in his usecase he was printing inside the decorated function
ah ok, that would still work then, this just expands it to non-printing functions, doesn't look very nice tho but then again, if thats what your after this probably isn't the way to do it at all xD
Any other weird way to do this?
!e
some_var = 10
def weirdStuff(global_var, v):
if global_var % 2 == 0:
globals()[[n for n, v in globals().items() if v == global_var][0]] = v
print(some_var)
weirdStuff(some_var, 12304234)
print(some_var)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 10
002 | 12304234
Another way I thought of was to use ast, currently looking for a way to ast the same file it's called in without putting the code in a string. Not sure if that's even possible
You should be able to inspect the frame the function was called from and change the locals() of it.
locals()```
Update and return a dictionary representing the current local symbol table. Free variables are returned by [`locals()`](#locals "locals") when it is called in function blocks, but not in class blocks. Note that at the module level, [`locals()`](#locals "locals") and [`globals()`](#globals "globals") are the same dictionary.
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
^
I already hear you screaming -- yes, this is the most appropriate channel to avoid implementaiton-specific behavior!
@boreal slate can't you also do ```py
@(lambda f: ...)
def function(...):
...
idk if it's actually valid syntax
I don't believe it is.
!e ```py
@(lambda f: ...)
def function():
...
@brisk zenith :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | @(lambda f: ...)
003 | ^
004 | SyntaxError: invalid syntax
ah indeed
You can only use identifiers and calls, possibly attributes.
There is a PEP to fix this IIRC
3.9 will allow any expression in them
noice
They will support that because of some GUI app who had some issues because of that
!pep 614
can we compress try and except blocks?
No you'd have to make a function or something
I mean unless you wanna do this exec('try:\n print(x)\nexcept Exception as e:\n print(e)')
thanks, i am doing a bunch of challenges online in one liner
so asked
def sum_up_diagonals(matrix, sum=0):
for m in range(len(matrix)) :
sum += matrix[m][m] + matrix[m][-m-1]
return sum``` can i get this in one line in lambda
hmm let me know how this goes sum_up_diagonals = lambda matrix, sum=0: sum([matrix[m][m] + matrix[m][-m-1] for m in range(len(matrix))])
Pretty sure sum is being redefined there so
sum_up_diagonals = lambda matrix, sum_=0: sum_ + sum([matrix[m][m] + matrix[m][-m-1] for m in range(len(matrix))])
There
oh thanks,
instead of -m-1 you can use ~m i think
Damn i never though about that! That's a great trick thanks !
it is the binary not operator
Yep. Often seen as "two's complement"
how is ~m different from -m-1 @copper thunder ?
It's shorter.
so basically ~m subtracts one from m?
It inverts all of the bit in the binary representation of an integer.
Well, not really in CPython, but that's what it's meant to look like.
two's complement says ~n + 1 = -n therefore ~n = -n - 1
okh
It inverts all of the bit in the binary representation of an integer.
Well, not really in CPython, but that's what it's meant to look like.
What does CPython really do, then ? It just "remembers" that the bits were flipped and inverts all subsequent logic ?
pretty sure it actually inverts the bits
Yeah, it is just a C call to do a not on the integer
async def emojify(emoji: str, *m):
return ''.join([re.sub(f'{w}', f'{emoji}{w}', w) for w in m]) + emoji
# input: emojify('๐', 'this is a test message')
# output: "๐this๐is๐a๐test๐message๐"
How can I write this shorter? not sure if re.sub was the right choice here
also not really the right channel
def emojify(e, m):
return f"{e}{m.replace(' ',e)}{e}"
what tuple are you giving it
async def emojify(e, *m):
return ''.join(w.replace(' ',e) for w in m)```
pretty sure it actually inverts the bits
I was expecting there to be weird logic for the arbitrary length integers.
@twilit grotto his original func took an arbitrary number of arguments m which you need to loop thru
yeah
e+e.join(''.join(m).split())+e may possibly be shorter
What exactly is this channel for?
Code golf and obfuscation, mainly.
Treating Python as a challenge rather than a helper.
Thanks Chilaxen, that works ๐
A particular retailer is having a 60 percent off sale on a variety of discontinued products. The
retailer would like to help its customers determine the reduced price of the merchandise by
having a printed discount table on the shelf that shows the original prices and the prices after
the discount has been applied.
Create a Function that uses a loop to generate this table, showing the original price, the
discount amount, and the new price for purchases. Ensure that the discount amounts and the
new prices are rounded to 2 decimal places when they are displayed. Return 3 Array of
Original Price, Discount Amount, After Discount Price.
Function Style: ComputeDiscount( TotalNoOfElements, ArrayElements)
can some on help me
whit this
unless you want a golfed solution, you should use a help channel #โ๏ฝhow-to-get-help
I added then and catch to Python coroutines
async def returnFive():
return 5
async def other():
return await returnFive().then(lambda i: i + 3)
async def main():
print(await other())
loop.run_until_complete(main())
This works internally by turning coroutines to asyncio.Tasks and adding a done callback
ComputeDiscount=lambda n,a:[*zip(*((x,.6*x,.4*x)for x in a))]
```Golfed version of the function.
Not sure how they want the function to display yet return.
...from #internals-and-peps
So I made this.
from functools import partial
import gc
d = gc.get_referents(dict.__dict__)[0]
HELLO = [None]
window = {
"answer": {
"get": lambda: 42,
},
"hello": {
"get": lambda: HELLO[0],
"set": lambda v: HELLO.__setitem__(0, v),
},
}
@partial(d.__setitem__, "__getitem__")
def get_item(self, key, *, ACTUAL_GETITEM=d["__getitem__"]):
try:
return ACTUAL_GETITEM(self, key)
except:
if key not in window:
raise
if "get" not in ACTUAL_GETITEM(window, key):
raise KeyError(f"{key} exists, but is not readable (just like your code, ha!)")
return ACTUAL_GETITEM(ACTUAL_GETITEM(window, key), "get")()
@partial(d.__setitem__, "__setitem__")
def get_item(self, key, value, *, ACTUAL_GETITEM=d["__getitem__"], ACTUAL_SETITEM=d["__setitem__"]):
if key not in window:
ACTUAL_SETITEM(self, key, value)
elif "set" not in window[key]:
raise KeyError(f"{key} exists, but is not writable")
else:
ACTUAL_SETITEM(ACTUAL_GETITEM(window, key), "set")(value)
to make an extra fallback for dict lookup.
However, it doesn't work. Why?
import random;import string as s;print(*random.choices('_'+s.ascii_letters+s.digits,k=16),sep='')
```I make it a challenge to make it in as least lines (then as least characters) as possible
Anything I missed?
Any way to make it shorter?
@formal sandal using dict[key] calls the c code directly
dict.__getitem__(key) performs a dot lookup (which looks for python methods first by default)
sad
Is there any other way to hook into getting a global variable then?
Object.defineProperty(window, 'answer', {
get: () => {
return 42
}
});
like this in JS
This is how you define a getter for the window obejct.
So every time you try to access the answer global variable, you get 42
print(*__import__("random").choices(["_",*filter(str.isalnum,map(chr,range(128)))],k=16),sep="")
@formal sandal the answer is yes, but it needs much ctypes fuckery
yea true
!e ```py
print(*import("random").choices(["_",*filter(str.isalnum,map(chr,range(128)))],k=16),sep="")
@grand tree :white_check_mark: Your eval job has completed with return code 0.
M2ZYvWgje6U8cxYr
cool
I invite anyone to do it in less lines.
class ParentInstanceMixin():
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
return object.__getattribute__(object.__getattribute__(self, "parent_instance"), name)
i am a horrible person, i know
ive never used much ctypes, why doesnt this work? py t = type("", (), {}) ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
well what were you expecting it to do, and what did it actually do?
i was expecting the base class of t to be function, but i got a segfault
unless ive misunderstood what thats doing
because the thing at that offset into PyObject is a pointer to the type of the object
right
>>> import ctypes
>>> t = type("", (), {})
>>> ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
>>> t
<function at 0x000001EEB8140538>```
that segfaults when running a file though
that's not really that surprising really, since that t is a pretty nonsensical object
you've just unceremoniously picked up data from a type object and told it that it's a function now
but surely type and function have the same layout in memory, roughly
they are both objects
ok maybe im asking the wrong question. i wanted to set an attribute of a function, such as __repr__ or __add__. ive seen other examples do it for integers by creating a dummy typ inhereting from int with the new method. i wanted to do the same for functions, but python wont let you have function as a base class
https://github.com/python/cpython/blob/master/Include/funcobject.h#L21 https://github.com/python/cpython/blob/master/Include/cpython/object.h#L185
they're quite different
oh okay, i thought function was just an object like int is
hm okay
why does that work in the repl then?
or is it just setting weird values for each field, and its just coincidence that it doesnt segfault
i think it's probably just a coincidence
doing almost anything else with that function object causes it to segfault
oh ok
so what would be the correct way of setting magic methods on a function object?
since i cant replace the base class
!e
import ctypes
t = type("", (), {})
ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
print(str(t))
@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).
<function at 0x5629d4b38b70>
>>> import ctypes
>>> t = type("", (), {})
>>> ctypes.py_object.from_address(id(t)+8).value = type(lambda x: x)
>>> print(str(t))
<class '__main__.'>
Why???
!e ```py
from ctypes import Structure, c_ssize_t, py_object
class PyObjStruct(Structure):
fields = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]
t = type('', (), {})
PyObjStruct.from_address(id(t)).ob_type = type(lambda x:x)
print(str(t))
@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).
<function at 0x55c07b4a7130>
is there some kind of tutorial on ctypes?
it looks a mix of Haskell and Japanese to me
a lot of it is relatively straight forward if you look at the python source code
helps to know c, as well
If you're really interested or have a big project converting c to python, hit up godlygeek sometime, he's super knowledgeable on the subject.
Greetings strangers. Anyone in here has had any experience with Google's foobar challange?
probably a lot, but is it really #esoteric-python ?
I got invited and I really don't know where to look for guidance, sorry if this is the wrong place to ask.
If you aren't sure what algorithm to use, #algos-and-data-structs. In most cases, just a help channel.
This channel is mostly for fun stuff you wouldn't want to actually ever use ๐
Got it, thanks!
.> Remind me to tell y'all the story about someone suggesting I use the gc library's ref counter to implement layering in my game engine some time.
For ideas of "things that work, but why?"
The proposal was basically "Make each layer an object, then find out what's on that layer by using the garbage collector to grab only those object.
!e
import gc
class GameObject:
def __init__(self, id, layer):
self.id = id
self.layer = layer
def __repr__(self):
return f"<GameObject {self.id}>"
LayerA = object()
LayerB = object()
objects = [
GameObject(1, LayerA),
GameObject(2, LayerA),
GameObject(3, LayerB),
GameObject(4, LayerA),
GameObject(5, LayerB),
]
print( gc.get_referrers(LayerA) )
print( gc.get_referrers(LayerB) )
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | [{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'GameObject': <class '__main__.GameObject'>, 'LayerA': <object object at 0x7fedcbffbb80>, 'LayerB': <object object at 0x7fedcbffbb90>, 'objects': [<GameObject 1>, <GameObject 2>, <GameObject 3>, <GameObject 4>, <GameObject 5>]}]
002 | [{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'GameObject': <class '__main__.GameObject'>, 'LayerA': <object object at 0x7fedcbffbb80>, 'LayerB': <object object at 0x7fedcbffbb90>, 'objects': [<GameObject 1>, <GameObject 2>, <GameObject 3>, <GameObject 4>, <GameObject 5>]}]
Huh, so I tried doing that, but it doesn't show the GameObjects in there for some reason?
only shows the globals() dict
Good to know it wouldn't even work.
my disappointment is immeasurable and my day is ruined
!e ```py
from ctypes import Structure, c_ssize_t, py_objectclass PyObjStruct(Structure):
fields = [
('ob_refcnt', c_ssize_t),
('ob_type', py_object)
]t = type('', (), {})
PyObjStruct.from_address(id(t)).ob_type = type(lambda x:x)
print(str(t))
@rugged sparrow
@rugged sparrow
@misty jewel Not gonna lie, looks like C or something for some reason.
Well... it is C, sort of
What is the use case for this?
The term 'use case' is prohibited in this channel ๐
this channel is reserved for absolutely useless and impractical stuff
yeah I guess, and I get the golfing and all, but I don't understand this at all. it doesn't seem as much esoteric as it does a hack
My criterion for 'esoteric' is "you wouldn't use it in production code".
Then it fits in perfectly here
@snow beacon append "if you don't want to get fired" ๐
"You wouldn't use it in production code if you knew your code would get read by people with the authority to get you fired who know Python best practices, and you don't want to get fired."
why not just "clever hacks"
I don't get it. The rays are clearly 3 characters long, not 2
i got it from the net, wanted to solve it
first code it without golfing
The question doesn't make sense to me
!e
import numpy as np
def sun(ray_length, start=0):
dim = ray_length * 2 + 3
mid = dim // 2
canvas = np.zeros((dim, dim))
xs = np.arange(dim)
ys = -xs - 1
# lines
canvas[xs, xs] = 1
canvas[xs, ys] = 1
canvas[mid, :] = 1
canvas[:, mid] = 1
return canvas
print(sun(2))
@zealous widget :white_check_mark: Your eval job has completed with return code 0.
001 | [[1. 0. 0. 1. 0. 0. 1.]
002 | [0. 1. 0. 1. 0. 1. 0.]
003 | [0. 0. 1. 1. 1. 0. 0.]
004 | [1. 1. 1. 1. 1. 1. 1.]
005 | [0. 0. 1. 1. 1. 0. 0.]
006 | [0. 1. 0. 1. 0. 1. 0.]
007 | [1. 0. 0. 1. 0. 0. 1.]]
now you just need to replace the 1's with correct values starting at top-left
there's a more clever approach, but I'll leave it as an exercise for the reader
that is different
'6 7 8'
' 9 O 1'
' 234'
'5678901'
' 234'
' 5 6 7'
'8 9 0'``` it should be like this
did you read what i typed
it's not difficult to see the correspondence between this array and your desired output
hmmm, ok, will try
!e
import numpy as np
def cycle(start):
while True:
yield start
start += 1
start %= 10
def rays(ray_length):
dim = ray_length * 2 + 3
mid = dim // 2
canvas = np.zeros((dim, dim), dtype=int) - 1
xs = np.arange(dim)
ys = -xs - 1
# lines
canvas[xs, xs] = 1
canvas[xs, ys] = 1
canvas[mid, :] = 1
canvas[:, mid] = 1
return canvas
def replace(canvas, start=0):
it = np.nditer(canvas, flags=['multi_index'])
cy = cycle(start)
for _ in it:
if canvas[it.multi_index] != - 1:
canvas[it.multi_index] = next(cy)
return canvas
def sun(ray_length, start):
arr = replace(rays(ray_length), start)
return '\n'.join(''.join(str(i) if i != -1 else ' ' for i in row) for row in arr)
print(sun(2, 6))
@zealous widget :white_check_mark: Your eval job has completed with return code 0.
001 | 6 7 8
002 | 9 0 1
003 | 234
004 | 5678901
005 | 234
006 | 5 6 7
007 | 8 9 0
ah almost got that, let me see my mistakes
' 9 O 1'
' 234'
'5678901'
' 234'
' 5 6 7'
'8 9 0'
is not the same as, this is problem i am getting
' 9 O 1 '
' 234 '
'5678901'
' 234 '
' 5 6 7 '
'8 9 0'```
is that an O?
yes
@zealous widget 
>>> >>> (lambda : (print("call"), gc.get_referrers(sys._getframe(0).f_code)[-1]()))()
call
call
...
call
call
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
[Previous line repeated 993 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
``` some recursive lambda. I didn't know how to do that in a simpler way (without naming the lambda, of course).
you can use a combinator (lambda f: f(f))(lambda f: f(f))
oh right ! I didn't think about it, thanks a lot !
(anyway, I love dirty codes ๐ )
Can you somehow take advantage of gc to make fizzbuzz?
Why doesn't deleting __builtins__ from globals() render everything unusable (mess things up)?
Do you have an ungolfed version?
not yet, i tried but i get the same problem as salt-die did
The O is not explained in the problem description. I would suggest one of the help channels might get you something working, and then this channel can get you something disgusting.
well did that in #help-pancakes
import numpy as np
import sys as u
def cycle(start):
while True:
yield start
start += 1
start %= 10
def rays(ray_length):
dim = ray_length * 2 + 3
mid = dim // 2
canvas = np.zeros((dim, dim), dtype=int) - 1
xs = np.arange(dim)
ys = -xs - 1
# lines
canvas[xs, xs] = 1
canvas[xs, ys] = 1
canvas[mid, :] = 1
canvas[:, mid] = 1
return canvas
def replace(canvas, start=0):
it = np.nditer(canvas, flags=['multi_index'])
cy = cycle(start)
for _ in it:
if canvas[it.multi_index] != - 1:
canvas[it.multi_index] = next(cy)
return canvas
def sun(ray_length, start):
arr = replace(rays(ray_length), start)
return '\n'.join(''.join(str(i) if i != -1 else ' ' for i in row).rstrip() for row in arr)
print(sun(int(u.argv[1]), int(u.argv[2])))``` how do i get this short now? @snow beacon
For a start, you could calculate a exactly how many numbers you'll need, generate an appropriate range, then take the range % 10. You can remove whitespace and the sys import.
Replace i != -1 with ~i.
Replace ys = -xs - 1 with ys=~xs
Change all the identifiers to single characters.
Maybe instead of numpy, you could try printing character by character, checking if the x and y coordinates match any of the x = y, x = len-y, x = len/2, y = len/2 criteria.
Instead of using four spaces for your indentation, use one space.
Get rid of the sun function and just put its contents into your code.
You can do the same with replace.
ok let me try if i get stuck i will put it here
For a start, you could calculate a exactly how many numbers you'll need, generate an appropriate range, then take the range % 10. You can remove whitespace and the
sysimport.
@snow beacon what do you mean by this?
You have a generator to generate infinite digits.
You don't need that many.
You can calculate how many you need from the size of the sun.
can i do like this a,b,c=*1
like *args
@snow beacon
import numpy as np
import sys as u
def j(start):
while True:
yield start
start+=1
start%=10
def q(rl):
d=rl*2+3
m=d//2
cv=np.zeros((d, d), dtype=int) - 1
xs=np.arange(d)
ys=-xs-1
cv[xs, xs]=1
cv[xs, ys]=1
cv[m, :]=1
cv[:, m]=1
return cv
def r(cv,start=0):
it=np.nditer(cv,flags=['multi_index'])
cy=j(start)
for _ in it:
if cv[it.multi_index]!= -1:
cv[it.multi_index]=next(cy)
return cv
t=r(q(int(u.argv[1])), int(u.argv[2]))
print('\n'.join(''.join(str(i) if i !=-1 else ' ' for i in w).rstrip() for w in t))```
if args is possible i will do that
well got shorter now @snow beacon
you can remove all the function calls and just have one long sheet of code
and instead of starting with np.zero you can just use np.full and start with an array of spaces
this is what i did till now py import numpy as np import sys as u def j(k): while True: yield k k+=1 k%=10 def q(rl): d=rl*2+3 m=d//2 cv=np.zeros((d,d),dtype=int)-1 xs=np.arange(d) ys=-xs-1 cv[xs,xs],cv[xs,ys],cv[m,:],cv[:,m]=1,1,1,1 return cv def r(cv,k=0): it=np.nditer(cv,flags=['multi_index']) cy=j(k) for _ in it: if cv[it.multi_index]!=-1: cv[it.multi_index]=next(cy) return cv print('\n'.join(''.join(str(i) if i !=-1 else ' ' for i in w).rstrip() for w in r(q(int(u.argv[1])), int(u.argv[2]))))
well i didn't understand what u said
@zealous widget and @snow beacon sorry for the ping!
np.zeros makes zeros, which you then replace with spaces. np.full makes some default element you pass it, such as ' ' which you wouldn't need to replace.
Also, you can still replace all of your indentation with a single space each time rather than four.
I'm not sure there's a simple transformation to get rid of all the functions, but the code from r can be taken out of a function.
You can also get rid of the sys import because you don't use u.
it's used on the last line
Thank you, I didn't see that.
It's likely easier to do from sys import* and from numpy import* than using u and np.
Also, @boreal slate I'm not going to apologise for this ping because I did it intentionally.
it's still pretty readable tbh
you just added a bunch of semicolons to separate lines
I HAVE A CHALLENGE
for anyone willing to accept.
The challenge is simple, output the word "Success" in a shorter amount of code than print('Success')
(YOU CAN ONLY USE ONE LINE OF CODE, AND NO SPECIAL MODIFICATIONS TO PYTHON)
Winner gets a pat on the back, and a thank you.
print 'Success' 1 less character, requires python 2
Or go to interpreter and type 'Success'
Those both count as special modifications to Python
๐ค
using python is a modification of python ๐ค
I can't be modified from standard Python 3
So what's wrong with using the python 3 interpreter?
quit('Success')
It's not a standard interpreter
Nice @proper vault
quit('Success')
@proper vault ๐
wookie184 receives the pat on the back
Yay
But @proper vault did it first, so, I pat him instead
Don't worry wookie I'll pat your back
If you allow other text too
@sudden osprey I thought about that by the way, but I figured not. Though good effort ๐
!e ```py
getattr(
import(True.class.name[1] + [].class.name[2]),
().class.eq.class.name[:2] +
().iter().class.name[6:9]
)(
1, str.encode((lambda _, __: (, __))(
lambda _, : chr( % 256) + (, __ // 256) if __ else "",
753072441997358419
))
)
@paper bloom :white_check_mark: Your eval job has completed with return code 0.
Success
not really a shorter amount of code than print('Success') :P
what are python vm languages
well, FormDSL doesn't fit that definition
It's just implemented in Python, it's not compiled to bytecode
Maybe the description should be changed to "toy languages implemented in Python" or something
I would say an interpreter in python fits
@fair wind :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | int main() {
003 | ^
004 | SyntaxError: invalid syntax
@fair wind This isn't Python.
you have many syntax errors
!e
fะพr=lambda *_:lambda *_:0
fะพr (i := 1, i < 2, ++i) ({
print(i)
});
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1
How are you running it?
If you want help with C++, there's this server: https://discord.gg/KEefW3
you have gcc in your name 
Challenge: FizzBuzz inside a single print statement. If possible, using only one f-string
update: I think someone already completed it lol
Here's a solution:
print(f"{chr(10).join(['fizz'*(n%3==0)+'buzz'*(n%5==0) or str(n) for n in range(100)])}")
print(exec(your source code)or"", end='')
lazy hack
!e
print(*['fizz'*(n%3==0)+'buzz'*(n%5==0) or n for n in range(100)],sep='\n')
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/izitaseruy
shorter, and no f-string
Yep! That was the original and I made it use an f-string as well (that was half the challenge)
!e py print(*('fizz'*(1-n%3)+'buzz'*(1-n%5) or n for n in range(100)),sep='\n')
@vague hearth :white_check_mark: Your eval job has completed with return code 0.
001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/aruqejafot
swapping ==0 for 1- before makes it 2 chars shorter
(could also change (1-n%5) or n to (1-n%5)or n
Oooh fizbuzz we were chatting about this on another server the other day
for i in range(100):print("Fizz"*(i%3>1)+"Buzz"*(i%5>3)or i+1)``` we got it down to 62
for i in range(100):print("Fizz"*(i%3>1)+"Buzz"*(i%5>3)or-~i)
```61
for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
``` 59
whats that -~ part doing
negative bit inverted i i think
-~x is x+1 but you can omit whitespace before it. ~-x is x-1.
huh
Unfortunately, this is 61 :(
i=0;exec('print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i);i+=1;'*100)
fair
!e
fะพr=lambda *_:lambda *_:0 fะพr (i := 1, i < 2, ++i) ({ print(i) });
Woah this is valid python?
Im actually only surprised about it being wrapped in {} lol
its valid but it doesnt do what it looks like it does
+(int) is __pos__
Indeed it does not.
i should use something in int.__pos__ to make it work ๐
Hmm
!e
class Integer(int):
def __init__(self, num):
super().__init__()
def __pos__(self):
self += 1
return self
fะพr=lambda *_:lambda *_:0
fะพr (i := Integer(1), i < 2, ++i) ({
print(i)
});
@steep mural :white_check_mark: Your eval job has completed with return code 0.
1
thats some fancy code
Sad I probably did it wrong
is this what trying to reinvent the wheel looks like
fะพr=lambda *:lambda *: yield 0
would this fix it or im dumb
!e
class Integer(int):
def __init__(self, num):
super().__init__()
def __pos__(self):
self += 1
yield self
fะพr=lambda *_:lambda *_:0
fะพr (i := Integer(1), i < 2, ++i) ({
print(i)
});
@wanton tundra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | TypeError: bad operand type for unary +: 'generator'
ye i got 0 clue whats going i should go back to just watching
!e
class Integer(int):
def __init__(self, num):
super().__init__()
def __pos__(self):
self += 1
return self
def fะพr(var, condition, after):
def wrapped(to_do):
while condition:
exec(next(iter(to_do)))
i = after
return wrapped
fะพr (i := Integer(0), i < 5, i := Integer(++i)) ({
"""
pass
"""});
@steep mural :warning: Your eval job timed out or ran out of memory.
[No output]
Doesn't work properly unfortunately
Oh I thought it had something to do with the scope lol
!e
class Integer(int):
def __init__(self, num):
super().__init__()
def __pos__(self):
self += 1
return self
def fะพr(var, condition, after):
def wrapped(to_do):
while eval(condition):
exec(next(iter(to_do)))
exec(after)
return wrapped
fะพr (i := Integer(0), 'i < 5', 'i = Integer(++i)') ({
"""
print(i)
"""});
@steep mural :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
Good enough
Hello, https://realpython.com/python-metaclasses/#defining-a-class-dynamically
Can somebody give me and example where metaclass could be used and why? ๐
@zealous widget unleash your pink mush
oh no
@sweet jolt If you have a genuine question, I would suggest opening a help channel ๐ This channel is more for stuff which is intentionally obscure, overengineered or otherwise uselessified
Here is an example of sum types (disjoint unions). It uses both metaclasses and metametaclasses (a metametaclass is a metaclass for a metaclass)
In [8]: class MaybeInt(SumType):
...: Just.of(int)
...: Nothing.of(())
...:
In [9]: x = MaybeInt.Just(42)
In [10]: x
Out[10]: 42
In [11]: type(x)
Out[11]: embellished('Just', <class 'int'>)
In [12]: y = MaybeInt.Nothing(())
In [13]: y
Out[13]: ()
In [14]: type(y)
Out[14]: embellished('Nothing', ())
(this is a very esoteric example, not something you would actually use)
so esoteric that julius evola himself would frequent this channel
Well the knock off c for loop is without strings which i think is pretty cool
!e
class Integer(int):
def __new__(cls, num, name, base=10):
self = super().__new__(cls, str(num), base)
self.name = name
return self
def __init__(self, num, base):
pass
def __pos__(self):
return f'Integer({self.name} + 1, {self.name})'
def __gt__(self, other):
return f'int({self.name}) > {other}'
def __lt__(self, other):
return f'int({self.name}) < {other}'
def fะพr(var, condition, after):
def wrapped(to_do):
while eval(condition):
exec(next(iter(to_do)))
locals()[var.name] = eval(after)
return wrapped
fะพr (i := Integer(0, 'i'), i < 3, +i) ({
"""
print('Hello World!')
"""});
@steep mural :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World!
002 | Hello World!
003 | Hello World!
u seem to enjoy this
i wonder if you could grab the stackframe inside for() and repeat/cancel exec of it based off of the for args
then you wouldnt need the string
would def need inspect and ctypes stuff
Hmm sounds like something out of my league lol
Hey y'all, just posted this in the wrong channel I think, so reposting here to get some assistance, hopefully
Hey y'all, I have a funky question / discussion topic: what is called when you raise an error? I have implemented a couple custom exception in my source, and what I want is to check the type of __context__ when raise <error> from <other error> is used, and if it is of a certain type, do some extra logic before the exception is actually raised.
I've googled and I can't find anything on this
It seems I'll have to pass it into the initializer for the custom exception, but I'd really like to leverge the raise ... from ... syntax
@rugged sparrow perhaps pdb can help you
try: raise Exception
except Exception as e:
do_something_else()
@uneven grail
Havenโt tested because I donโt exactly know why you would need raise ... from ... but as far as Iโm aware, this behaves as a context for your exception
Oh i see.
You know whatโs funny is Iโve been using Python for umpteen years and Iโve completely forgotten that syntax even exists
try: raise SomeException
except SomeException as e:
do_something_else()
raise AnotherException from e
haha right? I mainly just use raise ... from None when I want to overwrite the exception thrown but yeah, I want to save some metadata into the exception object itself about the exception it is raised from
Or you could just do raise Exception
and like I get that it gets saved into context but it doesn't seem like there is any way to access it before the raise is actually handled
here is a simple example, how do you print what its raised from?
Like you can't it seems lol
Yeah I could do that, but I want to do this from inside the exception, not the code raising it
if that makes sense
Nope ๐
lol
Like, okay
assume I have a custom exception MyException
and in my source I have a bit that fails due to some reason and I say raise MyException(stuff, more_stuff, etc.) from OtherException
The idea is that I want to save something specific from the OtherException into the MyException instance.
How is your MyException written?
Now I could always do something like raise MyException(stuff, more_stuff, etc. from=other_exception)
but I'm hoping to leverage the from notation
Itโs just a class inheriting from Exception
raise MyException(stuff, more_stuff, etc. from=other_exception)
no you couldn't,fromis a keyword
Oh
it was just a descriptive example
raise MyException(stuff, more_stuff, etc. from_exc=other_exception)
^ the name of the arg is not important, just that I'm passing it into the initializer
I guess what I'm getting at is that there is not internal method that is called when you raise an exception?
so RIGHT when its raised, not when the object is created, you can perform some logic
Define __call__ in your class definition?
I canโt remember if itโs __call__ or __called__
Idk man
I donโt know what youโre trying to accomplish lol
no worries, the goal is to customize some logging around error handling for use in serverless apps. There are a number of exceptions we deal with daily. What I'm trying to handle are boto3 ClientException and httplib HTTPError. I want to save some metadata about the requests themselves into the error signature (see code) automatically
right now I just have like 5 different base classes, but really it could be simplified by just saying "oh you are raising from an httperror? Let's save that request data into the signature. Oh its a client error? let's save some of the requests metadata there too"
I wouldnโt do that. Iโd use logging. Youโre going to shoot yourself in the foot modifying exception like this haha
^ that's what its wrapping lol
Hmmm
I don't want to insert logging everytime an exception is raised
that's just anti DRY
I want to have some prebaked, auto logging everytime my custom exception is raised
which is being done btw, I just want to extend it
the logging part is not the issue
its the accessing the context object when the exception is raised, not when its initialized that is the issue
haha sorry its a pretty funky question
I literally canโt fathom why you would need to access Exception after itโs raised.
no not after
Definitely esoteric for sure lol
but like RIGHT before
Try except is the best youโre gonna get lol
all we can do rn is create an object
atleast that's all I know how to do lol
but something must be happenning when raise is called
I just want to insert some functionality right at the beginning
no so
(spacing is weird because discord, sorr)
try: ... except Exception as e: ... litterally just catches the exception details and saves them into the object e. That is just initializing it, and you can access all the parameters you want
when you do try: ... except Exception as e: raise MyException from e it creates a new instance, with all the stuff of e saved as __context__ . But that is not available when e is created
Itโs already initialized when it got raised
that saviing into the context object is done as a part of the raise logic
Afaik
so I want to grab that stuff from e
before its raised
again
I could always just do ... raise MyException(from_exc=e)
but I'm trying to dive into using the first pattern, if its even possible
Youโre creating an entirely new exception instance. The from is for uninitialized exceptions
So you would have to call the type
But then you can access any data inside because itโs not initialized when you use from
Does that make sense?
As in
You can do it either way, take a look at pep3134, how you create the exception is just a nuance,
whether you raise from the base class or from an instance of the base class, it doesn't matter
all from does is sets the context
litterally translates to my_exc.__context__ = e
I feel like this shouldnโt be this difficult, but Iโm struggling lol
it seems like everything in python has a method behind. Hell, I can even overwrite how an object is accessed as an attribute through descriptors, but I just can't find any docs on what to do when an exception is raised
it seems that all I can do is initialization logic and that's it
And you looked at all the dunder methods I assume?
yeah no magic methods extend raise functionality
what I was hoping was that, just for example's sake, there was a method __raise__ that is called when an object is raised. Creating an "exception" was just simply defining this method. I could, in my exception, do something like def __raise__(self): ... do some logic on __context__... super().__raise__() and call it a day
but alas lol
Like, a really simple but impossible problem would be when an exception is raised, print "Hello, World" before all the raise stuff happens
like you just can't do that
The wonders of meta programming
You can do it when you create the exception object itself, but not after you call raise
I can try, but I don't think the object is called when its raised. Let me see what happens when I do that
Yeah no cookie
My brain is fried
Yeah same, I'm probably just going to go with the init arg route, but dang I'd love a real solution to this
you can subclass exception, and in the __init__ do whatever
yeah that's the issue though, I want to insert logic during the exception raise, not the initialization procedure
the reason is because raise ... from ... updates context during the raise procedure. During initialization, its just None
I just want to insert a little tidbit before the true raise procedure that will update the signature (see notebook from above) based on the type of exception we raised from
That's it ๐ฟ
!e ```py
import ctypes
import sys
def get_obj_mem(obj):
return (ctypes.c_char * sys.getsizeof(obj)).from_address(id(obj))
get_obj_mem(2)[-4] = 3
print(2 + 2)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
4
huh
that works in the interpreter
>>> get_obj_mem(2)[-4] = 255
>>> 2
255
>>> 2
255
>>> 1 + 1
255
>>> 1 + 1 == 255
True
>>>
prob some optimizer i need to disable
you can try to set your own __getattribute__ to do something when __context__ or __cause__ is set @uneven grail
In [53]: class MyException(Exception):
...: def __getattribute__(self, attr):
...: print("Looking for:", attr)
...: super().__getattribute__(attr)
...:
In [54]: try:
...: raise ValueError
...: except ValueError as e:
...: raise MyException from e
...:
Looking for: _render_traceback_
Looking for: __cause__
Looking for: __suppress_context__
Looking for: __context__
---------------------------------------------------------------------------
MyException Traceback (most recent call last)
<ipython-input-54-d2ae2723d1b0> in <module>
2 raise ValueError
3 except ValueError as e:
----> 4 raise MyException from e
5
MyException:
>>> class MyException(Exception):
... def __getattribute__(self, attr):
... print("Looking for:", attr)
... super().__getattribute__(attr)
...
>>> try:
... raise ValueError
... except ValueError as e:
... raise MyException from e
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Looking for: print_file_and_line
__main__.MyException```

In [1]: class MyException(Exception):
...: def __getattribute__(self, attr):
...: print("Looking for:", attr)
...: if attr == "__cause__":
...: return ProxyProperty(self)
...: return super().__getattribute__(attr)
...:
In [2]: class ProxyProperty:
...: def __init__(self, instance):
...: self.instance = instance
...: def __setattr__(self, attr, value):
...: print("Setting:", value)
...: setattr(super(Exception, self.instance).__getattribute__("__cause__"), attr, value)
...:
In [3]: try:
...: raise ValueError
...: except ValueError as e:
...: raise MyException from e
...:
Looking for: _render_traceback_
Looking for: __cause__
Setting:
Looking for: __suppress_context__
---------------------------------------------------------------------------
MyException Traceback (most recent call last)
<ipython-input-3-d2ae2723d1b0> in <module>
2 raise ValueError
3 except ValueError as e:
----> 4 raise MyException from e
5
MyException:
this is getting pretty hacky
are you sure those gets and sets are actually from python and not ipython
@zealous widget how can i get this short py import sys a,b=map(int,sys.argv[1:]) s,c="",a*2+4 r=range(1,c) for i in r: for j in r: if i==j or i+j==c or a+2in[i,j]:s+=str(b);b=(b+1)%10 elif j<i or j<c-i:s+=" " s+="\n" print(s[:-1])
did that challenge shorter
s+=str(b)[-1];b+=1 is shorter than s+=str(b);b=(b+1)%10
it will act differently if b is negative but if it isn't then it's the same (i think), just shorter
it is passing my test case so yes it works
i think you can also replace i==j or i+j==c or a+2in[i,j] with len({i,j,a+2})<3or i+j==c
nah
not i!=j!=a+2or c==i+j I think it should work, but am not 100% sure
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:
if not i!=j!=a+2or c==i+j:s+=str(b)[-1];b+=1
elif j<i or j<c-i:s+=" "
s+="\n"
print(s[:-1])``` this?
well
doesn't work @proper vault
>>> 1 != 2 != 1
True```
oh, those do not get chained
!= is getting chained, just it doesn't compare the first one and the third one
i'm not sure why mine didn't work though
len({i,j,a+2})<3 is true iff i, j and a+2 are not all different
(if they're all different it's 3, otherwise less than 3 since sets don't get duplicate elements)
i==j or i+j==c or a+2in[i,j] and that's basically what this is checking (i think), other than the i+j==c
well so is there any way of getting it shorter?
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:
if i==j or i+j==c or a+2in[i,j]:s+=str(b)[-1];b+=1
elif j<i or j<c-i:s+=" "
s+="\n"
print(s[:-1])``` this is what i got till now `190` chars
if someone can figure out what's wrong with my len({i,j,a+2})<3or i+j==c then i might be able to fix it and end up with something shorter than i==j or i+j==c or a+2in[i,j]
although actually
depending on your test cases, you may be able to replace print with quit
i think you can shorten i==j or i+j==c or a+2in[i,j] to not i!=j!=a+2!=i or c==i+j
i'm still confused about len({i,j,a+2})<3or i+j==c not working
do you have an example where that gives something that's different to i==j or i+j==c or a+2in[i,j]?
me? i don't think so
you're the one who has a load of test cases
if there's something wrong with len({i,j,a+2})<3or i+j==c you should be able to figure out what it is 
str(b%10) is shorter than str(b)[-1]
already did that
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:
if not i!=j!=a+2!=i or c==i+j:s+=str(b)[-1];b+=1
elif j<i or j<c-i:s+=" "
s+="\n"
print(s[:-1])```
well i can't bee
str(b)[-1] you didn't as far as I can tell
i think you can shorten
i==j or i+j==c or a+2in[i,j]tonot i!=j!=a+2!=i or c==i+j
@stark fable well i didn't understand this, why does this work tho
i!=j!=a+2!=i -> i!=j and j!=a+2 and a+2!=i, ish
it's like how you can do a<b<c -> a<b and b<c
except in this case it's with != which is a bit weird
ye thanks
super weird
because there is 2 times i in that inequation
but smh it doesn't work anymore if u remove one of them
damn my friend got it in 172
one of the is is being compared to j, and one of them is being compared to a+2
really j and a+2 are the weird ones since they appear once but they're used in comparisons twice
j<i or j<c-i
not-i>~j<i-cdoesn't save anything, but looks cooler
Can you just replace elif j<i or j<c-i: with else:?
Oh no
I see
I guess you can't have the trailing spaces?
for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I think this is equivalent to the if condition, but the hypothesis test did not finish yet
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:
if(j!=2+a!=i!=j)&(c!=i+j):s+=" "[(j>i)&(j>c-i):]
else:s+=str(b)[-1];b+=1
s+="\n"
print(s[:-1])``` 187
for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I think this is equivalent to the if condition, but the hypothesis test did not finish yet
@proper vault didn't work
had to do a small correction, think it should be correct now
<i-c),0],(s+ had to be <i-c),b],(s+
nah didn't work
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:s,b=[[s+" "*(not-i>~j<i-c),b],(s+str(b%10),b+1)][not i!=j!=a+2!=i or c==i+j]I
s+="\n"
print(s[:-1])``` you meant this right @proper vault ?
ye, though it seems like I missed something, it doesn't work for negative a, b
import sys
a,b=map(int,sys.argv[1:])
s,c="",a*2+4
r=range(1,c)
for i in r:
for j in r:
if(j!=2+a!=i!=j)&(c!=i+j):s+=" "[(j>i)&(j>c-i):]
else:s+=str(b)[-1];b+=1
s+="\n"
print(s[:-1])``` 187
@boreal slate well so need to get this down
for j in r:s,b=[[s+" "*(j<i or j<c-i),b],(s+str(b)[-1],b+1)][not i!=j!=a+2!=i or c==i+j] works for everything it seems
@fair wind :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | mport ctypes
003 | ^
004 | SyntaxError: invalid syntax
@fair wind :white_check_mark: Your eval job has completed with return code 0.
4
!e import ctypes
import sys
def get_obj_mem(obj):
return (ctypes.c_char * sys.getsizeof(obj)).from_address(id(obj))
get_obj_mem(2)[-4] = 3
print(eval('2 + 2'))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
6
@rugged sparrow
the issue was that 2 + 2 would get compiled and then optimized into 4
and 4 doesn't care what the value of 2 is since it's just 4
can someone help me convert python script to exe file
How to convert python script to a .exe file? This video covers the technique of converting a .py python script into .exe file using pyinstaller. This is the most detailed video for this, explaining various arguments which can be used in pyinstaller to utilize all the amazing f...
@hot barn
well, "converting .py to .exe" is probably on the same level of usefulness as metametaclasses
Iโm not so sure about that
Packaging an interpreter should be pretty easy, but you need to unpack, have a wrapper script, etc...
And you canโt have everything in one file
you take that back about metametaclasses
for a in range(106):print((' '*a).join('SCOTT'))
```Any way to shorten this more?
for a in range(106):print(*'SCOTT',sep=' '*a)
@proper vault thank you! Is there any way to make it shorter than that? Whatโs the shortest it can go?
for a in range(106):print(*'SCOTT',sep=' '*a)
``````py
a=0
while a!=106:print(*'SCOTT',sep=' '*a);a+=1
``````py
for a in range(106):print((' '*a).join('SCOTT'))
```These are ordered from shortest to longest.
@stark fable do you know if there is a pythonapi func that acts like gc.get_objects() but gets every currently allocated python object?
instead of the ones created after gc was inited internally
cause currently i have a ptr address and i want to check if its pointing to an actual py_object (which i can do if i loop thru all objs and compare id(obj)==ptr)
on a related note, is there any way to check that a given ptr is within python's address space
I kinda need to keep it referenced lmao
I'm trying to dynamically guess/assume the types of any struct
ah, Russian roulette ๐
If you guess incorrectly, your system language is changed to Russian
Yea a bit
So far it assumes everything is a long, but if it kinda looks like a valid ptr it follows it. But I need to get a way to check if a ptr is within pythons memory space
what's esoteric python
weird stuff that you never want to use in prod
!e
from functools import wraps
from contextlib import contextmanager
this = None
@contextmanager
def with_this(new_this):
global this
old_this = this
this = new_this
try:
yield
finally:
this = old_this
class Object:
def __init__(self, dict_=()):
self.__dict__.update(dict_)
def __repr__(self):
return f"Object({self.__dict__!r})"
@staticmethod
def constructor(fn):
@wraps(fn)
def _constructor(*args, **kwargs):
with with_this(Object()):
fn(*args, **kwargs)
return this
return _constructor
##############
# USER CODE: #
##############
@Object.constructor
def User(uid: int, name: str):
this.uid = uid
this.name = name
this.name_split = name.split()
fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
Object({'uid': 42, 'name': 'Fizz Buzz', 'name_split': ['Fizz', 'Buzz']})
The next step would be to add methods and prototype inheritance, which would be pretty cool
it would also be cool to use new instead of the decorator...
what are y'all trying to do?
I'm procrastinating over actual work ๐
I'm emulating JavaScript's object orientation model
I'm emulating JavaScript's object orientation model
oh yeah, of course
This code is so un-pythonic, I love it
I'm pretty sure it follows PEP8 ๐
(the python code, not JS)
except for the comment
Pirate Encapsulation Protocol
Haha
!e
exec(__import__("gzip").decompress(__import__("base64").b85decode(b'ABzY8N~~jF0{^{L!EW0y487|sxSZ_5$OjZCkYU($-MuIT#g-GTwq!`kvY^PnkCbFraonYcVhE6kBKgQikqm3C>7hO7+8fh3Q2k)6hocpPV?kFN?d2cesqLstH@(neCoN;l@0EiG_+hj}X*1I|vW27adroGBmd9`??-}emvlShX$iQ?BPeAb^38MpE*b_RzNy)BZ&?+suF5D!`5dm|cn7kHR8_##r7h3d^B8K~dPGE&{625wG)%M`!cWaF;+SRw<1n2~VHG{PN1h3?NUX={2^arbfGr&(C#9am9yu62-aomkKjMbfR4j#9^WbFwspmU{_=e%&TYbyfq#-9dRL8EHVABr+iG{I@jDLa7)Ob#o~DX8OoRl)1Iylv}Eu$>~23+d4zgyieP&<HP!AeC&))5>9lidB!q+EpY}ye5zo0#8%}&d-?F1^yR%E>{!mZk8ko0bjM@3`)ZrG7%+Zs5CaprRIqoo=Htznzibb^prMvtf`;MH!7j)VR{(1kXZ%4MR$<@D?#eT81P^3nkN?Whpf2D%YL$ak*ECaQtdP4CH=W?&OSl7ImDC*gN;L-s(b18rb)QCQJl92+)+3>I?mN5>?jgRinExR-3hyM72Msu9O)Fxq>b)OjVmWNT_|j7&fKbuQ2|<gg$?-=gk|(bHOB~c%M7D1k?UKHZSa`hjv)D7=%$mlAfbXpdo1L5In7T+5M`DJA+mY!7#knd%UD>nCx48cVa2Wu_q4K9<T&fx%d01{enyy|X}5*tSY7Yr>Ux8gY#EIP?`BaLEOT@h9Fb1O@8hg8r_UzmK1S}H_PKPxnGg2w%nALYE_8A1@7W|E)Y$mr>R#^uq>b2+7Rn~^$)}Anm=z8SR?!R5+l1nz9;Bai6W<=clN`&1-|R1KN>0ea2mk;')))
@Object.constructor
def User(uid: int, name: str):
this.uid = uid
this.name = name
@Object.method
def say():
print(f"<{this.name} #{this.uid}>")
@Object.getter
def name_split():
return this.name.split()
fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
fizzbuzz.say()
print(fizzbuzz.name_split)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Object(User, {'__props__': {'name_split': Object(Property, {'__props__': {}, '__proto__': <function Property at 0x7f63815d7700>, 'name': 'name_split', 'get': <function User.<locals>.name_split at 0x7f6381638040>, 'set': <function _cannot_set.<locals>._ at 0x7f63816381f0>})}, '__proto__': <function User at 0x7f63815d7820>, 'uid': 42, 'name': 'Fizz Buzz', 'say': <function User.<locals>.say at 0x7f638166cca0>})
002 | <Fizz Buzz #42>
003 | ['Fizz', 'Buzz']
lol
I guess I can make sort-of-prototype inheritance... but it won't be as functional as JS
reminds me i make decorators sometimes to change the code of methods to include self in the args and add all the class attributes into the function's locals
looks similar in spirit
!e
exec(__import__("gzip").decompress(__import__("base64").b85decode(b'ABzY8T()Ch0{_)k&2HN;48H3rxSZ_3$O9B8kYU($-MuIT#gP-Owq!`kvY^PjPo!j5ah#>Q3>XTu7JojHpGc~#v8IFOplfeT>p*qAu^x_A^p26PHrmTyzEzt+nIxUiVka$Q%<q+hNBCy645#%(zm*LfmEUtTE3`b)NBO{D*P4xJ0gnt!yX6Te3esV42m*TwPH<AP-7;vD7HvzCWH}&&955!Yh1SONo%Dqkoy3SFFYpVjP)@>U@2%P#y!>jdu|>1^LQW8zptq)%)}P=F-Or1XftCJXHE;&uClBJTf^c3wz}-0RP8`PSRyYSwn;)|F2uSE$Y2`UDoNSv40le|2URJPGwdapTNhKO`T5-%ygak&11?L#lalWYF?Ofis^@eQ6Na%w4;6Ney>d<e6mj#_lHson#KR`v+V`0rA7F4_?kQ5?(AqSkFLtYp7pX|9@jIg^&l6W9|)zCL64e!WUC@P8R&?uLhXLNW$HFjy%s$<e)+UT*uek$Kfp{|GVV%$t-75o(KLH?@*u@_^&KizAd808Ncxys9Kw0xDP{O%I>newvysc&9=f^buaF%br97j&xbq~DuugjISkt@6c^x`b8-$-|;?-X6m03KON{xWSrs7oO=Dhcq)>3cGU^ESIlG{7U?3qgzvlWt7{JX2N;u+uW>7kpUWG<A~t(#$+Qr#M6p5ntBIq^;IefC6Pp14JCOjL<kMiX!dTH>**qsJg;QJYr3yF0x$Xd7=1U{`wQ}J@{!TOZj&*`1-j1{9uH&99pOBsQNc)jFZ8yRw!lLLiH)Ie2jRG`DugIA?h%o}Y&VDb@iOuq?9rcU7_s7#AUVDeDwaN36qllBw0;RN-_uh<Z&7vq1XkA%R>|hkaL?T(g~5D{?mwx~eXPbCU3BRXHZ9rTm?Hc?W~Rqu_fO^|Kn-ItJec#-k+cyT(i&f<dh%Js3?{?{!YaHdydokeT@(IElGp;_cREM9!f*B)s^>PXI0^s&')))
@Object.constructor
def NameSayer():
@Object.method
def say():
return f"<{this.name} #{this.uid}>"
@Object.constructor
def WithNameSplit():
@Object.getter
def name_split():
return this.name.split()
@Object.inherit(NameSayer, WithNameSplit)
def User(uid: int, name: str):
this.uid = uid
this.name = name
fizzbuzz = User(42, "Fizz Buzz")
print(fizzbuzz)
print(fizzbuzz.say())
print(fizzbuzz.name_split)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Object(User, {'__props__': {'name_split': Object(Property, {'__props__': {}, '__proto__': <function Property at 0x7f7569c223a0>, 'name': 'name_split', 'get': <function WithNameSplit.<locals>.name_split at 0x7f7569c22a60>, 'set': <function _cannot_set.<locals>._ at 0x7f7569c229d0>})}, '__proto__': <function User at 0x7f7569c22790>, 'say': <function NameSayer.<locals>.say at 0x7f7569c22820>, 'uid': 42, 'name': 'Fizz Buzz'})
002 | <Fizz Buzz #42>
003 | ['Fizz', 'Buzz']
now with inheritance... sort of
But it's kind of cheating here because fizzbuzz.say is a bound method, unlike in JS
so the proper way to implement this would be to do it via message passing, like
fizzbuzz("say")
fizzbuzz("say", arg1, arg2)
and then I'd have proper prototypal inheritance cause I'd be able to inherit objects, not constructor functions
Ew regex

