#esoteric-python
1 messages · Page 50 of 1
what are you even saying anymore
you can call 1 foot tile a 1 foot tile but not 1 yard tile, si unit would stay meters
???
then please stop continuing it ^^
Tbf, MiB is correct:
MiB -> Mebibyte was set out by IEC and it's multiple of 2
MB -> Megabyte which is the si unit and multiple of 10
So yes, you are not using si unit, but the si unit call MB instead of MiB, and what you looking for is still MiB
nope
Can you just do a quick Google search?
Or, mark specifically what I say wrong?
in case you are too lazy to google search
Here a source:
https://physics.nist.gov/cuu/Units/binary.html
Not wrong, but at least, we should at least have the knowledge of what is right :)
And annoy that the official IEC standard document is behind a pay wall
im not saying you're incorrect
im saying its not what im referring to
and what you looking for is still MiB
this part specifically
Well, because you used 1024 instead of 1000, you are using the IEC standard instead of the si standard, which that use MiB instead of MB
^^
actually
i am following neither standard
if i was following the standard, i would have written MiB
but i didn't, so
you are using the IEC standard
thats incorrect
In the calculation
We are saying your prefix is wrong because your calculation is IEC standard
by not conforming to any standard you are free to use any terms you want
but some ppl may misinterpret them which is fine if it doesn't matter that much
everyone knows what i mean from context though ^^
:D
Then, you relying on a standard for the everyone to understand then you should at least acknowledge you used it incorrectly
i was not relying on a standard
Ok, so you mean no one suppose to understand you :)
no, i mean that everyone can just read the numbers i wrote if they want to understand
and if they dont understand, they can just ask me for clarification
this is normal in conversations
Ok, so let me suppose that they can also equivalent understand that that are equivalent to 1 idksomethingfunny
Ok, Let me say:
I don't understand what you mean by 13.6959056854 MB, that is 13695905.6854 Byte, how to you have a fraction of a byte
Because I am so stupid I cannot understand it
Can you clarify?
here i am using MB to mean 1024 * 1024 bytes ^^
But MB mean 10**6 according to si unit
I don't understand because I am stupid, can you further clarify?
there are no fractions of bytes
but i am not using si units ^^
as said previously
Oh, then what are you using? I definitely couldn't possibly guess what it's because I'm stupid
Also maybe move this to #ot0-psvm’s-eternal-disapproval ?
at this point i dont think you are asking for clarification in good faith anymore, since you're asking for clarification about things that you previously said you understood
so im going to stop engaging with you
Oh ok, so saying making a mistake is that hard huh
Also btw, if you want to clean up this chunk of message that irrelevant to the channel topic, go ahead and I will follow :)
you are using your own made up units, right
expecting others to understand you is weird
i provided the exact numbers i used for my calculations
there isnt much room for misunderstanding if people just. read the numbers
like i said here
And the make up unit is literally a different standard is more funny
It is basic equivalent to
10km:
10 / 1.852 = 5.39957 mile
But the mile I am using is nautical mile instead, and assume people could understand that it is even though I didn't say so
I provided the exact numbers for my calculations
you surely don't understand the importance of units
Y'all better get over this already. :/
.topic
Suggest more topics here!
medium of writing code
or returns the first operand if it's truthy, otherwise the second one.
Likewise, and returns the first operand if's falsy, otherwise the second one
!e
print(17 and "wat")
print(() and "wat")
print(17 and [])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | wat
002 | ()
003 | []
its secret knowledge not everyone knows
how the heck did we get here
in fact how the hell did people argue in #esoteric-python
if you care about the precision of 1024 vs 1000 then go use bytes
KB, MB, and GB are all approximate units to me
Can we just drop this discussion please?
Hello world but I resized my editor to be 4 characters wide
(
vars
)((
vars
)()[
dir(
)[1]
])[
'pr\
int'
]('\
Hel\
lo,\
Wo\
rld\
!')
It is so hard to see 💀
is 3 possible? 🤔
Alternative more boring version, but also doesn't work for 3. ```py
(
exec
)("
pri
nt(
'He
llo
, W
orl
d!'
)")
i don't think it's possible to get the builtins dictionary using only 3-long identifiers
that's really the limiting thing there
if you have g=getattr at the start I think you can do anything 😄
same with vars
with getattr? I don't think much can be done with getattr without using identifiers shorter than 3 chars
If you have g=getattr, you can actually do it in 2: https://paste.pythondiscord.com/OEBA
Could probably be done more efficiently, but that's the first thing that came to mind because theevalgame has lived rent free in my head for too long.
yeah but g=getattr is not 2 chars wide so thats rejected
its just impossible to do it in less than 3 chars
The premise was
with getattr? I don't think much can be done with getattr without using identifiers shorter than 3 chars
Which I had to prove wrong
['abs', 'all', 'any', 'bin', 'chr', 'dir', 'hex', 'id', 'int', 'len', 'map', 'max', 'min', 'oct', 'ord', 'pow', 'set', 'str', 'sum', 'zip']```when you do 3 chars these are the only functions you can use
and its not possible to execute code which writes to stdout using those functions
there are no methods less than 4 chars, except for add and pop of setpy {'abs': [], 'all': [], 'any': [], 'bin': [], 'chr': [], 'dir': [], 'hex': [], 'id': [], 'int': [], 'len': [], 'map': [], 'max': [], 'min': [], 'oct': [], 'ord': [], 'pow': [], 'set': ['add', 'pop'], 'str': [], 'sum': [], 'zip': []}
but dict is 4 chars so you can use it in 3 chars width
though you can use {}
but still those methods are not useful for accessing stdout with just these
hello esopy what are we cooking today
trying to print hello world with a 3-column source file
ctypes.memoryview_at() coming in 3.14
yeah after that I admit defeat
I am curious, what is the minimal amount of character per line possible to rewrite any python script that only rely on standard library, without using eval/exec (except case that the original script used them), assuming the variable/function/class name doesn't matter (not used as library)
ooh
hmm, I can't figure out how to do it in under 3 characters per line
Maybe someone smarter than me can, here's a way I did it in 1 character per line in javascript, though, maybe it's useful here
Javascript ☕
you forgot to call the function though
ah yeah, that's just my codewars solution lol
Javascript is trivial in theory, since any jsfuck program can be made 1 char wide
asuming you ignore and throw away typehints (which in this channels, is a given), I think the longest construction is that of a class, which at it's most (without loosing functionality) is
class a(b):
only bested by it's magic methods:
def __init__(s, *a, **k):
for which, we can make a smaller function to insert without exceeding the number of chars of the class definition, for example
def change(cls, method, dunder):
setattr(cls, dunder, method)
which the smallest it can get should be
def a(*a):
setattr(
a[0],a[2],
a[1])
which is just a char smaller than the class, so I would bet for len("class a(b):") = 11
correct me if I'm wrong though
ignoring imports
for some reason I thought that would be bigger
You can use type for class
So maybe shorter?
you can actually make it 4 wide ```py
a=
(
type
)("
a",(
b,),
{})
So I think the limit for everything is 4 wide
what's the smallest thing you need for a function? I think def is as long or shorter than lambdas
As long as you can get getattr and setattr through vars, you should be able to make everything only 4.
Issue, how to write a function 🤔
hm
you could be a menace and pre-compile the bytecode and write the bytecode, instanciate with it a code object and with it a function
💀
Nope, you basically running arbitrary code at this point
What stopping you to compile the entire code in bytecode in a function
I think it's 6 with function 🤔
def _(
I love how a couple channels below is type-hinting is a couple channels below discussing about the best practices of writing maintanable code and here we are discussing if it's a valid solution pre-compile a function so that we can clap it's code into 1 char per line
yeah pretty much
*a for the args and more arguments to replace higher order functions
Well, let's the traditional
Yep, and after that, you can store into a dictionary or whatever if you have many
And string can have whatever length
You also can apparently create functions using the types.FunctionType constructor, but that takes a code object which is back in the same domain as exec and eval.
When column >= 2
you could be a menace and pre-compile the bytecode and write the bytecode, instanciate with it a code object and with it a function
there's a compile function that should spit out a code object without executing the code
The main restriction of this is arbitrary code execution lul, only allowed to use it if the original code use it and only for that specific purpose
Yes, but that's boring since you could just do compile("the entire code here") and then make a function f with that body, then call f for a "we have exec at home`.

Example, if the original code that the user input and evaluate it, you can use eval for that purpose and not ask you write an entire python parser, compiler and interpreter in python from scratch
you can, even, to put functions into dictionaries, reuse the same name, for example
d={}
def a(
s,b):
...
d['\
som\
e_n\
ame'
]=a
def a(
s,c):
...
d['\
som\
e_o\
the\
r_n\
ame'
]=a
...
I just noticed how long return is
I think the maximum is gonna be set by return instead of by def
Oh return💀
No one had remember we might need them
output arguments
Write a return value stack
you pass a list
and the return value gets appended
that is genuinely so dumb it could work, as long as there is no compatibility to be maintained
is that allowed or are we gonna have to stick with
return _
(9 chars)
Even stupider idea: have a variable named r, and every time you want to return a thing do globals()["r"]=thing, then read the value of r after the function. The only issue then would be implementing the short-circuiting behavior of return.
globals()[ ugh, how long is that?
well append is also pretty big
but pretty sure there's some getattr magic to make it shorter
so should be with globals
k, nvm, not a bad idea
getattr solves everything
the short-circuiting, yeah
Top level return isn't too bad, but what about when it's nested
can we make a decorator that when detects A>B on the code that instruction in the bytecode gets replaced by a return instruction?
You might need an additonal global that's used for checking if you are in "return mode", then insert checks for that everywhere.
Or I guess it could be local
like replace LOAD_NAME (A) LOAD_NAME (B) with LOAD_CONST (0), RETURN?
But another problem is dealing with indentation
since we return in an argument/global we don't care what the first const is
tab is a single char
So you would need a global to track return mode since function calls would be the only way to solve arbitrary indentation.
or take everything out into a function (and probably set an argument to it not to waste names)
s=[]
g=\
vars(
vars(
)["__\
built\
ins__"
])["g\
etatt\
r"]
t=g(s,
"appe\
nd")
p=g(s,
"pop")
def a(
*b):
t(b[0
])
a([1])
vars(
vars(
)["__\
built\
ins__"
])["p\
rint"
](p())
Function that return the argument and print it (print outside the function)
t is s.append and p is s.pop
g is getattr
I should have bootstrap builtins to b
like
p = print # getattr magic that I'm gonna skip
def a(
n,b=a
):
p("n\
umber\
is e\
ven")
if (
n<1):
p(
"numb\
er<0")
else:
p("
numbe\
r>0")
def b(
n,b=a
):
p("n\
umber\
is o\
dd")
if (
n<1):
p(
"numb\
er<0")
else:
p("
numbe\
r>0")
def a(
n,e=a,
o=b):
if (
n%2==(
1)):e(
n)
else:
o(n)
I wonder if it would be possible to get rid of functions entirely using inlining
you have to take into account that you can't run out of identifier names for the functions or for the variables, so you have to be very stinky when naming something that is not temporary
can't you directly operate on locals/globals, so since you are now using strings identifier names aren't an issue?
s=[]
v=vars
b=v(v(
)["__\
built\
ins__\
"])
g=b["\
getat\
tr"]
i=b["\
__imp\
ort__"
]
t=g(s,
"appe\
nd")
p=g(s,
"pop")
d={}
this would be a nice bootstrap
oh right, you can, and don't need a seperate dictionary
def\
a(b\
):
(
...
)
fair
Wait you can do this?
yes
def\
``` is allowed?
yes
wow that is terrible, thanks
We just figured we would use a list as a return value stack
yep
and the short-circuiting? are we separating everything into nested conditions that lead to more functions to save space in identation for nested comparisons or are we making a decorator to insert returns when some magic operation (like A>B) is done?
first thing would make us waste space in idents, second thing is just too much work I think
thinking it should be able to do anything by calling another function to keep everything indent of 1
but not sure it is possible
it should
we could have the return value stack include if it's returning from a return statement
so that could be checked for shortcircuiting
Well, if b return value from c
Just b don't do any thing to the return stack
we would have to insert and else and put the rest of the function that's not on the if, inside other function and call it from that exec
Well, we can for each expression that needs to evaluate Boolean, just calculate the Boolean and else is just opposite of that value
or
o=(1
if v
else
2)
this is selection and should be possible to be done in any case
we index a list from the boolean so that we don't waste a single extra ident?
that's clever
only when we don't need short circuiting
oh wait, this cannot apply when the code is indented
but it can be done by a one line function (in multiple line) to add to the return stack
yeah, the else is already 4 chars
Ifs are translatable to ternaries, so they are trivial to fix. The problem is nested fors/whiles, especially ones that contain return statements.
Or you could turn a list of if-elif-elses into indexing
Some fors could be turned into generators, but what about whiles, especially infinite ones like while 1:?
def\
a(x,
y):\
t(
...
)
The ... can be a 4 character expression
So it can be done by calling another function to calculate the expression and append to return stack, then use the value from return stack to do other thing
So it's a short circuit selection
while <condition>:
...
``` -> ```py
for _ in iter(lambda: <condition>, 0):
...
then the for loop can be made into a generator
breaks and continues make things more complicated
but ternary expressions and flag variables that the condition checks ought to take care of that
But we don't have function that can properly return
In 4 column
But we might able to make so at the end, it call the expression function, then the iter take data from the function stack from pop
c()
for _ in iter(p,0):
...
c()
This should be easier ?
yeah the function can be .pop of the return list
sorry wrong reply
this
I tried to sketch up what it would look like, but problem: we don't have an actual return, but iter with a sentinel wants a function with an actual return
Check this
p is s.pop, where s is the return stack
c is the imaginary call of the expression
So it would be the partial of pop on the output object?
Oh, I just noticed a issue, what should we do in filter where it needs a proper function to filter?
Hopefully not re-implement them
we probably do end up needing to reimplement them
or find a way to get functions properly returning
I think that would need min 7 for lambda, if it's possible to use backslash, or 9 for proper return
Which isn't much fun
I will see if I have any thoughts about re-implement while shower
lambda does work for 7 ```pycon
x=
... (
... lambda
... :1)
print(x())
1
and unless there is another way that would be it, since too many things need a proper return. (basically all dunders)
alternatively we could try to find a way to define functions in a pointfree manner
What does that mean?
consider f(x) = (√x)/2 and g = (half ° sqrt)
these are equivalent definitions, but f explicitly operates on a point in its input space x, while g doesnt
any function defined this way will have a return value as long as all of the functions that it is composed of have a return value
if we can define functions this way, starting from builtins that we know have return values, we can build functions that return values
so the issue just becomes, how does one implement function composition with at most 4 characters per line
I need a explanation of how function composition would work in 4 character
That's the question
Apperantly compose does exist since 3.12 from test.test_zipfile._path._functools import compose https://stackoverflow.com/questions/77425962/how-to-compose-functions-through-purely-using-pythons-standard-library
💀
from test.test_zipfile._path._functools import compose is weird
There are a bunch of other very cursed/cool answers in that post as well
from signal import _int_to_enum as rcall
from functools import reduce, partial
def increment(x):
return x + 1
def double(x):
return x * 2
double_and_increment = partial(reduce, rcall, [double, increment])
print(double_and_increment(1))
functools.reduce(function, iterable, [initial, ]/)```
Apply *function* of two arguments cumulatively to the items of *iterable*, from left to right, so as to reduce the iterable to a single value. For example, `reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])` calculates `((((1+2)+3)+4)+5)`. The left argument, *x*, is the accumulated value and the right argument, *y*, is the update value from the *iterable*. If the optional *initial* is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If *initial* is not given and *iterable* contains only one item, the first item is returned.
Roughly equivalent to:
functools.partial(func, /, *args, **keywords)```
Return a new [partial object](https://docs.python.org/3/library/functools.html#partial-objects) which when called will behave like *func* called with the positional arguments *args* and keyword arguments *keywords*. If more arguments are supplied to the call, they are appended to *args*. If additional keyword arguments are supplied, they extend and override *keywords*. Roughly equivalent to:
```py
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
People thought of this curse way is crazy
Now the question is that since composition is fairly trivially possible, how to re-write everything point free
Also which one to use, since the actual composemight not always be present, but abusing _int_to_enum stops ValueError propigation
That is another big issue we haven't talked about: what do we do about try/except statements?
This works, but is again 7 long ```pycon
try:
... raise ValueError
... except
... ValueError:
... print(1)
...
1
Using enter and exit dunder can absorb error, but it needs 5 character min, and 6 when in function
I think there are some function in stdlib that silent error
Idk if it's useful
!e help("keywords")
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Oh, another issue, raising error need 6 character, unless there are function in stdlib handle that
And async function / await also require 6 chatacter
you can raise any error you want in 4 ```py
v=
vars
b=v(
v()[
'__
bui
lti
ns_
_'])
b['
get
att
r'](
( ()
for(
)in(
)) ,
'th
row'
)(b[
'Ru
nti
meE
rro
r'])
import timeit
setup_code = """
from __main__ import list_append, list_set
n = 10_000
"""
def list_append(n):
result = []
for i in range(n):
result.append(i)
return result
def list_set(n):
result = [0] * n
for i in range(n):
result[i] = i
return result
append_time = timeit.timeit("list_append(n)", setup=setup_code, number=100)
set_time = timeit.timeit("list_set(n)", setup=setup_code, number=100)
print(f"list_append time: {append_time:.5f} seconds")
print(f"list_set time: {set_time:.5f} seconds")
what's this weird code? I wrote those two functions and asked chatgpt to give code to check which is faster
I remember using that (()for()in()) for something else
does timeit uses processes? Last time I saw main usage was when using multiprocessing
It is just using a genexpr to raise an error by calling .throw(Exception)
chilaxan had an implementation of try/except statements as an expression a while ago
thats probably a good starting point
I found this #esoteric-python message
tbh I don't understand context managers enough to understand if that can be made fully equivelant to try/except
Same with async, I don't understand it enough to tell if it can be made 4 wide
Ah
When exit, it would give you 3 parameter which would tell you what state of the code inside the context manager end in
And if you return True it would stop the propagation of error?
Yep
3 parameter:
Exception type
Exception
Exception traceback
If it ends with a. error, it would have those values, if it doesn't end with an error, all of them is None
E.g.
timeframe%2Ftimeframe.py lines 162 to 168
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException],
exc_tb: Optional[types.TracebackType]) -> bool:
if exc_type is None or exc_type == IterationCompleted:
self.end()
else:
self.failed(tb='\n'.join(traceback.format_exception(exc_type, exc_val, exc_tb)))
return True```
Which would call the perspective exit handler and pause propagation of any error
neither do i, but chilaxan is a wizard so im willing to trust what they say lol ^^
So with that, looking through the keywords list everything besides async/await should be fully 4-char-wideable
nope
timeit afaik uses two nested python for loops with benchmarking functions
Hmm, but it use 3 lambda, not sure if it can be replaced with partial function🤔
Or composite function
we can replace all lambdas into normal functions, which we should be able to make into 4-char wide
ok, then sure then
Also I think I might know how it work
it basically inherit ContextDecorator, which is a class that act as a decorator but function as a context manager, where when it exit, it silence the error through implementing __exit__ and always return True
should be possible to make a form of function which ignore whatever parameter given and return True
if we don't care specific error
If we do care about error, we need to get -1 from None through function composition
Umm, function composition doesn’t work with more than 1 argument
what's the worst, most painful, type-hinting you can come up with?
Write an itertools.product, that works as it would via duck typing for .count(), .index(), __getitem__, __len__ is fairly miserable
that is, supports each of the methods individually if all the passed iterables support it
well, it's a bunch of type vars but nothing crazy if I'm not mistaken
and a whole bunch of protocols
I ask it because I remembered how I made a function whose return type depended on the args and the returned-typed structure and types depended on them as well, and for marking it didnt exists I put it inside an Optional and got like a 2 entire lines of typehiting iterators inside iterators inside generators whose sequences could have one type, another, or it could not be a sequence but another generator and so on
I asked how to simplify it and got roasted for about an hour
now I look back at it and hope I recover that piece of trash
and I didnt know overloads
It is a quadratic number of overloads, since remember that you need to do the whole
def method(a: Iterable[T], b: Iterable[T1], c: Iterable[T2]) -> Iterable[T, T1, T2]
```for every protocol and every product arg length up to a reasonable bound. And that isn't even considering the pain of actually implementing all of it type safely (which I'm mostly sure is impossible)
I gave up and just have Iterable and Sequence and a non-typesafe impl.
I may do it later with not a single overload
go for it, I'm curious if there's a good solution
who said it was going to be good?
anything that's not quadratic is a good solution in my book
wait a class or a method?
It needs to be a class
my impl works by having a class that just assumes all iterables in product are the same type, and unsafely casting
and then it's just linear to the number of protocols in __init__
if I use Generic[T] instead of normal typevars is because my default python interpreter is ancient
can a function return Generic[T]?
ummm
im cloning the repository which has the ps3 linux kernel (6.13)
gulp 10598185 files
Chilaxin is indeed a wizard and has been for a very long time
import tkinter as t;from tkinter import ttk
from bs4 import BeautifulSoup as B
class H:
def __init_subclass__(C,**K):setattr(C,'__getattr__',lambda s,n:s.__dict__.get(n)or getattr(t,n));super().__init_subclass__(**K)
def __init__(s,h):
r=t.Tk();s.__dict__.update(h=h,r=r,f=('Helvetica',),m=t.Frame(r,padx=20,pady=20,bg='#f5f5f5'));r.title("F");r.geometry("600x800");s.m.pack(f=t.BOTH,e=1)
for k,v in {'g':'c','fr':t.Frame,'lb':t.Label,'bt':t.Button,'cb':ttk.Combobox}.items():setattr(s,k,v);s._el=lambda x:x and x.name
def c(s,p,e):
x=e.get_text(strip=1);y=e.name;b,cc='#f5f5f5','#2d3436'
if y=='div':w=s.fr(p,padx=10,pady=10,bg=b);w.pack(f=t.BOTH,e=1);[s.c(w,i)for i in filter(s._el,e.contents)]
elif'h'in y:s.lb(p,text=x,font=(*s.f,26-int(y[1])*2,'bold'),bg=b,fg=cc).pack(pady=10,fill=t.X)
elif y=='p':s.lb(p,text=x,wraplength=500,font=(*s.f,11),bg=b,fg=cc).pack(pady=5,fill=t.X)
elif y=='input'and'text'==e.attrs.get('type','text'):w=t.Entry(p,bg='#fff',fg=cc,insertbackground=cc,relief='solid',bd=1);e.attrs.get('value')and w.insert(0,e.attrs['value']);w.pack(pady=5,fill=t.X,padx=5)
elif y=='button':s.bt(p,text=x,bg='#4299e1',fg='white',relief='flat',padx=20,pady=5,font=(*s.f,10,'bold')).pack(pady=10)
elif y=='select':w=s.cb(p,values=[o.text for o in e.find_all('option')],state='readonly');e.find_all('option')and w.current(0);w.pack(pady=5,fill=t.X,padx=5)
elif y=='table':
tf=s.fr(p,bg='#e2e8f0');tf.pack(pady=10,fill=t.BOTH,e=1,padx=5)
for i,r in enumerate(e.find_all('tr')):
rf=s.fr(tf,bg='#e2e8f0');rf.pack(f=t.X)
for z,c in enumerate(r.find_all(['td','th'])):
fg='black'if i else'white';bg='#fff'if i else'#4299e1'
s.lb(rf,text=c.text.strip(),bg=bg,fg=fg,relief='solid',borderwidth=1,padx=10,pady=8,width=15,font=(*s.f,10,'bold'if z==0 else'normal')).pack(side=t.LEFT,fill=t.BOTH,e=1)
def cv(s):[s.c(s.m,i)for i in filter(s._el,B(s.h,'html.parser').contents)]
if __name__=='__main__':H("""<div><h1>My Form</h1><p>Please enter your name:</p><input type="text" name="name" id="name" value="p"><p>Choose your favorite color:</p><select><option value="red">Red</option><option value="blue">Blue</option><option value="green">Green</option></select><table><tr><th>Name</th><th>Age</th></tr><tr><td>John Doe</td><td>30</td></tr></table><button onclick="submitForm()">Submit</button></div>""").cv();t.mainloop()
``` simple html to python (tkinter) converter
Does esoteric python have to do with Python frameworks like say RPython
!e ```py
def fib(x):
if not x >> 2:
return ~hash(~x)
return fib(x - 1) + fib(x - 2)
for i in range(10): print(fib(i))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
python abuse, yes
?

I am wondering your thought process when you decided to make this
"wait, the first 4 results look like the fibonacci sequence..."
talking about ~hash(~x)
What about the Liberace sequence tho 
@karmic pumice I may be onto something ||```py
import codecs
class What(str):
def contains(self, other): return True
w = codecs.open(1, What("w"), "rot13")
w.write("foo\n") # prints sbb\n
what's "it"
how to get 68 here: https://code.golf/rot13#python
naive is 69
if i could see just one solution from that site it would have to be brainfuck or hexdump
im 10 away on hexdump and 14 on brainfuck
ive spent weeks just staring at both of them
search through libraries then
wdym
maybe there's something other than codecs?
oh i thought you were talking about these two
How about this.d?
Would require suppressing stdout though
import sys
x,y='ABCDEFGHIJKLM','NOPQRSTUVWXYZ'
print(''.join(dict(zip(x+y+(x+y).lower(),y+x+(y+x).lower())).get(c,c)for c in'\n'.join(sys.argv[1:])))
149c
||```py
i=import;s=i('sys');o,s.stdout=s.stdout,None;[o.write(i('this').d.get(c,c))for c in'\n'.join(s.argv[1:])]
109c using your idea
v
I wonder if in golf its ever useful to do exec(open(...)) 🤔
for example this is an alternate (albeit long) way to do rot13 if passed through stdin
import encodings.rot_13 as e
exec(open(e.__file__).read())
What are codecs erm in Python terms. I assume it is different outside of Python? 
codecs define how to read bytes into strings that are (generally) python source code
and also str->bytes ofc
but some codecs are special and do str->str like rot13
if you haven't figured out a 68 then try looking for a similar function to codecs.encode in codecs
oh
i found it
thanks
The thing is I have
I've tried codecs.open, but the need to translate out of bytes for stdout makes it too long
I tried iterencode, but it was longer
the 68 I found uses one of those
I did make like 4 or 5 different 69s before finding it though
Is it just me or can you not use the rot13 encoder with open()?
writelines restricts to str only input
but the passes it to write() as bytes
write() literally can't work
!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.write(b"bytes")
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | handle.write(b"bytes")
004 | File "<frozen codecs>", line 727, in write
005 | File "<frozen codecs>", line 377, in write
006 | File "/snekbin/python/3.12/lib/python3.12/encodings/rot_13.py", line 15, in encode
007 | return (str.translate(input, rot13_map), len(input))
008 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
009 | TypeError: descriptor 'translate' for 'str' objects doesn't apply to a 'bytes' object
Can't translate because rot13_map is string only
!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.write("string")
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | handle.write("string")
004 | File "<frozen codecs>", line 727, in write
005 | File "<frozen codecs>", line 378, in write
006 | TypeError: a bytes-like object is required, not 'str'
rejects because not given bytes
so codecs.open() literally doesnt' work with rot13
!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.writelines([b"bytes", b"bytes"])
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | handle.writelines([b"bytes", b"bytes"])
004 | File "<frozen codecs>", line 731, in writelines
005 | File "<frozen codecs>", line 385, in writelines
006 | TypeError: sequence item 0: expected str instance, bytes found
!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.writelines(["string", "string"])
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | handle.writelines(["string", "string"])
004 | File "<frozen codecs>", line 731, in writelines
005 | File "<frozen codecs>", line 385, in writelines
006 | File "<frozen codecs>", line 378, in write
007 | TypeError: a bytes-like object is required, not 'str'
So it can't be open
but the mandatory part for iterencode is 55 characters
Is there a way to print a generator in 13 characters that I don't know?
_ _
print(*_,sep="\n") is 17
for i in _:print(i) is even longer (19)
print("\n".join()) is the shortest but still too long (17)
*map(print,), oh fuck you
I tried that one and it was longer before goddamnit
thats how golf is sometimes
the wiki on the website has a lot of good tips like that
Grok said golf is abusing Python’s syntax for lack of a better word. That sounds so bad
grok?
grok doesn't get it
!e print(int(+--~~~+~-+~--+-~~-~++--~--~~-~+--+-~+----~-~~+-+++-~~+~++---+~~+-+type('',(),{'__init__':lambda s:(s.__setattr__('v',0),s.__setattr__('l',0),None)[-1],'__pos__':lambda s:(s.__setattr__('v',s.v+3**(s.l)),s.__setattr__('l',s.l+1),s)[-1],'__neg__':lambda s:(s.__setattr__('v',s.v+(-1)*(3**(s.l))),s.__setattr__('l',s.l+1),s)[-1],'__invert__':lambda s:(s.__setattr__('l',s.l+1),s)[-1],'__str__':lambda s:str(s.v),'__repr__':lambda s:str(s),'__int__':lambda s:s.v})()).to_bytes(13).decode('ascii'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
jolly
how do you even come up with this
i found out that you can chain unary ops without parentheses, and wrote this:
class T:
def __init__(self):
self.val = 0
self.pos = 0
def __pos__(self):
self.val = self.val + 3**(self.pos)
sef.pos += 1
return self
def __neg__(self):
self.val = self.val + (-1) * (3**(self.pos))
self.pos += 1
return self
def __invert__(self):
self.pos += 1
return self
def __str__(self):
return str(self.val)
def __int__(self):
return self.val
__repr__ = __str__
and then made it into a one-liner
T=type("T",(),{"__init__":lambda x:exec('x.val=0;x.pos=0'),"_r":lambda x,*a,**b:x,"__pos__":lambda x:x._r(exec("x.val=x.val+3**(x.pos)",{"x":x})),"__neg__":lambda x:x._r(exec("x.val=x.val+(-1)*(3**x.pos)",{"x":x})),"__invert__":lambda x,x._r(exec("x.pos+=1",{"x":x})),"__str__":lambda x:str(x),"__int__":lambda x:x.val})
For one-linear, you mean this?
not test btw
oof
!e ```py
print(int(+--~+~-+~--+--~++--~---~+--+-~+----~-+-+++-+~++---++-+type("",(),{"init":lambda x:setattr(x,'z',z:=[0,0])or setattr(x,'a',z.append)or setattr(x,'p',z.pop),"pos":lambda x:x.a(3**(z:=x.p())+x.p())or x.a(z+1)or x,"neg":lambda x:x.a(-3**(z:=x.p())+x.p())or x.a(z+1)or x,"invert":lambda x:x.a(x.p()+1)or x,"repr":lambda x:'%i'%x,"int":lambda x:x.z[0]})()).to_bytes(13).decode('ascii'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
I like the contrast between golfing and obfuscation here lol
i wanted to golf but the way i wanna do it wasn't with a 1 liner ¯^¯
!e ```py
class T:
def init(s):s.v=s.p=0
def pos(s):s.v+=3s.p;return~s
def neg(s):s.v-=3s.p;return~s
def invert(s):s.p+=1;return s
repr=lambda s:'%i'%s;int=lambda s:s.v
print(int(+--~+~-+~--+--~++--~---~+--+-~+----~-+-+++-+~++---++-+T()).to_bytes(13).decode())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
that was what i had in mind
!e
class N(int):__pos__=lambda s:N(s*3);__neg__=lambda s:N(+s+1);__invert__=lambda s:N(-s+1)
print((-~+++-~--+-+-++~+--~+++~~----++~+~-++~~~--~--+-+~~~-+~-~+~~++++~-N()).to_bytes(13).decode())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
golfed 👀
very nice
nice, but it cant have negative numbers because its not balanced ternary
-s+1 make it negative? and then you can use +s+1 to move closer to 0 in the number line
!e
print('Hello world!')
-169
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
🤯
code
!e
quit('Hello world!')
-1
:x: Your 3.12 eval job has completed with return code 1.
Hello world!
TIL python bot uses _sitebuiltins
wait
!e ```py
print(copyright)
ooh
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | Copyright (c) 2001-2024 Python Software Foundation.
002 | All Rights Reserved.
003 |
004 | Copyright (c) 2000 BeOpen.com.
005 | All Rights Reserved.
006 |
007 | Copyright (c) 1995-2001 Corporation for National Research Initiatives.
008 | All Rights Reserved.
009 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/NZXQNX63S2SKDB43GC6AW662G4
!e ```py
import this
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/YNTU5QMIXLHWEQYJ3LCFEEV6OA
I’m relatively new to learning Python, but I can’t unsee what I’ve seen in this channel.
I must learn the cursed code…
not python in general, but obfuscated (so code made to be unreadable) and golfed (code made to be very short) python code
In software development, obfuscation is the practice of creating source or machine code that is intentionally difficult for humans or computers to understand. Similar to obfuscation in natural language, code obfuscation may involve using unnecessarily roundabout ways to write statements. Programmers often obfuscate code to conceal its purpose, l...
Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that solves a certain problem. Code golf challenges and tournaments may also be named with the programming language used (for example, Perl golf).
(and other esoteric code. Not necessarily golfed or obfuscated)
Could anyone help me make this shorter? Currently 255b py t,P,R,b=1,print,range,[*' '*7+'\n']*6 while t: while(c:=int(input()))//7:P('?') for j in R(40+c,~0,-8): if'?'>b[j]:b[j]=p='YR'[t%2];t+=1;break P('',*b,sep='|') if any(p*4in''.join(b[i::j])for i in R(48)for j in(1,7,8,9)):P(p);t=0 if t>42:P('=');t=0
is this an exercise in absurdity like making puzzles and stuff or is there an actual functional need for it
it's just fun
ya it is fun
I learn things about the language that I would never have thought about otherwise
thank god for GPT I my ADHD would lock me down at the second while
what does it do? 🤔
almost every channel here is for python in some form
oh is it connect 4
would //7 -> >6 accomplish the same?
i think this should work for 248
t,P,R,b=1,print,range,[*' '*7+'\n']*6
while t:
while(c:=int(input()))//7:P('?')
for j in R(40+c,~0,-8):
if'?'>b[j]:b[j]=p='YR'[t%2];t+=1;break
P('',*b,sep='|')
if t>42:t=P('=')
if any([p]*4==b[i::j][:4]for i in R(48)for j in(1,7,8,9)):t=P(p)
I wonder if it would be possible to use regex to search for the 4 in a rows?
can also replace the (1,7,8,9) by a byte string but I don't know much discord likes that
it would be fine
discord wouldnt properly display it, but if you copy and paste it it'd still work ^^
ah that's a nice trick
probably, I might look at that tomorrow
245
t,P,R,b=1,print,range,[*' '*7+'\n']*6
while t:
while(c:=int(input()))//7:P('?')
for j in R(40+c,~0,-8):
if'?'>b[j]:b[j]=p='YR'[t%2];t+=1;break
P('',*b,sep='|')
if t>42:t=P('=')
if 4*[p]in[b[i::j][:4]for i in R(48)for j in(1,7,8,9)]:t=P(p)
ignore that
while(c:=int(input()))//7:P('?') -> c=['',c:=int(input())][0<=c<7]
2 chars less at the cost of raising an error instead looping if receiving a number outside the expected range
or c='0123456'.index(input())
depends on if @stable hornet is fine with this change to the api
the reason I think it's a fine change is because we can input a non-int to raise an error, so we might as well raise error with every bad input
wise assessment
yeah I agree with what Andreaw said
I kinda liked printing a ? if it was out of range but my rules were fairly arbitrary anyway
i don't think it makes a difference though
oh i see
Is interpreted vs compiled the separation layer between C and Python?
separation layer?
Hey ceweal. The separation layer between Python and C is I was thinking about how it comes down to abstraction. Python takes care of many details like memory and types, (interpret) making it simpler to use, while C gives you more direct control over the hardware (compile)
Basically, no
Python is higher level because it was designed as a higher level language. It would still be higher level if it were compiled, as e.g. Nuitka does.
i guess?
Idk what Nuitka is I’ll check it out
It’s a bit too early for this in my little corner of the world. Let’s revisit this another time 😂👌
I think you are a bit confused. Python the language is a fairly abstract idea, that can be implemented in any language. See the Alternative Python Implementations page. CPython just happens to be the most popular implementation. There also isn’t a clean separation layer between Python and it’s implementation when using CPython, since using implementation specific features can be useful. In terms of C vs Python, they are completely separate programming languages, where the most popular implementation of Python happens to be using C.
Very confused
- Python, a programming language
- CPython, an implementation of Python using C
- C, a programming language
These are 3 separate but related things, which is why talking about the “separation layer between Python and C” doesn’t make much sense. Aside from the CPython implementation, C and Python are completely separate languages.
Yeh I know about all of that. Separation layer may have been the wrong word. Abstraction is the better word
High vs low level programming
Not even abstraction, CPython isnt relevant to C except it is implemented in C
Python code run in a python virtual machine
CPython
[X] - Build on top of
[✓] - Build with
C
And also, low level programming doesn't include C either, C is still high level language
What make CPython isn't abstract from C is there are not much related to C, it is just The language C is used to implement a software, which is the CPython interpreter, that implement the Python language specification to run the python code -> bytecode in the python virtual machine
low and high level are relative
claiming something or other isnt low or high level is pointless and subjective
whats important for the context of this discussion is that C is lower level than Python
what is esoteric python?
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
esoteric languages are usually silly/proof of concept like brainfuck which aren't made to be used for actual software
The definition Google cites of the word esoteric is: “intended for or likely to be understood by only a small number of people with a specialized knowledge or interest”
So that and the Python programming language.
Can we update the channel description admin
admin overlords
https://en.wikipedia.org/wiki/Low-level_programming_language
Unless you think Wikipedia is inaccurate in this instance, which there are nothing I could help with, as I couldn't find a better place for this definition
A low-level programming language is a programming language that provides little or no abstraction from a computer's instruction set architecture; commands or functions in the language are structurally similar to a processor's instructions.
A low-level programming language is a programming language that provides little or no abstraction from a computer's instruction set architecture; commands or functions in the language are structurally similar to a processor's instructions. Generally, this refers to either machine code or assembly language. Because of the low (hence the word) abs...
Because it isn't being used as comparison e.g. lower or higher
This is the more traditional notion of low level language where it's basically just assemblers
^^
what to?
i mean tbf #esoteric-python is like a sub-#internals-and-peps sometimes, weirdly written python other times
Idk let’s poll the Python community or server
it's called esoteric for a reason, i don't think that'll work
What you don't like the channel description for
Gore and weirdness 😂 that could go in a channel called dark arts or something I don’t know 💀
That is like the literal correct name for everything tho 
yes, #esoteric-python
i don't see why general weirdness doesn't belong in the weirdness channel
yeah that's the point
better answer that doesn't use a dictionary definition for "esoteric": obscure, unconventional, unintended, and unexpected ways to use python
I wonder what the history of this channel is for it to get this description
its not like it was added after
it was created to be this
Is Hawaii esoteric pizza?
nowadays, "low-level" typically refers to a language with either
a) minimal abstractions over hardware concepts (C, assembler, etc)
b) native features for accessing hardware and using hardware concepts (pointers, byte-level data transmutation (reinterpret_cast), etc)
some languages have minimal abstraction and native hardware-level features (primarily C)
and some offer hardware-level interfaces and high-level abstractions like OOP or allocated data types (C++, Rust, C#, etc)
I mean, modern C is more about driving the compiler than hardware, with things like restrict, attributes, ...
just saw
def f(x: (1).__class__.__base__.__subclasses__()[-1].__init__.__builtins__["print"]("Hello world")):
pass
on https://peps.python.org/pep-0749/#which-expressions-can-be-stringified
now here's a challenge since this chat is not active
can y'all code and golf minesweeper with pygame, such that all code executes in typehints?
no eval
nor exec
No exec, no eval
def f(x: (open("x.py", "w").write("source code goes here"), __import__("x"))):
pass
you can put anything in typehints even defintions using walrus, so idt it'd be too difficult ```py
def a(b: print("hello world")): ...
...
hello world
i say it's easy but I won't be the one try to make it
walrus?
really?
oh they changed 3.14
i see
and how would you do a loop?
and this beats the point
list comp
!e ```py
def a(b: [print("Hello, World")for{}[()]in iter(int,1)]):pass
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | Hello, World
002 | Hello, World
003 | Hello, World
004 | Hello, World
005 | Hello, World
006 | Hello, World
007 | Hello, World
008 | Hello, World
009 | Hello, World
010 | Hello, World
... (truncated - too many lines)
Full output: too long to upload
pretty much use any one liner trick inside the typehint
one-expression* trick but okay
!e
def a(b: list((print(1)for i in range(12)))):
...
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/JZO2XBYVPBVX3Q6YM4YBTN333I
same energy as that one w3schools sample
scary
there couldn't be a worse site
any-number-of-only-expression-trick*
but yeah with walrus and with iter(int, 1) is easier than I thought
i don't think you can use any number of expressions in a type hint but sure
well including the inner ones maybe
def f(a: expr1, b: expr2, c: expr3, ...) -> yet_another_expr: ...
ah
or
so just put it all in type hints
def f(a: expr1, b: expr2, c: expr3, ...) -> yet_another_expr: ...
def d(a: expr1, b: expr2, c: expr3, ...) -> yet_another_expr: ...
def e(a: expr1, b: expr2, c: expr3, ...) -> yet_another_expr: ...
even then, how would that looked golfed
!e ```py
def f(a: print([x + 4 for globals()['x'] in [2,5]]*x)): pass
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[6, 9, 6, 9, 6, 9, 6, 9, 6, 9]
okay
unintentionally picked some nice numbers but i guess assignment still works fine
I don't think you can unpack nicely with walrus
that's why we use magic called comprehensions
but if you were to golf the minesweeper or snake or whatever, y'all always do smth like
s,L,k=0,print,range
or sum like that, you can't do that here, and a list comp is longer than just declaring them separatedly
and infinite loops would be a challenge to golf if iter(int, 1) didnt exist
and function calls would also be a challenge without walrus
!e ```py
from pathlib import Path
print(
Path('.') == Path('.').parent
)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True
hmm
!e
print(import("pathlib").Path(".").parent)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
.
Hmm, it just count . as root?
!e
import pathlib
print(pathlib.Path("/").absolute().parent)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
/
Probably
!e
from pathlib import Path
print(Path(".").resolve())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
/home
relative paths are purely lexical until you resolve them
why isn't parent of . equal to ./.. ?
because the . is not resolved
like anonymousdapper said
!e
import pathlib
print(pathlib.Path("../"))
print(pathlib.Path("../").parent)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ..
002 | .
I just got the most cursed piece of code I've ever written working, and I need to share it: https://paste.pythondiscord.com/Z7BA
It has all the things, Python, Rust, WASM, and JavaScript. By base64 encoding the WASM output from the wasm-bindgen'd rust code, it can be converted to a blob URL by javascript, which then dynamically builds and adds modules to import from that instead of the normal paths, doing the same for the javascript, resulting in this rustwasm example successfully running from a single HTML file.
!e
(lambda _, __, ___, ____:
eval(''.
join([bytes([_____]).
decode() for
_____\
in [(____+((___<<___<<_)-(___<<_))),(____+((___<<___<<_)-___)),
(____+(___<<_)+_),(____+((___<<___<<_)-(___<<___))+(___)),
(____+(___<<___<<_)),((___<<___)+(___<<___<<___)),((___<<___<<___)+___),
(____+(___<<_)),(____+_),(____+(___<<___)),(____+(___<<___)),
(____+(___<<___)+___+_),(___<<___<<___),(____+(___<<___<<_)+
(___+_)),(____+(___&___&___^_|___)+(___|_|__+___)+
(___|_)+___),(____+(___<<___<<_)-(___+___<<_)+
(___<<___)-___),(____+(___<<___)),____,
((___<<___<<___)+___),((___<<___<<___)+(___<<___)+_)]]))
)(_:=([([map(int,
(__builtins__.len({}.__iter__.
__repr__.__subclasshook__.
__init__.__name__).__subclasshook__.
__init__).__str__())])]!=
{...==...:[...,...][0:[]!=[]==[
{}.__iter__.__subclasshook__]]}),__:=~-_,(_<<(_^__)), ((((((_ << _ << _)
>> __ >> __ >> __) **
(_ << _ << _)) >> _)-(_
<< _ << _ << _ << _ << _)+(_<<_<<_))))```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
that one tickles my brain
not because of its complexity just the pretty heiroglyphics it came out to be XD
that was the point XD
What integer obfuscator you used?
Guys i have a problem where when i build an app using pyinstaller , the app i have currently selected or windows explorer automatically closes
not the place to ask
🥴ok
!e ```py
=lambda :ord([:=not _][][])+!=-~+<<<<~*~_ or not _+"Hello World!"
print(next(filter(('g',).le,id.self.dict.items()))~(not _)[~(not __)])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:3: DeprecationWarning: Bitwise inversion '~' on bool is deprecated and will be removed in Python 3.16. This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool. Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.
002 | print(next(filter(('g',).__le__,id.__self__.__dict__.items()))[~(not _)](__:=_.__code__,[*filter(_,dir(__))][len(len.__name__)])[~(not __)])
003 | Hello World!
they should have true = -1 and then they're the same thing
backwards incompatible
or scrap two's complement altogether (PSF should release python-tailored cpus, PHF!)
python bytecode on bare metal
I mostly write cursed programs when I procrastinate
When I'm working on my game or other project I like and find an extremely annoying bug, I just start writing weird programs to "relax" from debugging
lol
omg
?
hey guys i want to get the name of a class
cls.__name__?
it may or may not get the name of your class :)
Depends on how you define the "name"
for posterity:
def malloc(initial=None):
def a():
x = initial
def b():
nonlocal x
return x
return b
return a().__closure__[0]
cell = malloc(4)
print(cell.cell_contents)
cell.cell_contents = 10
print(cell.cell_contents)
what does it do?
it's a pointer, always exactly one value, unlike python lists which can have any number of values.
!e ```py
def ptr(initial=None):
x = initial
return (lambda: x).closure[0]
cell = ptr(4)
print(cell.cell_contents)
cell.cell_contents = 10
print(cell.cell_contents)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 4
002 | 10
!e ```py
from types import CellType as ptr
cell = ptr(4)
print(cell.cell_contents)
cell.cell_contents = 10
print(cell.cell_contents)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 4
002 | 10
it can be simplified
I wonder if (lambda x=None: (lambda: x).__closure__[0]) would work, then?
I do not understand the purpose of this at all 
!e ```py
ptr = lambda x=None: (lambda: x).closure[0]
cell = ptr(4)
print(cell.cell_contents)
cell.cell_contents = 10
print(cell.cell_contents)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 4
002 | 10
yup
Quickest way to make a Cell object, which is python's hidden smart pointer object
class ptr:
__slot__ = ("cell_contents",)
def __init__(self, v):
self.cell_contents = v
cell = ptr(4)
What is the difference
Ignore any mistakes I might have made there
no difference pretty much
but CellType is implemented in C and is widely used in internal C code
Ah ok
the most important thing is implemented in C, which overpowers any python implementation!! >:<
It use C btw /j
little golf challenge: make a function complete which given a string made up of only <>[](){} closes all the unclosed brackets. Some example testcases:
assert complete('((({}') == '((({})))'
assert complete('(<<[({})][][]{') == '(<<[({})][][]{}>>)'
assert complete('()()') == '()()'
Here's my solution:
||
172 chars/bytes: ```py
complete=lambda d,s=[],f={"(":")","{":"}","<":">","[":"]"}:[(s:=s+[x])if x in"([{<"else(s:=s[:-1])if f[s[-1]]==x else 1 for x in d]and"".join([d,[f[x] for x in s[::-1]]])
It's a golfed version of this code: ```py
def complete(data):
stack = []
flip = {"(":")","{":"}","<":">","[":"]"}
for x in data:
if x in "([{<":
stack.append(x)
elif flip[stack[-1]] == x:
stack.pop()
for x in stack[::-1]:
data += flip[x]
return data
||
This assumes that )( is an invalid input, ie that only >])} will have to be added.
you can assume that there are no mismatched bracket and remove the elif condition
complete=lambda x:x.translate({40:'()',41:'()',60:'<>',62:'<>',91:'[]',93:'[]',123:'{}',125:'{}'})
I don't know how that would help my existing solution, but that did make me come up with another solution that's the exact same length: ||```py
def complete(d):
t=[d,1]
while(t:=import("re").subn(r"()|{}|[]|<>","",t[0]))[1]:...
return"".join([d,[{"(":")","{":"}","<":">","[":"]"}[x]for x in t[0][::-1]]])
Not using a lambda since I can't remember how to make while loops work in those
iter
close, but doesn't pass tescases 😉
it meets the definition as given /shrug
make a function
completewhich given a string made up of only<>[](){}closes all the unclosed brackets.
I know iter, and the iter(int,1) trick for infinite loops, but I don't remember how to/if you can make one that stops.
iter(f, x) yields values of f until f returns x
iter(boolean_function, False) yields values of boolean_function until it returns False
for example
like a while loop ^^
if you have testcases that you want the function to pass, you ought to have included those in the requirements silly
how would you suggest to phrase it better?
wdym
if my solution doesnt do what you wanted, then i dont know what you wanted in the first place
so i cant really suggest a better phrasing
gigagon maybe you could clarify?
maybe like this: given a string with some amount of various parens, return a new string with balanced parentheses. The given string must be a prefix of the returned string. The returned string must be the one with the smallest length satisfying these constraints (to prevent introducing new parens)
Maybe make it so the test cases are formatted like assert complete("") == "" idk it made sense to me on first read
ah
i read those as an example of a function that satisfied the requirements
not the Normative Function Return Values
A "robust" solution will only add chars that match with currently unmatched brackets, and a "robuster" one will add a minimal number of such chars
||133b, passes without technicality ```py
def complete(d):
d,s=d.encode(),0
for c in d:s+=[f:=s.pop(),c]-~-(0<c-f<3)
return(d+bytes(x+1+(x>40)for x in s[:0:-1])).decode()
||113b ```py
def complete(d):
s=[0]
for c in d:c=ord(c);s+=[f:=s.pop(),c+1+(c>40)]*(f!=c)
return d+bytes(s[:0:-1]).decode()
83 bytes long, passes the tests:
||```py
complete=lambda x:x+"".join(b*(x.count(a)-x.count(b))for a,b in zip("[{<(","]}>)"))
It still is technically fully compliant to the task and not only the tests (||order wasn't required, only implied by the tests||). If I ignore the task and focus on only passing the tests, I can easily drop two bytes like this:
||```py
complete=lambda x:x+"".join(b*(x.count(a)-x.count(b))for a,b in zip("{<(","}>)"))
Here's mine with only 29 bytes:
||```py
class complete(str):__eq__=id
```||
so it can be called with a string, perhaps
I see
||py complete=lambda x:x+"".join(b*((f:=x.count)(a)-f(b))for a,b in zip("[{<(","]}>)"))||
82 bytes
line = input().split(", ");dictionary = {};[dictionary.__setitem__(i, dictionary[i] + 1 if i in dictionary else 1) for i in line];print(dictionary)
frequency array in python and it actually works, all in one line, submitted for my hs cs class
; == \n until it's not 😦
def a(): exp1; exp2
# Is obviously this
def a():
exp1
exp2
# And not
def a():
exp1
exp2
# And
def a(): b = 1; for x in range(1): pass
# Is
SyntaxError: invalid syntax
# And not
def a():
b = 1
for x in range(1):
pass
# And neither
def a():
b = 1
for x in range(1):
pass
Technically every program can be oneline, just exec with integer encoding of the characters
Since you use integer encoding, you encode the new line by integer
So technically the code is a single line
line can be inlined into the expression (listcomp)
Or, the dictionary and print could inline together
Which this used 2 reference of line
Then you can wrap inside a lambda
And execute it
Or just:
print([(line ::= input().split(", ")),(dictionary ::= {}),[dictionary.__setitem__(i, dictionary[i] + 1 if i in dictionary else 1) for i in line][0])
Where does the ::= come from
(lambda l:print({k:l.count(k)for k in set(l)}))(input().split(", "))
what's the purpose of making it a set
I have an 88 👀
technically every program is just a big number if take raw binary of file stored on drive and convert it to base 10
we already got an 82
legit?
seems like it doesn't follow this
it doesn't work for an input of [{ though, returning [{]}
fyi this dictionary can be dict('() {} <> []'.split())
Not required in the task description. Order isn't required, just completing the un-closed brackets. It's not stated that [({<}])> is invalid.
yo guys just asking to better understand, is esoteric programming used for any research of language capabilities or is it just used for shits and giggles
It's mostly just fun
by stretching conventional boundaries you discover novel aapplications. are they useful? usually not. are they cool? heck yeah
oh well i consider that research of language capabilities
Mostly just for fun, but that doesn't mean it's useless. Solving the puzzles people post here can make you better at programming, getting good at code golfing requires you to know a bunch of different ways to solve the same problem. There are also sometimes thorny edges of the language that get discussed, like how MRO works or advanced decorator possibilities.
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
!e
__builtins__.__dict__.__getitem__(__name__.__class__.__class__.__name__.__getitem__(__name__.__len__().__bool__().__add__(__name__.__len__().__bool__())).__add__(__name__.__class__.__name__.__getitem__(__name__.__len__().__bool__().__add__(__name__.__len__().__bool__()))).__add__(__name__.__len__().__class__.__name__))("Hello, world!")``` redundant import
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
!e ```py
build_class.self.dict.getitem(name.repr.name.getitem(import.self.getattribute(import.self.dir().getitem(import.doc.len().floordiv(spec.delattr.name.len()).add(debug)))(annotations.class.name.len(),debug.int().invert())).add(name.len().class.name))("Hello, world!")
Clearly, ``__import__`` is necessary.
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
Preventing reassigning
#Sudoku analizer if answer is correct
return all([len(x) == 9 for x in list(map(set, [[board[i + k][j + l] for k in range(3) for l in range(3) ]for i in range(0, 9, 3) for j in range(0, 9, 3) ]))]) and all([x != 0 for x in sum(board, [])]) and all([len(x) == 9 for x in list(map(set, board + list(map(list, zip(*board))) ))])
does this belong here?
Yes
:white_check_mark: Your 3.12 eval job has completed with return code 0.
True True
But in that code, it's fine to reassign as l.count(k) will stay the same
print(dict(zip(x:=input().split(", "),map(x.count,x))))
x=input().split(", ");print({k:x.count(k)for k in x})
i see..
!e
0----------------------------------------------------------------0
0- -0
0- (not not print("Hello world!")) -0
0- -0
0----------------------------------------------------------------0
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
Is there any other cuter way to turn a None type to a int or bool?
I thought the point of this channel was to write the most obscure and non-cute code.
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
idk
ternary?
False if potential_none is None else potential_none```
0 --------------------- 0
0 -- 0 or print or 0 -- 0
0 --------------------- 0
0 --------------------- 0
0 or print or 0
0 --------------------- 0
yeah thanks
!e
0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0
0--- ---0
0-- --0
0- -0
0 or print("Hello world!") or 0
0- -0
0-- --0
0--- ---0
0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
🤔
Not really, it's common concept
if you are using ==, then you can just 0== print ==0
!e ```py
(
1==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0
in broadcast -- START,
0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==1,
1==0==[ python is not smart (however, it is cool) ]==0==1,
1==0==[ it can do ]==0==1,
1==0==[ many, many things, like ]==0==1,
0==0==( print("Hello world!") or 5 ** 500 )==0==0,
1==0==[ (although, use print to, yknow, display) ]==0==1,
1==0==[ anyways, that is all ]==0==1,
1==0==[ goodbye for now, programmer in esotericism ]==0==1,
0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==1
in broadcast -- END,
1==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0==0,
)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world!
#######################################
# code guessing 14 - bea2c60d1a2dfca0 #
#######################################
######### undefined behavior ##########
input or output (undefined. seriously,)
############### install ###############
from file import * # program entrypoint
from file import sans_undertale as file
############### sponsor ###############
0>0>_>0>_>v0v0v0v0v0v0v0v0v0v<_<0<_<0<0
0>0>_<0<_[RAID:SHADOW-LEGENDS]>>0>_<0<0
0>0>_>0>_>0^0^0^0^0^0^0^0^0^0<_<0<_<0<0
################ usage ################
entry([...], [...]) # [list]s of floats
############## thank you ##############
(... for tuning in today (it is kind,))
But itll do unnecessary operations
but is it evaluatable?
||the original code is wrapped in docstrings, so it looks just like a funky header but secretly it is evaluatable when running using the -x flag||
no module named file
this is not the whole file lol
Quite an interesting problem:
Create a python program that prints not missing. However, if the last character of the script is removed, print missing
||m="missing";print(["not "+m,m][open(".py").read()[-1]!="#"])#||
my best is ||47||, but somehow there are much shorter solutions that I do not know of....
what's the name of the script
Is your best without cheating?
a more "in the spirit" approach might prohibit opening the file itself, for which there are also clever ways to do it
define "cheating"
not looking at future code?
if you mean without open(__file__) and the like 51
As usually defined by PPCG, for example no reading of own source code.
hmm interesting, I wanna see a solution that doesnt open the file
coming up with one yourself is a rewarding challenge ;)
good point lol, I'll brainstorm for a bit
||```py
type('',(),{"getattr":lambda x,y:print(["missing","not missing"][y=="x"])})().xy
where
does that include self-imports?
Can't look right now, probably somewhere at https://codegolf.meta.stackexchange.com/
36 ||```py
t={}[print(t*"not "+"missing")]=0x01
34, ignoring errors ||```py
t=print(t*"not "+"missing")._=0x01
insane
my 51:
||```py
a="missing"
aa='not '+a
class x:lt=print
x()<aa
32
||```py
t:print(t*"not "+"missing")=0x01
I meant this, but it doesn't actually ban reading your source code unless it's a quine challenge.
doesn't work in 3.14+
one more trick to get to 30 (or 32 depending on version):
||py t:print("not missing"[t:])=-77||
should be able to exit instead of print as well
true, no need to worry about the None
my first thought: ```py
type("",(),{"add":lambda s,x:print(["","not "][x]+"missing")})()+0b01
what if instead of the last character being removed it was the first? For that my best so far is a ||43||
||```py
10and-print('missing');print('not missing')
My first idea: ||56|| ||```py
xx=1;print(["not ",""][bool(vars().get("x"))]+"missing")
I got the same length (||43||) as yours, but very different idea: ||```py
xx=4;print("not missing"[vars().get("x"):])
39 ||```py
f'm'
exit((doc or'not m')+'issing')
clever!
Docstrings aren't docstrings if they're f-strings?
umm what???...
sadly this gets 36
||```py
#exit("missing")
exit("not missing")
so i guess this version is only interesting if we specify output to stdout
37
||```py
r'
not missing'
print(doc[4:])
Also update on my cursed wasm program: I have decided I am too stupid to use web-sys and will instead use inline js snippets, so it has gotten even worse https://paste.pythondiscord.com/VNWA
i have a cute 42 for this
||```py
f"{print('not ',end='')}";print("missing")
ooh using ||docstrings|| is really clever
This isn't competitive but I find it cute
||```py
*,='',
print('not missing'[4-len(str()):])
look ma no alphanumerics
55
@lambda _:print('not ',end='')
def f():0
print('missing')
``` anyone did a decorator yet?
Part 1:
Here are challenges (that I'm not planning to solve):
You need to provide code, where it needs to respond with:
Nothing removed
One character removed at the front
One character removed at the end
One character removed at both the front & the end
You need to print the message for each case respectively (in order to the above condition, you should only print the line corresponding to the action occurred):
Nothing is missing
Missing at the Front
Missing at the End
Missing at both the Front and the end
The output message is case-sensitive
The program must not read itself or any other file
The program must not import anything, including any standard library.
You must try to make it as short as possible.
-# Edit 1: add codeblock for the output data
-# Edit 2: Improved clarity (Added: respectively (in order to the above condition, you should only print the line corresponding to the action occurred))
-# Edit 3: Reference this as Part 1
(that I'm not planning to solve)
:(
just seems annoying frankly due to all the strings
With inconsistent cases
too bad that we can't import anything; I'm pretty sure there's a method in functools that handles all of this for us
Getting the first solve here, not really a golfed solution (||151||):
||```py
f"a"
a=["Missing at both the Front and the end",
"Missing at the Front",
"Missing at the End",
"Nothing is missing"]
b:print(a[b])=(not doc)*2+0x01
Nice
My idea was maybe I could mess up the casing while still look like a normal sentence to make merging a headache
Here's slightly shorter solution (||140||):
||```py
f"a"
="Missing at "
a=[+"both the Front and the end",
_+"the Front",
_+"the End",
"Nothing is missing"]
b:print(a[b])=(not doc)*2+0x01`
Part 2: You realised that you have no extra storage to store the value
Rule: eval/exec/compile not allowed, assignment is not allowed
globals/locals/vars/setattr are not allowed
open not allowed
(Pre-existing rule from Part 1 still applied)
(I don't know if this is possible btw)
Down to ||132|| now:
||```py
f""
="Missing at "
f="the Front"
b:print([+"both "+f+" and the end",+f,+"the End","Nothing is missing"][b])=(doc!="")*2+0x01
Nice
Does the ||docstring trick|| still work under this rule set?
Since it's technically assigning to ||__doc__||
||__doc__ is a pre-existing value from builtins
But if you reassign the variable, it's not allowed||
That doesn't really clear it up for me, but I've thought of a different way of phrasing the question. Does no assignment mean no STORE_NAME? Because ||"a" -> LOAD_CONST 0 ('a') + STORE_NAME 0 (__doc__)||
What is the code tho, I don't know what specific trick you talk about because from what I see, none of them are being assigned to? But I might have skipped some
Or you mean the code is just ||"a"||
Yea, using ||f"" -> "" for detecting the first letter removal||. Is that allowed under no assignment since it generates a STORE_NAME to ||__doc__||?
It is fine
||
>>> exec("\"a\"\n__doc__")
>>> __doc__
'a'
Wait what???
Oh oops, well I said it is fine so well, you now have one space of string storage
||
Part 3 would probably disallow this
Then this might satisfy part 2? ||185 I didn't do any assignments, but the compiler did by way of functions. Also should still be possible to use functions to get around the docstring even if __doc__ isn't allowed by something like 1+type+1 or 1+type+type+1 or similar. ```py
f""
type("",(),{"add":lambda s,x:print(["Missing at both the Front and the end",
"Missing at the Front",
"Missing at the End",
"Nothing is missing"][x+(doc!="")*2])})()+0b01
Also someone else can optimize the strings if they want, I'm too lazy
nice, I didn't notice ||object __add__|| was a solution and this look quite nice
Technically compliant? ||214||
||```py
f""
loader().load_module("atexit").register(lambda:print(["Missing at both the Front and the end","Missing at the Front","Missing at the End","Nothing is missing"][(doc!="")*2+annotations["b"]]))
b:0x01
no:
Pre-existing rule from Part 1 still applied -> The program must not read itself or any other file, The program must not import anything, including any standard library.
note that I didn't specify specific keyword/function related to import, but the general idea of importing
but for ||b:0x01||, it is a nice workaround that is technically compliant
Also just for completeness, here is ||210 no __doc__ cheese, just pure function cheese: ```py
10+type("",(),{"radd":lambda s,x:type("",(),{"add":lambda s,y:print(["Missing at both the Front and the end",
"Missing at the Front",
"Missing at the End",
"Nothing is missing"][y+x//5])})()})()+0b01
Nice, this would also complete the part 3 that is still in my mind🥴
That’s also why I made it :)
I was under wrong impression that atexit is pre-loaded by python interpreter, but it sadly is only by python interactive console (if it was preloaded, as some of the modules are, I'd argue that it wouldn't be technically importing).
I'm not sure. I got lucky with part 2, since ||functions|| happened to be the first thing I thought of when bulmenisaurus originally posted. Looking over the general ideas of previous solutions:
Passing info from end to middle: ||
- functions (getattr, add) (part 4?)
- assignment (part 1)
- annotations (part 3)
||
Passing info from beginning to middle: || - functions (add) (part 4?)
- assignment (part 1)
- docstrings (part 3)
- f-strings (!!!) #esoteric-python message
||
So only beginning->middle has a non-cheese solution, so another breakthrough would be needed if all the existing cheese was removed for part 4.
Also the complete of Part 3:
By dissecting the program(dis) it must not contain any bytecode instruction where in its string readable form as parameter would cause this function to return false:
def is_allowed(instruction_str: str) -> bool:
return "IMPORT" not in instruction_str and "STORE" not in instruction_str and "DELETE" not in instruction_str
(Pre existing rule from Part 1 and Part 2 still applied)
||Annotation would violate Part 3 from bytecode||
Unless there are other trick
shh I just edited it
||Since STORE_SUBSCR is used||
🥴
||Also technically your solution in Part 3 already are an expression which can be contained in other expressions, so cannot restrict from that||
Oops
||That would be sensible if it were a challenge, but it isn't. The challenge description could have been:
Apparently you are only given the opportunity to run a string from input via eval||
🤔 Would it possible to require the program to be symmetrical in the middle (i.e. by converting the original program string to a list of character, where reversing it is the exact same as the original program string)
If you used multiple line, line break is consider as \n, not \r\n, and the symmetrical is calculated by the whole of the string, not for each line
Also a further path from the program:
- It no longer need to be symmetrical, but it must function both ways, and detected whether it have reversed and removed character from start and end. The character would be removed before it reversed. You only need to provide sufficient readable indicators of what transform made
Also follow-up that I haven't apply:
(Pre-existing rule from Part 1, Part 2, Part 3 still applied)
I do not understand the restrictions after this one, but here's a very hacky solution for requirements up to and including these (||size 255||):
||```py
##!/usr/bin/python -cimport sys;f=open(sys.argv[1]);print(['Missing at the Front','Missing at both the Front and the end'][f.read()[-2]!='y']);f.close()
type('',(),{"getattr":lambda x,y:print(["Nothing is missing","Missing at the End"][y=="x"])})().xy
Disassembly to back up the validity of the solution:
||```
0 0 RESUME 0
2 2 PUSH_NULL
4 PUSH_NULL
6 LOAD_NAME 0 (type)
8 LOAD_CONST 0 ('')
10 LOAD_CONST 1 (())
12 LOAD_CONST 2 ('__getattr__')
14 LOAD_CONST 3 (<code object <lambda> at 0x785ce0d25c50, file "/tmp/test.py", line 2>)
16 MAKE_FUNCTION 0
18 BUILD_MAP 1
20 CALL 3
28 CALL 0
36 LOAD_ATTR 2 (x)
56 POP_TOP
58 RETURN_CONST 4 (None)
Disassembly of <code object <lambda> at 0x785ce0d25c50, file "/tmp/test.py", line 2>:
2 0 RESUME 0
2 LOAD_GLOBAL 1 (NULL + print)
12 LOAD_CONST 1 ('Nothing is missing')
14 LOAD_CONST 2 ('Missing at the End')
16 BUILD_LIST 2
18 LOAD_FAST 1 (y)
20 LOAD_CONST 3 ('x')
22 COMPARE_OP 40 (==)
26 BINARY_SUBSCR
30 CALL 1
38 RETURN_VALUE
```||
||Blatantly copying [#esoteric-python message](/guild/267624335836053506/channel/470884583684964352/)||
You cannot open, that is Part 1
Or, what is the top bit
That's a comment, always a comment 
The first line ||is a Shebang https://en.wikipedia.org/wiki/Shebang_(Unix)||
This doesn't work on all CPython executable platform (do I need to make a rule for this...)
And for the executable platform, you imported and store stuff and used open
But this is a workaround, just not a solution (I am in luck that I haven't specify the function open but just open)
One thing I have no idea is the sys.argv[1] tho
Isn't it the first parameter from the console?
Additional rule for future answer:
- It must be functional for all Tier 1/Tier 2 CPython platform(refer to: PEP 11) in file form (
python3 script.py, where the script is inscript.pyafter transformation) and in repl form.
For unknown reasons to me, the first argument is -c.
So what are you opening 🥴
||```py
#!/usr/bin/python -cimport sys;print(sys.argv)
Outputs ``['-c', '/tmp/test.py']`` (the latter is a path to the ran file).
So [1] is the ran file
Read Part 1 rule 🥴
The program must not read itself or any other file
Ah so you are the one they warn about for not using sys.argv[1] for cli input
And it doesn't, the loader does.
It counts as a part of the program.
How? It's a part of code, but how of program?
You cannot just put the entire program in Shebang and bypass every rule
Also
define program
provide (a computer or other machine) with coded instructions for the automatic performance of a task.
You technically provided coded instruction for the loader to operate to open a file
Outside of normal behaviour
Of the interpreter
I can use a completely different programming language in the shebang.
Anyhow https://codegolf.meta.stackexchange.com/a/10002/104482, I only did this solution, to test if it's possible this way, def "cheaty" at best.
So far the furthest I've gotten is this ||```py
11+type("",(),{"radd":lambda ,x:print("left"(11-x))})()#
"})'esrever'(tnirp{"f""
#)()}))x-11("thgir"(tnirp:x, adbmal:"ddar"{,)(,""(epyt+11
It works for normal, reverse, missing left, and missing right + reverse. I don't think anything further is possible, at least with my current design. That's because a working solution for this challenge would require a single piece of code that works to detect left when normal, and right when reversed, and vice-versa for right normal/left reversed. If it is possible, I am by far not good enough at writing palindromic/symmetrical code to figure it out.
Missing right + reverse is just missing left🥴 but well, nice try
*oh wait it's not the symmetrical one, I misread
I would not have wrote that
Sill unsure of how to do this with the restrictions, but I have managed to figure it out using an import: ||```py
aax0:0xbb
if "ax0" in annotations: print("left")#)"thgir"(tnirp :snoitatonna ni "0xa" fi
"})'esrever'(tnirp{"f""
import("atexit").register(lambda:print("right")if annotations["bbx0"]==0xa else 1)#)1 esle ax0==]"0xbb"[snoitatonna fi)"tfel"(tnirp:adbmal(retsiger.)"tixeta"(tropmi
bbx0:0xaa
The biggest challenge is to have a line of code that executes after another line, but it's earlier in the file.
Really nice
(Rule violation: import*1, annotation store bytecode*2)
@grave grail I got this, non-golf-able further (||3 bytes||) + it's always a semi-quine (the output contains the code of the current variant), isn't it beautiful?
||```py
abc
With distinguishing the cases as this:
||
Nothing:
```py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined. Did you mean: 'abs'? Or did you forget to import 'abc'?
First removed:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bc' is not defined
Last removed:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ab' is not defined. Did you mean: 'abs'?
Reversed:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cba' is not defined
Reversed + first removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ba' is not defined
Reversed + last removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cb' is not defined
||
sufficient readable indicators
This is not readable
It is not possible for anyone to identify what is the transformation without your specific definition
But not wrong, it's beautiful
Chess Battle Advanced
since when did code golf have to be readable ;)
The output need to be readable as the question definition, so welp
||Also according to this, ab is technically also valid since the output is program exit with no response, with the violation of the rule of producing a sufficient readable indicators
||
I don't think either of these would work for left + right + reversed, which I assumed was part of it, since they give the same output as left + right. ||abc -> b, ab -> ||
So you would need ||4 bytes||
I somehow the forgot the case exist as the one who created the question 💀
The output need to be readable as the question definition, so welp
It's subjective and not well defined. Can you explain what qualifies exactly and what doesn't?
On completely unrelated note, here's a quine that I've found. Probably not the first person to do it, but still...
||```py
File "<stdin>", line 1
File "<stdin>", line 1
IndentationError: unexpected indent
very clever
You can understand what it means without creating a custom definition of it
E.g. right/left / leftright / null / start startend
<, > <>, <>reversed
(By knowing the entire question with no idea what transform was made, without the knowledge of what the code and your definition, the output of the code should tell what transformation was made
You can assume that they can inspect multiple output before attempt to understanding it
I.e. they can understand
||NameError: name 'right' is not defined|| given that they have read a different error message that provide the specific information
You can assume that they understand english
bro 😭
I think we're getting a bit far from the original challenge
testing epython limits
Wbaut ||```py
print("Hello World!")
It's clear that:
||If to remove the first character:
```py
Traceback (most recent call last):
File "/tmp/test.py", line 1, in <module>
rint("Hello World!")
^^^^
NameError: name 'rint' is not defined. Did you mean: 'print'?
``` that the first character is missing.
If to remove the last character:
```py
File "/tmp/test.py", line 1
print("Hello World!"
^
SyntaxError: '(' was never closed
``` that the last character is missing.
If to reverse the code:
```py
File "/tmp/test.py", line 1
)"!dlroW olleH"(tnirp
^
SyntaxError: unmatched ')'
``` it's clear what was done.
Same with the rest of modifications.||
My solution is basically a golfed version of this.
Should have not make the challenge easy and have definite answer on what to output...
You win
Or very simple: only stdout counts.
It wasn't in the rule before which I cannot add arbitrary rule after someone completion
You can add this to your challenge, tho.
python -c ... 2>&1
Here's a new challenge:
Recover from nuking the interpreter.
The task is as follows:
Write a code that is executed (inserted) afterwards this snippet:
def nuke():
global __builtins__
import sys, gc
g = globals()
__builtins__.__dict__.clear()
__builtins__={}
g.clear()
sys.modules.clear()
gc.collect()
nuke()
That manages to do these things:
- Output
Hello World!(doesn't matter if to stdout or stderr), doesn't have to be the only thing outputted. - Exit gracefully (0 exit code)
Things to note:
It has to work when ran using the command python <filename>, as interactive shell modifies the state.
Please check, that your sitecustomize doesn't do anything (same reason as for interactive shell).
Ofc, this is a codegolf challenge.
(The RuntimeError: lost builtins module exception is raised when trying to printout an object in interactive shell and is not something that will prevent the code form execution - try forcing a zero division error for example. It's caused by this line of code: https://github.com/python/cpython/blob/1a8082a4bfc002fc05beb05637df4fc13597c49f/Python/sysmodule.c#L710)
My current solution is ||...151 bytes...|| long, but there's a plenty room for improvement.
I think I have seen this challenge here maybe 2 years ago
- thats not python, and 2. stdout is still distinct with stdin from the perspective of the program here
Does it have to be together or it can be separate by part
E.g.
Hello ...... World ..... !
Also are there any specify version of python / os platform, or I just have to prove it work on some version
Nvm, got it
||
async def f():...
f.__qualname__="Hello World!"
f()
||
||I don't have the tool to see exit status tho, but I can run f() for second time to double the error message so I would assume it gracefully exit|| @austere mauve
Output:
||
Exception ignored in: <coroutine object Hello World! at 0x7385a28720>
Traceback (most recent call last):
File "<string>", line 18, in <module>
KeyError: '__builtins__'
Exception ignored in: <coroutine object Hello World! at 0x7385a28720>
Traceback (most recent call last):
File "<string>", line 18, in <module>
KeyError: '__builtins__'
[Program finished]
||
||-2 from last one||
||
async def f():0
f.__qualname__="Hello World!"
f()
```||
I wonder if it's possible to really recover from this, not just print something. Can you regain the ability to import something? Can you restore builtins?
Well you've lost most of the direct access to many things. But a lot of others are probably still accessible - modules still existing because a function is stored somewhere, etc. And things like sys or builtin types are always accessible on the C side.
it'll be through object.__subclasses__ traversal if nothing else
I found way to access BaseException class but I couldn't find a way to print Hello, world! with exit code 0
I also found way to get SystemExit but it doesn't work with nuked interpreter
yes it exits with 0
how do you get it?
||py [()][0].__class__.__base__.__subclasses__()[115]||this will return BaseException class
for SystemExit, wait
ah
||py [()][0].__class__.__base__.__subclasses__()[161](0,0).__call__()||this will raise SystemExit
you can put exit code as argument in __call__
show
which is almost double the 49b from the async def
||```py
raise.0.class.base.subclasses()[115].subclasses()[4]("Hello, World!")
you'll need to include python version in submissions as well because internals change
I could have done that too but the problem is it returns exit code 1 not 0 which is a condition
mk
3.13
mk?
"okay"
Thx
I like that solution.
Here's a dumb hacky solution of only ||31|| length, but is more or less invalid one:
||```py
if 0 else print("Hello World!")
3.10-3.?? (||SyntaxWarning turning into SyntaxError eventually||)
||```py
1or"Hello, World"
Oh well, I never memorize much warning
async one is the one that I have remember
nice to see other warning kind output
The status code is 100% not 0
Which doesn't meet your requirement
Don't break your own rule lmao🥴
.... thats genius
My phone do this🥴
||
<string>:12: SyntaxWarning: invalid decimal literal
[Program finished]
||
Well, guess I can only test when I get home
It's appended without newline:
def nuke():
global __builtins__
import sys, gc
g = globals()
__builtins__.__dict__.clear()
__builtins__={}
g.clear()
sys.modules.clear()
gc.collect()
return sys.stdout
out=nuke()if 0 else print("Hello World!")
Anyhow, that's not a proper solution (the new line should be present) (that's also the reason this is not a spoiler).
Warnings don't get line description when using interactive shell, here's the output when ran using a python file (as per the task):
||```py
$ python /tmp/test.py
/tmp/test.py:13: SyntaxWarning: invalid decimal literal
1or"Hello, World"
Well, that's python on my phone running it, which I'm aware it's not accurate on specifically this kind of thing🥴
Oh🥴
does anyone know WTF the parser calls the token: SOFT_KEYWORDS ?
asking for a @upbeat folio
a soft keyword is a keyword that you can use as an identifier. the context is enough to determine when its actually a keyword
e.g. match and case are that, and the new type statement too
Oh, you can? I never give a thought about them
So the thing that is weird is that the tokenizer renders match, case and type as NAME
We can't find something that the tokenizer will render as a SOFT_KEYWORD so we're wondering if it is obsolete.
don't forget about the _
most "hard" keywords don't deserve be keywords
they as well could be soft keywords
https://docs.python.org/3/reference/lexical_analysis.html#soft-keywords
Don't think it's obsolete, it's added in 3.10
When will Python reach version 4.0 and what do you guys and gals think that will look like
there's no guarantee it will
there's an almost guarantee it won't
why so?


