#esoteric-python

1 messages · Page 50 of 1

arctic skiff
#

you can call 1 foot tile a 1 foot tile but not 1 yard tile, si unit would stay meters, I am telling you to use the correct unit not si

#

also I don't wanna continue this further

versed eagle
#

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

#

???

versed eagle
grave grail
#

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

grave grail
#

Can you just do a quick Google search?

#

Or, mark specifically what I say wrong?

#

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

versed eagle
#

im saying its not what im referring to

#

and what you looking for is still MiB

#

this part specifically

grave grail
#

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

versed eagle
#

^^

grave grail
#

Yes exactly

#

So it's MiB

versed eagle
#

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

grave grail
#

In the calculation

#

We are saying your prefix is wrong because your calculation is IEC standard

earnest wing
#

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

grave grail
#

Ok, so it's 1 idksomethingfunny

#

Great, no one knows what it means :)

versed eagle
grave grail
versed eagle
#

i was not relying on a standard

grave grail
#

Ok, so you mean no one suppose to understand you :)

versed eagle
#

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

grave grail
#

Ok, so let me suppose that they can also equivalent understand that that are equivalent to 1 idksomethingfunny

versed eagle
#

if you provided sufficient context

#

then yes

grave grail
#

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

grave grail
#

Can you clarify?

versed eagle
grave grail
#

But MB mean 10**6 according to si unit
I don't understand because I am stupid, can you further clarify?

versed eagle
versed eagle
#

as said previously

grave grail
versed eagle
#

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

grave grail
#

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 :)

fleet bridge
versed eagle
#

there isnt much room for misunderstanding if people just. read the numbers

grave grail
#

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

arctic skiff
earnest wing
#

Y'all better get over this already. :/

arctic skiff
#

.topic

glass drumBOT
#
**What's a common part of programming we can make harder?**

Suggest more topics here!

arctic skiff
restive void
#

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 [])
night quarryBOT
arctic skiff
#

its secret knowledge not everyone knows

subtle viper
#

if you care about the precision of 1024 vs 1000 then go use bytes

#

KB, MB, and GB are all approximate units to me

restive void
#

Can we just drop this discussion please?

hybrid trail
#

Hello world but I resized my editor to be 4 characters wide

(
vars
)((
vars
)()[
dir(
)[1]
])[
'pr\
int'
]('\
Hel\
lo,\
 Wo\
rld\
!')
grave grail
#

It is so hard to see 💀

hybrid trail
#

is 3 possible? 🤔

fleet lintel
#

Alternative more boring version, but also doesn't work for 3. ```py
(
exec
)("
pri
nt(
'He
llo
, W
orl
d!'
)")

earnest wing
#

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

earnest snow
#

with getattr? I don't think much can be done with getattr without using identifiers shorter than 3 chars

fleet lintel
#

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.

arctic skiff
#

its just impossible to do it in less than 3 chars

fleet lintel
#

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

arctic skiff
#
['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

hybrid trail
#

don't forget methods

#

but yeah

arctic skiff
# hybrid trail don't forget methods

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': []}

hybrid trail
#

oh 🤦‍♂️

#

there's also dict.pop

arctic skiff
#

though you can use {}

arctic skiff
quartz wave
#

hello esopy what are we cooking today

earnest wing
#

trying to print hello world with a 3-column source file

quartz wave
#

ctypes.memoryview_at() coming in 3.14

earnest snow
grave grail
#

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)

versed eagle
craggy hamlet
#

hmm, I can't figure out how to do it in under 3 characters per line

earnest snow
#

you forgot to call the function though

craggy hamlet
#

ah yeah, that's just my codewars solution lol

fleet lintel
#

Javascript is trivial in theory, since any jsfuck program can be made 1 char wide

earnest snow
# grave grail I am curious, what is the minimal amount of character per line possible to rewri...

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

fleet lintel
#

you can make classes through type

#

Ie class a(b): could be a=type("a",(b),{})

earnest snow
#

for some reason I thought that would be bigger

grave grail
#

So maybe shorter?

fleet lintel
#

you can actually make it 4 wide ```py
a=
(
type
)("
a",(
b,),
{})

So I think the limit for everything is 4 wide
earnest snow
#

what's the smallest thing you need for a function? I think def is as long or shorter than lambdas

fleet lintel
#

As long as you can get getattr and setattr through vars, you should be able to make everything only 4.

grave grail
#

Issue, how to write a function 🤔

fleet lintel
#

hm

earnest snow
#

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

grave grail
#

💀

earnest snow
#

but I don't think that serves the point

#

or does it?

grave grail
#

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 _(
earnest snow
#

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

earnest snow
#

*a for the args and more arguments to replace higher order functions

grave grail
#

And string can have whatever length

fleet lintel
#

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.

grave grail
#

When column >= 2

earnest snow
#

there's a compile function that should spit out a code object without executing the code

grave grail
#

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

fleet lintel
#

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`.

grave grail
#

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

earnest snow
#

I just noticed how long return is

#

I think the maximum is gonna be set by return instead of by def

grave grail
#

No one had remember we might need them

earnest snow
grave grail
#

Write a return value stack

earnest snow
#

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)

fleet lintel
#

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.

earnest snow
#

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

fleet lintel
#

getattr solves everything

earnest snow
#

the short-circuiting, yeah

fleet lintel
#

Top level return isn't too bad, but what about when it's nested

earnest snow
#

can we make a decorator that when detects A>B on the code that instruction in the bytecode gets replaced by a return instruction?

fleet lintel
#

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

earnest snow
fleet lintel
#

But another problem is dealing with indentation

earnest snow
#

since we return in an argument/global we don't care what the first const is

earnest snow
fleet lintel
#

So you would need a global to track return mode since function calls would be the only way to solve arbitrary indentation.

earnest snow
#

or take everything out into a function (and probably set an argument to it not to waste names)

grave grail
#
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

earnest snow
#

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)
fleet lintel
#

I wonder if it would be possible to get rid of functions entirely using inlining

earnest snow
#

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

fleet lintel
grave grail
#
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

grave grail
grave grail
versed eagle
#

yes

earnest snow
versed eagle
#

yes

grave grail
#

Ok great we are back to 4

#

Thx

fleet lintel
#

wow that is terrible, thanks

versed eagle
#

you cant return from it though

#

because return is too long

grave grail
versed eagle
#

yep

earnest snow
earnest snow
grave grail
#

but not sure it is possible

fleet lintel
#

we could have the return value stack include if it's returning from a return statement

#

so that could be checked for shortcircuiting

grave grail
#

Just b don't do any thing to the return stack

earnest snow
#

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

grave grail
#

or

o=(1
if v
else
2)
#

this is selection and should be possible to be done in any case

earnest snow
#

we index a list from the boolean so that we don't waste a single extra ident?

#

that's clever

grave grail
#

only when we don't need short circuiting

grave grail
#

but it can be done by a one line function (in multiple line) to add to the return stack

earnest snow
#

yeah, the else is already 4 chars

fleet lintel
#

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:?

versed eagle
#

iter

#

any while loop can be made into a for loop

grave grail
#
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

versed eagle
#

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

grave grail
#

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 ?

versed eagle
#

sorry wrong reply

fleet lintel
grave grail
#

p is s.pop, where s is the return stack

#

c is the imaginary call of the expression

fleet lintel
#

So it would be the partial of pop on the output object?

grave grail
#

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

versed eagle
#

we probably do end up needing to reimplement them

#

or find a way to get functions properly returning

grave grail
#

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

fleet lintel
#

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)
versed eagle
#

alternatively we could try to find a way to define functions in a pointfree manner

fleet lintel
#

What does that mean?

versed eagle
#

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

fleet lintel
#

partial

#

actually no

grave grail
#

I need a explanation of how function composition would work in 4 character

fleet lintel
#

That's the question

grave grail
#

💀
from test.test_zipfile._path._functools import compose is weird

fleet lintel
#

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))
grave grail
#

Need to now learn partial and reduce

#

!d functools.reduce

night quarryBOT
#

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:
grave grail
#

🤔

#

Why so slow

#

Oh that was me 🥴

#

!d functools.partial

night quarryBOT
#

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
grave grail
#

People thought of this curse way is crazy

fleet lintel
#

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

grave grail
#

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

stable hornet
grave grail
#

Can you un-write this to a normal line of code 🥴

#

So it's easier to understand

eager canopy
#
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

fleet lintel
#

I remember using that (()for()in()) for something else

eager canopy
#

does timeit uses processes? Last time I saw main usage was when using multiprocessing

fleet lintel
stable hornet
versed eagle
#

thats probably a good starting point

fleet lintel
#

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

grave grail
#

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.

night quarryBOT
#

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```
grave grail
#

Which would call the perspective exit handler and pause propagation of any error

versed eagle
fleet lintel
#

So with that, looking through the keywords list everything besides async/await should be fully 4-char-wideable

quartz wave
#

timeit afaik uses two nested python for loops with benchmarking functions

grave grail
#

Or composite function

earnest snow
grave grail
#

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

grave grail
#

Umm, function composition doesn’t work with more than 1 argument

earnest snow
#

what's the worst, most painful, type-hinting you can come up with?

proper vault
#

that is, supports each of the methods individually if all the passed iterables support it

earnest snow
#

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

proper vault
#

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.

earnest snow
proper vault
#

go for it, I'm curious if there's a good solution

earnest snow
#

who said it was going to be good?

proper vault
#

anything that's not quadratic is a good solution in my book

earnest snow
#

wait a class or a method?

proper vault
#

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__

earnest snow
#

if I use Generic[T] instead of normal typevars is because my default python interpreter is ancient

earnest snow
#

man mypy is dumb

#

doesnt type-check for self

earnest snow
#

can a function return Generic[T]?

sick hound
#

ummm
im cloning the repository which has the ps3 linux kernel (6.13)
gulp 10598185 files

floral meteor
torn tulip
#
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
midnight isle
#

Does esoteric python have to do with Python frameworks like say RPython

quartz wave
#

!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))

night quarryBOT
restive sparrow
#

print("hello")

#

@night quarry

grave grail
#

?

past forge
arctic skiff
subtle viper
#

talking about ~hash(~x)

midnight isle
#

What about the Liberace sequence tho deadge

formal sandal
#

@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

distant wave
#

This is annoying me so much

#

...

distant wave
#

well if anyone figures it out

#

ping me

quartz wave
#

what's "it"

distant wave
#

naive is 69

long fulcrum
#

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

quartz wave
#

search through libraries then

long fulcrum
#

wdym

quartz wave
#

maybe there's something other than codecs?

long fulcrum
gleaming linden
#

Would require suppressing stdout though

fleet bridge
#
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

fleet bridge
long fulcrum
#

I'm pretty sure the 68 contains "rot13" in it

#

although there might be multiple 68s

wraith quartz
#

v

hybrid trail
#

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())
midnight isle
#

What are codecs erm in Python terms. I assume it is different outside of Python? blobhuh

earnest wing
#

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

craggy silo
stable hornet
distant wave
#

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

stable hornet
#

the 68 I found uses one of those

distant wave
#

I am blind, I see

stable hornet
#

I did make like 4 or 5 different 69s before finding it though

distant wave
#

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")

night quarryBOT
# distant wave !e ```py import codecs handle = codecs.open(1, "w", "rot13") handle.write(b"byte...

: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
distant wave
#

Can't translate because rot13_map is string only

#

!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.write("string")

night quarryBOT
distant wave
#

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"])

night quarryBOT
distant wave
#

!e ```py
import codecs
handle = codecs.open(1, "w", "rot13")
handle.writelines(["string", "string"])

night quarryBOT
# distant wave !e ```py import codecs handle = codecs.open(1, "w", "rot13") handle.writelines([...

: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'
distant wave
#

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

hybrid trail
#

thats how golf is sometimes

long fulcrum
midnight isle
earnest wing
#

grok?

noble belfry
#

!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'))

night quarryBOT
bright valve
noble belfry
#

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

grave grail
#
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

subtle viper
#

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'))

night quarryBOT
clear venture
#

I like the contrast between golfing and obfuscation here lol

subtle viper
#

i wanted to golf but the way i wanna do it wasn't with a 1 liner ¯^¯

quartz wave
#

!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-=3
s.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())

night quarryBOT
quartz wave
#

that was what i had in mind

hybrid trail
#

!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())
night quarryBOT
hybrid trail
#

golfed 👀

neat otter
#

very nice

noble belfry
#

nice, but it cant have negative numbers because its not balanced ternary

grave grail
#

-s+1 make it negative? and then you can use +s+1 to move closer to 0 in the number line

craggy hamlet
night quarryBOT
hybrid trail
#

🤯

dense sand
#

!e

night quarryBOT
#
Missing required argument

code

hybrid trail
night quarryBOT
quartz wave
#

wait

#

!e ```py
print(copyright)

#

ooh

night quarryBOT
vast wave
#

!e ```py
import this

night quarryBOT
# vast wave !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

ashen shard
#

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…

sturdy pond
#

i'm new too

#

is this channel for python?

noble belfry
#

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).

sturdy pond
#

?

#

ok

#

but what channel is python

noble belfry
restive void
stable hornet
#

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

hot glacier
#

is this an exercise in absurdity like making puzzles and stuff or is there an actual functional need for it

proper vault
#

it's just fun

stable hornet
#

ya it is fun

#

I learn things about the language that I would never have thought about otherwise

hot glacier
#

thank god for GPT I my ADHD would lock me down at the second while

hybrid trail
#

what does it do? 🤔

versed eagle
hybrid trail
#

oh is it connect 4

stable hornet
#

yeah it is

#

oops I meant to mention that in my message

hybrid trail
#

would //7 -> >6 accomplish the same?

stable hornet
#

yeah it would

#

actually it wouldn't work for negative inputs

hybrid trail
#

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

versed eagle
#

it would be fine

#

discord wouldnt properly display it, but if you copy and paste it it'd still work ^^

stable hornet
hybrid trail
#

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)
oblique ibex
#

ignore that

oblique ibex
#

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

hybrid trail
#

or c='0123456'.index(input())

#

depends on if @stable hornet is fine with this change to the api

oblique ibex
#

I forgot what .index does lmao

#

very smart

oblique ibex
pure dew
#

wise assessment

stable hornet
#

I kinda liked printing a ? if it was out of range but my rules were fairly arbitrary anyway

quartz wave
#

oh i see

midnight isle
#

Is interpreted vs compiled the separation layer between C and Python?

midnight isle
# quartz wave 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)

proper vault
#

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.

midnight isle
#

So abstraction is the key difference?

#

This subject really interests me

quartz wave
midnight isle
#

Idk what Nuitka is I’ll check it out

midnight isle
# quartz wave i guess?

It’s a bit too early for this in my little corner of the world. Let’s revisit this another time 😂👌

fleet lintel
# midnight isle Hey ceweal. The separation layer between Python and C is I was thinking about ho...

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.

fleet lintel
#
  • 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.
midnight isle
#

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

grave grail
#

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

versed eagle
#

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

sonic bobcat
#

what is esoteric python?

oblique ibex
#

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

midnight isle
# sonic bobcat what is esoteric python?

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.

sonic bobcat
#

I see

#

that's quite interesting

midnight isle
#

Can we update the channel description admin prayge admin overlords

grave grail
# versed eagle low and high level are relative

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

proper vault
#

This is the more traditional notion of low level language where it's basically just assemblers

clear venture
#

^^

quartz wave
midnight isle
quartz wave
grave grail
#

What you don't like the channel description forpithink

midnight isle
#

Gore and weirdness 😂 that could go in a channel called dark arts or something I don’t know 💀

grave grail
#

That is like the literal correct name for everything tho pithink

quartz wave
#

i don't see why general weirdness doesn't belong in the weirdness channel

earnest wing
#

yeah that's the point

earnest wing
midnight isle
#

I wonder what the history of this channel is for it to get this description

karmic pumice
mortal thorn
#

Is Hawaii esoteric pizza?

pure dew
#

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)

proper vault
#

I mean, modern C is more about driving the compiler than hardware, with things like restrict, attributes, ...

earnest snow
#

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

restive void
#

No exec, no eval

def f(x: (open("x.py", "w").write("source code goes here"), __import__("x"))):
    pass
oblique ibex
#

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
quartz wave
#

really?

#

oh they changed 3.14

#

i see

earnest snow
oblique ibex
quartz wave
#

!e ```py
def a(b: [print("Hello, World")for{}[()]in iter(int,1)]):pass

night quarryBOT
oblique ibex
#

pretty much use any one liner trick inside the typehint

quartz wave
#

one-expression* trick but okay

noble belfry
#

!e

def a(b: list((print(1)for i in range(12)))):
    ...
night quarryBOT
quartz wave
#

scary

#

there couldn't be a worse site

earnest snow
#

but yeah with walrus and with iter(int, 1) is easier than I thought

quartz wave
#

i don't think you can use any number of expressions in a type hint but sure

#

well including the inner ones maybe

earnest snow
quartz wave
#

ah

earnest snow
#

or

quartz wave
#

so just put it all in type hints

earnest snow
#
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

quartz wave
#

!e ```py
def f(a: print([x + 4 for globals()['x'] in [2,5]]*x)): pass

night quarryBOT
quartz wave
#

okay

#

unintentionally picked some nice numbers but i guess assignment still works fine

earnest snow
#

I don't think you can unpack nicely with walrus

quartz wave
#

that's why we use magic called comprehensions

earnest snow
#

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

fleet bridge
#

!e ```py
from pathlib import Path
print(
Path('.') == Path('.').parent
)

night quarryBOT
fleet bridge
#

hmm

grave grail
#

!e
print(import("pathlib").Path(".").parent)

night quarryBOT
grave grail
#

Hmm, it just count . as root?

#

!e
import pathlib
print(pathlib.Path("/").absolute().parent)

night quarryBOT
grave grail
#

Probably

pure dew
#

!e

from pathlib import Path
print(Path(".").resolve())
night quarryBOT
pure dew
#

relative paths are purely lexical until you resolve them

fleet bridge
#

why isn't parent of . equal to ./.. ?

clear venture
#

it is

#

wha

#

oh this is pathlib

earnest wing
#

like anonymousdapper said

grave grail
#

!e

import pathlib
print(pathlib.Path("../"))
print(pathlib.Path("../").parent)
night quarryBOT
grave grail
#

Tf

#

It's cursed if you haven't resolved the absolute

fleet lintel
#

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.

fluid pumice
#

!e

(lambda _, __, ___, ____:
    eval(''.
    join([bytes([_____]).
    decode() for
    _____\
    in [(____+((___<<___<<_)-(___<<_))),(____+((___<<___<<_)-___)),
    (____+(___<<_)+_),(____+((___<<___<<_)-(___<<___))+(___)),
    (____+(___<<___<<_)),((___<<___)+(___<<___<<___)),((___<<___<<___)+___),
    (____+(___<<_)),(____+_),(____+(___<<___)),(____+(___<<___)),
    (____+(___<<___)+___+_),(___<<___<<___),(____+(___<<___<<_)+
    (___+_)),(____+(___&___&___^_|___)+(___|_|__+___)+
    (___|_)+___),(____+(___<<___<<_)-(___+___<<_)+
    (___<<___)-___),(____+(___<<___)),____,
    ((___<<___<<___)+___),((___<<___<<___)+(___<<___)+_)]]))
)(_:=([([map(int, 
(__builtins__.len({}.__iter__.
__repr__.__subclasshook__.
__init__.__name__).__subclasshook__.
__init__).__str__())])]!=
{...==...:[...,...][0:[]!=[]==[
{}.__iter__.__subclasshook__]]}),__:=~-_,(_<<(_^__)), ((((((_ << _ << _) 
>> __ >> __ >> __) ** 
(_ << _ << _)) >> _)-(_ 
<< _ << _ << _ << _ << _)+(_<<_<<_))))```
night quarryBOT
clear venture
#

that one tickles my brain

fluid pumice
#

that one is probably the simplest esoteric hello world I have written

#

XD

clear venture
#

not because of its complexity just the pretty heiroglyphics it came out to be XD

fluid pumice
#

that was the point XD

grave grail
fluid pumice
#

none, I wrote that code by hand

#

All my esoteric programs are hand written

hushed quest
#

Guys i have a problem where when i build an app using pyinstaller , the app i have currently selected or windows explorer automatically closes

clear venture
#

not the place to ask

grave grail
austere mauve
#

!e ```py
=lambda :ord([:=not _][][])+!=-~+<<<<~*~_ or not _+"Hello World!"

print(next(filter(('g',).le,id.self.dict.items()))~(not _)[~(not __)])

night quarryBOT
# austere mauve !e ```py _=lambda _:ord(_[__:=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!
versed eagle
quartz wave
versed eagle
#

i know

#

they never will, likely

#

but i think this is what it should have been

austere mauve
#

or scrap two's complement altogether (PSF should release python-tailored cpus, PHF!)

pure dew
#

python bytecode on bare metal

fluid pumice
#

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

fluid pumice
brazen arrow
#

hey guys i want to get the name of a class

stable hornet
#

cls.__name__?

brazen arrow
stable hornet
grave grail
compact trench
#

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)
hybrid trail
#

what does it do?

compact trench
#

it's a pointer, always exactly one value, unlike python lists which can have any number of values.

quartz wave
night quarryBOT
quartz wave
#

!e ```py
from types import CellType as ptr

cell = ptr(4)
print(cell.cell_contents)
cell.cell_contents = 10
print(cell.cell_contents)

night quarryBOT
quartz wave
#

it can be simplified

compact trench
#

I wonder if (lambda x=None: (lambda: x).__closure__[0]) would work, then?

grave grail
#

I do not understand the purpose of this at all pithink

quartz wave
night quarryBOT
quartz wave
#

yup

compact trench
grave grail
#
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

fleet bridge
#

no difference pretty much

#

but CellType is implemented in C and is widely used in internal C code

grave grail
#

Ah ok

quartz wave
grave grail
#

It use C btw /j

hybrid trail
#

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('()()') == '()()'
fleet lintel
# hybrid trail little golf challenge: make a function `complete` which given a string made up o...

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.

hybrid trail
#

you can assume that there are no mismatched bracket and remove the elif condition

versed eagle
fleet lintel
#

Not using a lambda since I can't remember how to make while loops work in those

hybrid trail
versed eagle
#

make a function complete which given a string made up of only <>[](){} closes all the unclosed brackets.

fleet lintel
# versed eagle `iter`

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.

versed eagle
#

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 ^^

versed eagle
hybrid trail
#

how would you suggest to phrase it better?

versed eagle
#

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?

hybrid trail
#

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)

fleet lintel
versed eagle
#

ah

#

i read those as an example of a function that satisfied the requirements

#

not the Normative Function Return Values

earnest wing
#

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

quartz wave
#

||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()

austere mauve
quartz wave
#

very weak tests indeed..

#

how scary

austere mauve
#

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
```||
fleet bridge
#

why do you subclass str?

#

tests don't check that the callable returns a string

karmic pumice
fleet bridge
#

I see

arctic skiff
minor gale
#
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

past forge
#

"one line" 🤨

#

; == Enter == \n

#

(in my opinion at least)

pure dew
#

technically is one line

#

"standalone expression" is a better term

austere mauve
#

; == \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
grave grail
#

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

grave grail
#

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

austere mauve
#

Or just:

print([(line ::= input().split(", ")),(dictionary ::= {}),[dictionary.__setitem__(i, dictionary[i] + 1 if i in dictionary else 1) for i in line][0])
grave grail
#
(lambda l:print({k:l.count(k)for k in set(l)}))(input().split(", "))
oblique ibex
#

what's the purpose of making it a set

arctic skiff
arctic skiff
hybrid trail
#

legit?

hybrid trail
arctic skiff
#

I modified @austere mauve's

hybrid trail
#

it doesn't work for an input of [{ though, returning [{]}

magic wraith
austere mauve
main mango
#

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

earnest wing
#

by stretching conventional boundaries you discover novel aapplications. are they useful? usually not. are they cool? heck yeah

main mango
#

oh well i consider that research of language capabilities

fleet lintel
night quarryBOT
#

:white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello, world!
unique heath
#

!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
night quarryBOT
austere mauve
#

!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.
night quarryBOT
bright valve
shrewd vale
#
#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?

grave grail
#

Yes

night quarryBOT
#

:white_check_mark: Your 3.12 eval job has completed with return code 0.

True True
oblique ibex
subtle viper
#
print(dict(zip(x:=input().split(", "),map(x.count,x))))
x=input().split(", ");print({k:x.count(k)for k in x})
#

i see..

wraith granite
#

!e

0----------------------------------------------------------------0
0-                                                              -0
0-             (not not print("Hello world!"))                  -0
0-                                                              -0
0----------------------------------------------------------------0
night quarryBOT
wraith granite
#

Is there any other cuter way to turn a None type to a int or bool?

jaunty lake
#

I thought the point of this channel was to write the most obscure and non-cute code.

wraith granite
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
idk

jaunty lake
#
False if potential_none is None else potential_none```
fleet bridge
#
0 --------------------- 0
0 or      print      or 0
0 --------------------- 0
wraith granite
#

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
night quarryBOT
wraith granite
#

🤔

grave grail
fleet bridge
quartz wave
#

!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,
)

night quarryBOT
earnest wing
#
#######################################
# 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,))
bright valve
earnest wing
#

||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||

unique heath
#

no module named file

earnest wing
#

this is not the whole file lol

hybrid trail
#

Quite an interesting problem:
Create a python program that prints not missing. However, if the last character of the script is removed, print missing

oblique ibex
#

||m="missing";print(["not "+m,m][open(".py").read()[-1]!="#"])#||

hybrid trail
#

my best is ||47||, but somehow there are much shorter solutions that I do not know of....

quartz wave
#

what's the name of the script

restive void
hybrid trail
#

a more "in the spirit" approach might prohibit opening the file itself, for which there are also clever ways to do it

quartz wave
#

not looking at future code?

hybrid trail
restive void
oblique ibex
#

hmm interesting, I wanna see a solution that doesnt open the file

hybrid trail
oblique ibex
#

good point lol, I'll brainstorm for a bit

restive void
#

||```py
type('',(),{"getattr":lambda x,y:print(["missing","not missing"][y=="x"])})().xy

quartz wave
restive void
quartz wave
#

36 ||```py
t={}[print(t*"not "+"missing")]=0x01

#

34, ignoring errors ||```py
t=print(t*"not "+"missing")._=0x01

hybrid trail
#

insane

#

my 51:
||```py
a="missing"
aa='not '+a
class x:lt=print
x()<aa

#

32
||```py
t:print(t*"not "+"missing")=0x01

restive void
# quartz wave where

I meant this, but it doesn't actually ban reading your source code unless it's a quine challenge.

quartz wave
hybrid trail
#

one more trick to get to 30 (or 32 depending on version):
||py t:print("not missing"[t:])=-77||

earnest wing
#

should be able to exit instead of print as well

quartz wave
#

yup

#

31 for 3.14+ ||```py
t=exit("not missing"[t:])._=-77

#

no errors too

earnest wing
#

true, no need to worry about the None

fleet lintel
#

my first thought: ```py
type("",(),{"add":lambda s,x:print(["","not "][x]+"missing")})()+0b01

hybrid trail
#

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')

fleet lintel
#

I got the same length (||43||) as yours, but very different idea: ||```py
xx=4;print("not missing"[vars().get("x"):])

stable hornet
#

39 ||```py
f'm'
exit((doc or'not m')+'issing')

hybrid trail
#

clever!

restive void
#

Docstrings aren't docstrings if they're f-strings?

grave grail
#

umm what???...

earnest wing
#

sadly this gets 36
||```py
#exit("missing")
exit("not missing")

hybrid trail
#

so i guess this version is only interesting if we specify output to stdout

#

37
||```py
r'

not missing'
print(doc[4:])

fleet lintel
#

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

versed eagle
#

||```py
f"{print('not ',end='')}";print("missing")

versed eagle
earnest wing
#

This isn't competitive but I find it cute
||```py
*,='',
print('not missing'[4-len(str(
)):])

#

look ma no alphanumerics

proper vault
#

55

@lambda _:print('not ',end='')
def f():0
print('missing')
``` anyone did a decorator yet?
grave grail
#

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

hybrid trail
#

(that I'm not planning to solve)
:(

earnest wing
#

just seems annoying frankly due to all the strings

austere mauve
#

With inconsistent cases

stable hornet
#

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

austere mauve
grave grail
#

Nice

grave grail
austere mauve
#

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`

grave grail
#

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)

austere mauve
grave grail
#

Nice

fleet lintel
#

Since it's technically assigning to ||__doc__||

grave grail
#

||__doc__ is a pre-existing value from builtins
But if you reassign the variable, it's not allowed||

fleet lintel
#

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__)||

grave grail
#

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"||

fleet lintel
#

Yea, using ||f"" -> "" for detecting the first letter removal||. Is that allowed under no assignment since it generates a STORE_NAME to ||__doc__||?

grave grail
#

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

fleet lintel
#

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

grave grail
#

nice, I didn't notice ||object __add__|| was a solution and this look quite nice

austere mauve
grave grail
#

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

fleet lintel
#

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

grave grail
#

Nice, this would also complete the part 3 that is still in my mind🥴

fleet lintel
#

That’s also why I made it :)

grave grail
#

🤣

#

What restriction can I make for part 4pithink

#

That has to be also sensible

austere mauve
fleet lintel
#

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.
grave grail
#

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)

grave grail
#

Unless there are other trick

fleet lintel
#

shh I just edited it

grave grail
#

||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||

grave grail
#

||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
grave grail
#

Also follow-up that I haven't apply:
(Pre-existing rule from Part 1, Part 2, Part 3 still applied)

austere mauve
# grave grail Also the complete of Part 3: By dissecting the program(`dis`) it must not contai...

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/)||
grave grail
#

Or, what is the top bit

austere mauve
grave grail
#

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)

grave grail
#

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 in script.py after transformation) and in repl form.
austere mauve
grave grail
#

So what are you opening 🥴

austere mauve
grave grail
#

So [1] is the ran file

#

Read Part 1 rule 🥴

#

The program must not read itself or any other file

fleet lintel
austere mauve
grave grail
#

It counts as a part of the program.

austere mauve
#

How? It's a part of code, but how of program?

grave grail
#

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

austere mauve
fleet lintel
# grave grail Also a further path from the program: - It no longer need to be symmetrical, but...

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.
grave grail
#

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

fleet lintel
# grave grail Also a further path from the program: - It no longer need to be symmetrical, but...

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

austere mauve
#

The biggest challenge is to have a line of code that executes after another line, but it's earlier in the file.

grave grail
#

Really nice
(Rule violation: import*1, annotation store bytecode*2)

austere mauve
#

@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

||

grave grail
#

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

fleet lintel
#

Chess Battle Advanced

stable hornet
grave grail
grave grail
fleet lintel
#

So you would need ||4 bytes||

grave grail
#

Oh right I forgot

#

🥴

#

Yep, ||4b||

austere mauve
#

Wait, right, you can remove from both sides at once.

#

So, it can be ||```py
abcd

grave grail
#

I somehow the forgot the case exist as the one who created the question 💀

austere mauve
#

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

stable hornet
#

very clever

grave grail
#

<, > <>, <>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

grave grail
#

You can assume that they understand english

hybrid trail
#

bro 😭

stable hornet
#

I think we're getting a bit far from the original challenge

quartz wave
#

testing epython limits

austere mauve
# grave grail I.e. they can understand ||`NameError: name 'right' is not defined`|| given tha...

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.
grave grail
#

Should have not make the challenge easy and have definite answer on what to output...
You win

austere mauve
grave grail
#

It wasn't in the rule before which I cannot add arbitrary rule after someone completion

You can add this to your challenge, tho.

pure dew
austere mauve
#

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)

austere mauve
#

My current solution is ||...151 bytes...|| long, but there's a plenty room for improvement.

fleet bridge
#

I think I have seen this challenge here maybe 2 years ago

versed eagle
grave grail
grave grail
#

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()
```||
restive void
#

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?

potent comet
#

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.

earnest wing
#

it'll be through object.__subclasses__ traversal if nothing else

arctic skiff
#

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

arctic skiff
arctic skiff
quartz wave
#

ah

arctic skiff
# quartz wave ah

||py [()][0].__class__.__base__.__subclasses__()[161](0,0).__call__()||this will raise SystemExit

#

you can put exit code as argument in __call__

quartz wave
#

eh

#

shortest code involving exceptions i have so far is 85b

arctic skiff
#

show

quartz wave
#

which is almost double the 49b from the async def

quartz wave
earnest wing
#

you'll need to include python version in submissions as well because internals change

arctic skiff
quartz wave
#

mk

arctic skiff
quartz wave
grave grail
austere mauve
earnest wing
#

3.10-3.?? (||SyntaxWarning turning into SyntaxError eventually||)
||```py
1or"Hello, World"

grave grail
#

Oh well, I never memorize much warning

#

async one is the one that I have remember

#

nice to see other warning kind output

grave grail
#

Which doesn't meet your requirement

#

Don't break your own rule lmao🥴

grave grail
#

My phone do this🥴
||

<string>:12: SyntaxWarning: invalid decimal literal

[Program finished]

||
Well, guess I can only test when I get home

austere mauve
# grave grail The status code is 100% not 0

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).

austere mauve
grave grail
oak horizon
#

does anyone know WTF the parser calls the token: SOFT_KEYWORDS ?
asking for a @upbeat folio

karmic pumice
grave grail
#

Oh, you can? I never give a thought about them

oak horizon
fleet bridge
grave grail
midnight isle
#

When will Python reach version 4.0 and what do you guys and gals think that will look like

flint hollow
#

there's no guarantee it will

earnest wing
#

there's an almost guarantee it won't

oblique ibex
#

why so?