#esoteric-python

1 messages · Page 106 of 1

stark fable
rigid yoke
#

ohhh

#

wait what did you take out?

stark fable
#

a space

#

) for -> )for

rigid yoke
#

ahhh welp tysm

stark fable
#
for x in range(1,101):print(*[i for i in range(1,x+1)if x%i==0])``` this also makes it another character shorter
rigid yoke
#

ohhh ty!

#

i'm assuming people who scored lower than that would have used a different method

#

but i'll try another problem now

#

thank you 🙂

obsidian scarab
#

when normal seed isn't enough

toxic jewel
#

think im gonna make a hello world just from zero

#
(
    (lambda _: (
        print(_.__invert__().__abs__())
    ))(
        __import__("__main__").__doc__.__bool__().__int__())
)```
sick hound
#

!e (
(lambda : (
print(
.invert().abs())
))(
import("main").doc.bool().int())
)

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1
toxic jewel
#

progress so far

#

this is gonna take forever

sick hound
#

how did you learn to make this

toxic jewel
#

by stalking this channel for months on end and learning dunders

#

almost have one letter!

#

out of all of these..

#

uh

#

i cant send my code

#

not sure why it gives me that but i now have one letter!

sick hound
#

what.

toxic jewel
#

lmao

#

lemme try to compress it and send

#

!e

(lambda _,__,___:__.stdout.write(___(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__())))))))))))).__mul__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__()))))))).__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__())))))))(__import__('__main__').__doc__.__bool__().__int__(),__import__('sys'),chr)
night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

_
errant kiln
#

Instead of x%i==0 you can often get away with x%i<1 or even 1^x%i

#

Wait no, xor doesn't work here, but the less than 1 should

terse mortar
#

!e t```py
____ = 100

print(chr(.add(import("math").sqrt().int()).add(import("math").sqrt().int().sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([____].len().bool().str().len())))))

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

t
toxic jewel
#

5 chars in

#

298 lines

toxic jewel
#

__import__ done

shy remnant
#

fizzbuzz?

#

no

#

idk

toxic jewel
#

its finished

#

1k+ lines

#

that can all be condensed to one

terse mortar
toxic jewel
#

no clue

#

81,086 characters @terse mortar

terse mortar
#

Pog

toxic jewel
#

it could definitely hit 100k chars if i didnt use lambda

terse mortar
#

Now using eval and chr make it say ```py
import("hello")

#

It will make it longer

toxic jewel
#

thats what it says

#

theres alot of room for length improvement

#

i also used .__mul__ because i'm lazy

bronze anvil
#

cant remember who i took this from but it's not mine

def ___(n):
    _,__ = 0,1
    while _ < n:
        yield _
        _,__ = __,_+__
for _ in ___(20):
    print(_)
#

!e def (n):
,
= 0,1
while _ < n:
yield _
,
= __,
+__
for _ in __(20):
print(
)

night quarryBOT
#

@bronze anvil :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
floral meteor
#

Inside the print expression

floral meteor
#

Don't make me do it, I'll do unholy things to python that will traumatise you for life

sick hound
#
(lambda _, __, ___, ____, _____, ______, _______, ________:getattr(__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),().__class__.__eq__.__class__.__name__[:__] +().__iter__().__class__.__name__[_:][_____:________])(_, (lambda _, __, ___: _(_, __, ___))(lambda _, __, ___:bytes([___ % __]) + _(_, __, ___ // __) if ___ else(lambda: _).__code__.co_lnotab,_ << ________,(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<_))) + (_____ << ______) + (_ << ___))))(*(lambda _, __, ___: _(_, __, ___))((lambda _, __, ___:[__(___[(lambda: _).__code__.co_nlocals])] +_(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []),lambda _: _.__code__.co_argcount,(lambda _: _,lambda _, __: _,lambda _, __, ___: _,lambda _, __, ___, ____: _,lambda _, __, ___, ____, _____: _,lambda _, __, ___, ____, _____, ______: _,lambda _, __, ___, ____, _____, ______, _______: _,lambda _, __, ___, ____, _____, ______, _______, ________: _)))
floral meteor
#

!e ```py
[(:=[]==[]),(__:=[~-,^-,lambda ,,:[[.extend([[],.pop(_)+.pop(~-),__.pop(~-)])]and [~-_]for ____ in iter(lambda:[~-]<,not )]]),....class.class('%c'%(+),(),{'':print,'le':lambda ,__:.(*__)})()][-]<=__-~_

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041
floral meteor
#

@bronze anvil @sick hound there you go

sick hound
#

nice

#

can you explain the code

#

please

floral meteor
#

!e und here's ein modifikaschun:

fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)])]and __[~-_]for ____ in iter(lambda:__[~-_]<___,not _)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)

#===
 
fib(20)
sick hound
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
floral meteor
#

!e und here's ein modifikaschun:

fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)]),(___:=___-_)]and __[_]-__[~-_]for ____ in iter(lambda:___,_-_)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)

#===
 
fib(8)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
floral meteor
#

there it's now correct

#

it didn't have zero before

#

alrighty then so you want me to explain the workings of this monstrosity?

sick hound
#

yes please

floral meteor
#
def ___(n):
    _,__ = 0,1
    while _ < n:
        yield _
        _,__ = __,_+__
for _ in ___(20):
    print(_)

Is how it works.

#

jk

#
fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)]),(___:=___-_)]and __[_]-__[~-_]for ____ in iter(lambda:___,_-_)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)

fib= that's assigning to a variable. the variable is called fib and this is what we call on later with the desired number n terms of fibonacci.

#

lambda ___: makes a function, with one input to LOAD_FAST

#

also overrides any ___ in locals() / globals() but doesn't override any other variables

#

[ start a list.

#

(_:=[]==[]) initialise the value of _ at True

#

(__:=[ use another walrus operator and start another nested list

#

assigning such to __

#

~-_ invert negative True = 0

#

_^_-_ :: 1 xor (1 - 1) = 1

#

lambda _,__,___:three input variable function

#

[ begin list comprehension

#

[ begin another list

#

__.extend( ... ) make __ longer

#

[__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)] another list.
__[_] the zeroeth element
__.pop(_) get rid of the 1th element and return
+__.pop(~-_) add the return of getting rid of the 0th element
__.pop(~-_) move the now 0th element back to its original position

lone nebula
#

quick question

floral meteor
#

(___:=___-_)] finish the list of evaluation with decrementing the input stack

lone nebula
#

why the fuck is pytorch so hard

floral meteor
#

hol up im still going

sick hound
#

thank u

lone nebula
#

oh

#

sorry

floral meteor
#

idk what pytorch is

#

so that's half the problem

lone nebula
#

yk tensorflow?

#

machine learning

#

and

#

its supposed to be easy to learn

floral meteor
#

and __[_]-__[~-_] forget the previous list and return the previous iteration

floral meteor
lone nebula
#

lmao

floral meteor
#

hence machine learning

sick hound
#

lmao

#

he has a point

floral meteor
#

for ____ in iter iterate.

#

(lambda:___,_-_) only stop iterating if ___ evaluates to 0

#

hence the counter decrements to 0

#

]]), end most of the fuckload of lists and listcomprehension, except for one

#

....__class__.__class__('%c'%(_+_),(), create a class called 0x02 with no inheritance.

#

{'_':print, set the _ attribute to print

#

'__le__':lambda _,__:_._(*__,sep=chr(10)) set the <= behaviour to a function
lambda _,__: self, args
_._ print
*__, expand list as args
sep=chr(10) newline separate args

#

})() end class definition and create an instance of it, with the property that object : 0x02 <= s : List(str) will print the list of strings with newline separation

#

][-_] end our list comprehension suffering and return the last value evaluated in it

#

<= call the __le__ method of this value

#

__[-~_](_,__,___) get the second element of __ and call it with (True, self, input)

#

and that's the end of the function

#

I call it with 8, 8 goes to input, hence it evaluates 8 iterations of yielding fibonacci terms and prints them newline separated

#

any questions?

rugged sparrow
#
>>> @optimize
... def test():
...     x = []
...     x.append(1)
...     x.extend([2,3,4])
...     return x
... 
>>> test()
[1, 2, 3, 4]
>>> dis.dis(test)
  3           0 BUILD_LIST               0
              2 STORE_FAST               0 (x)

  4           4 LOAD_FAST                0 (x)
              6 NOP
              8 LOAD_CONST               1 (1)
             10 LIST_APPEND              1
             12 POP_TOP

  5          14 LOAD_FAST                0 (x)
             16 NOP
             18 BUILD_LIST               0
             20 LOAD_CONST               2 ((2, 3, 4))
             22 LIST_EXTEND              1
             24 LIST_EXTEND              1
             26 POP_TOP

  6          28 LOAD_FAST                0 (x)
             30 RETURN_VALUE
>>> ``` wrote some code that tries to infer a variables type, and if it can it optimizes the bytecode to use the direct opcodes for stuff like `list.append`
#

it works for the following methods

set.add, SET_ADD
set.update, SET_UPDATE
list.append, LIST_APPEND
list.extend, LIST_EXTEND
dict.update, DICT_UPDATE
sick hound
floral meteor
#

ur welcome

earnest wing
#

Does overload abuse fit?

from typing import *

@overload
def frobnicate(n: Literal[0]) -> Literal[1]: ...

@overload
def frobnicate(n: Literal[1]) -> Literal[2]: ...

@overload
def frobnicate(n: Literal[2]) -> Literal[3]: ...

# ...

def frobnicate(n: int) -> int:
  return n + 1
bronze anvil
#

!e (lambda , , , ____, , , ______, ________:getattr(import(True.class.name[] + [].class.name[]),().class.eq.class.name[:] +().iter().class.name[:][:__])(, (lambda _, __, : (, __, ))(lambda , __, :bytes([ % __]) + (, __, ___ // __) if ___ else(lambda: ).code.co_lnotab, << ___,((( << ) + ) << (( << ) - )) + ((((( << )- ) << ) + ) << (( << ) + ( << ))) + ((( <<) - ) << ((((( << ) + )) << ) + ( << ))) + (((<< ) + ) << (( << ) + )) + ((( << ) - ) <<(( << ))) + ((( << ) - ) << (((( << ) + _) <<) - )) - ( << (((( << __) - ) << __) + )) + (<< ((((( << ) + )) << ))) - (((((( << ) + )) << __) +) << (((( << ) + ) << ))) + ((( << ) - ) <<((((( << ) + )) << ))) + ((( << ) + ) << (( <<))) + ( << _____) + ( << ___))))(*(lambda _, __, ___: (, __, ___))((lambda , , :[([(lambda: ).code.co_nlocals])] +(, __, ___[(lambda _: _).code.co_nlocals:]) if ___ else []),lambda _: _.code.co_argcount,(lambda _: _,lambda _, __: _,lambda _, __, ___: _,lambda _, __, ___, ____: _,lambda _, __, ___, ____, _____: _,lambda _, __, ___, ____, _____, ______: _,lambda _, __, ___, ____, _____, ______, _______: _,lambda _, __, ___, ____, _____, ______, _______, ________: _)))

night quarryBOT
#

@bronze anvil :white_check_mark: Your eval job has completed with return code 0.

Hello world!
bronze anvil
#

lol

rigid yoke
rigid yoke
limpid crest
#

python malbolge interpreter in 1 line :)

toxic jewel
#

not really bullshit

#

it has good irl use

#

lambda still tops it tho imo

#
(lambda t: print(f"{t} is your name.")(input("What is your name?")
#

heres a thingy i made

#
while 1: (
    (lambda o: (
        (lambda d: (
            (lambda i: (
                d.get(i)() if i in d else print("Invalid command.")
            ))(input("root@localhost $ ")) # Input
        ))({"clear": lambda: o.system("cls")if o.name == "nt"else o.system("clear")}) # Dict
    ))(__import__("os")) # OS
)
proper vault
#

why use := when you can use a comprehension

toxic jewel
toxic jewel
#

im so confused

#

idk why this wont work

proper vault
#

@toxic jewel p is the whole input, so p[1] is the second character of 'echo e'

#

you could do on line 13

)(*input('root... ').split())
``` and then actually use the `*a` you take in the lambda starting at line 8
toxic jewel
#

ooh

#

you're a genius!

toxic jewel
#
while 1:(lambda o,s,t:(lambda d:(lambda i,*a:d.get(i)(*a)if(i)in(d)else(print(f'Command "{i}" Not Found.')))(*input(f'{t["config"]["name"].lower()}@{t["config"]["host"]}: ').split()))({'clear':lambda:o.system('cls')if(o.name)==('nt')else(o.system('clear')),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a)}))(__import__('os'),__import__('sys'), (__import__("toml").loads(open("config.toml").read())))
#

config.toml is just hostname

#

and with no walrus 😎

fluid tree
#

(lambda a:print(a))(1)
[print(a)for a in(1,)]

toxic jewel
#

fair enough

floral meteor
#

I open this channel and now i feel like I'm home...

#

alright challenge for y'all:
make something that's readable for the wrong reasons

#

but you lose points for anything that's readable for the right reasons

next flame
#

obligatory warning to not run the above code

terse mortar
#

Care to explain what this does?

gentle willow
#

I'm not going to run it, but python can't actually "rm -rf /" without sudo, right?

gentle willow
gentle willow
#

That's why I don't sudo python unless it is my code... Or I am in a chroot on a temporary device

#

That's not to say I don't run plenty of code I shouldn't, just that I don't use sudo

floral meteor
#

Actually it attempts to wipe hard drive but exits if it fails

floral meteor
#

I should've said e.g. not i.e.

#

!zen

night quarryBOT
#
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

floral meteor
#

Imma make an anti-zen

#

and it will perfectly describe the code posted here

#
**The AntiZen of Python, not by Tim Peters.**
Beautiful is worse than ugly.
Implicit is better than explicit.
Complex is better than simple.
Complicated is better than complex.
Nested is better than flat.
Dense is better than sparse.
Readability sucks.
Special cases should break the rules.
Although purity beats practicality.
Errors should be silenced.
In the face of ambiguity, guess.
There should be many-- and preferably more than one --obvious way to do it.
Although none of them might be obvious at first, especially if you're Dutch.
Now is worse than never.
Although *right* now is better than procrastinating.
If the implementation is hard to explain, you're on the right track.
If the implementation is easy to explain, you're doing something wrong.
Namespaces are a terrible idea -- try not to do any of those!
stone bane
#

Can we please not post malicious code that people may accidentally run?

#

Or at least take the responsibility of properly caveating the code snippet itself.

#

Letting evil code float around without adequate warning in the very same message is not cool.

earnest wing
#

Instead, can we all set up a bot to automatically fetch and execute all code blocks posted in this channel? Preferably in the same installation as your discord client.

floral meteor
#

alright it has been exterminated

snow beacon
#
**The Stress of Esoteric Python, by IFcoltransG**
Ugliness is not worse than or equal to beautiful-ness.
Implicit...
Complex things and the idea of complexity itself is seen as more pleasant and/or useful than simplicity in of itself, and by extension simple things, as if anyone would actually consider simple things good, by some unspecified people or person.
Some things are nested (and those things exist (in a manner better than flat ones)).
Dense-is-better-than-sparse.
Eadabilityway isway otnay atthay eatgray.
*Everything is special, especially special cases, enough to warrant breaking the rules.*
Though when in doubt, make it unnecessarily abstract.
Errors? Never heard of 'em.
Maybe in the face of ambiguity, keep them guessing.
There should be many++ or preferably zero ++ways to do it.
Though we're rather cosmopolitan here, so your nationality shouldn't impact your ability to programme.
But not never, because things have to happen.
If the implementation is hard to explain, it's inherently good.
If the implementation is easy to explain, you'd better be sure it's worth it.
Namespaces $namespaces __namespaces__ NameSpaces.
Maybe later.
floral meteor
#

wiped from hardrive, as you will

#

alright I'll abstract the example for the 'readable for the wrong reasons ' challenge

#

!e ```py
not_snekbox_compatible="""
from os import system as sys
from things_to_do.tasks import shell_commands as a
"""
#snekbox substitution
sys=lambda a:0
a=["do this", "do that", "do the other thing"]
#continue

error = debug; command,successfully,executed=('command','successfully','executed')
if sys(a[0]) or sys(a[1]) or sys(a[2]) >= error : exit(error)
else: print(command,successfully,executed)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

command successfully executed
floral meteor
#

there I finally did it

twilit mountain
#

Anyone here ever obfuscated their Python code?

#

Or is there a way to make my Python code non readable to other users?

snow beacon
#

They're are some string obfuscators in the esoteric python challenges GitHub repo.

twilit mountain
#

It's like, I wanna obfuscate it and then pack it using cx_Freeze and distribute to other people

#

Can anyone help?

stone bane
#

There's a few obfuscators available, I believe pyamor is one. Check it out. I will note though that there's code deobsfucators available too

twilit mountain
#

@stone bane sorry for the ping, but do u know how to do it?

fluid tree
stark fable
twilit mountain
stark fable
#

if it actually matters if someone can get the code (i.e. if they could then obtain supposed-to-be-secret information and break the security of something) then you've already done something wrong and you should rewrite things on the assumption that an attacker can deobfuscate your code perfectly

#

if you just generally don't really want people to be able to deobfuscate it but nothing particularly bad is going to happen if they do then it's fine

twilit mountain
#

Well it's not like, I have any passwords or credit card numbers or something

#

I just don't want people to see the code

stark fable
#

alright sounds like it's fine then beecloseloaf

twilit mountain
#

If they see it by cracking the obfuscated code, then I don't have a problem

stark fable
#

just sometimes obfuscation is an attempt to make sure someone won't see holes in a clearly insecure system and with that the solution is to make the system more secure

twilit mountain
#

Ahh nah, haha

stark fable
#

alright good slugloafbeetuch

snow beacon
#

It's probably pretty easy to just ship the .pyc files rather than the source. They look incomprehensible, even if they're not too hard to decode.

#

You do need to be more careful about your Python version if you go that route though.

twilit mountain
verbal geode
#

Sure!

#

(don't run that. seriously.)

hardy burrow
#

!e

1+1+1*0.+1
night quarryBOT
#

@hardy burrow :warning: Your eval job has completed with return code 0.

[No output]
hardy burrow
#

what

stark fable
#

...what did you expect it to do beecloseloaf

lunar ore
#

!e

print(*b"e")

How does this work

night quarryBOT
#

@lunar ore :white_check_mark: Your eval job has completed with return code 0.

101
lunar ore
#

Actually, why does it work

#

!e

print(*range(*b"e"))
night quarryBOT
#

@lunar ore :white_check_mark: Your eval job has completed with return code 0.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
lunar ore
#

Unpacking a bytes object gives you an int?

karmic edge
#

shouldn't it be bytes

twilit grotto
#

each byte is just a number right?

karmic edge
#

it's 0 1

#

no

#

that's nvm

lunar ore
toxic jewel
#

nvm it got killed

twilit grotto
#

it would probably dissuade most people; won't help if someone really wants to though

toxic jewel
#

creating OS and kernel in python

fluid tree
lone scarab
#

!e

type("H",(),{"H":"H"})().H
night quarryBOT
#

@lone scarab :warning: Your eval job has completed with return code 0.

[No output]
lone scarab
#

!e

print(type("H",(),{"H":"H"})().H)
night quarryBOT
#

@lone scarab :white_check_mark: Your eval job has completed with return code 0.

H
twilit mountain
#

Anyone here ever obfuscated their code?

#

Ping me if anyone has!

next flame
#

um, scroll up?

twilit mountain
#

@next flame to?

tribal moon
#

just keep scrolling until you find discord messages

toxic jewel
#

@twilit mountain yea

#

only hand obfuscating tho

#

anything else is gross

verbal geode
#

if run in terminal on linux terminal crashes

twilit grotto
#

(don't run that. seriously.)
presumably you read this part, right

rugged sparrow
#

it attempts to read ~2.15 gb of random data

verbal geode
verbal geode
#

i didnt know what would happen

#

and i just ran it

#

and

#

it fucking crashed my pc

twilit grotto
#

you...sent it without knowing what it does?

verbal geode
#

no

#

i did

#

i sent it after i knew what happened and i knew it a long time ago

amber ravine
verbal geode
#

13 gigs of ram

twilit grotto
#

bruh

toxic jewel
#

anyone know how to inline with open?

#
while 1:
    (
        lambda o, s, n, h: (
            lambda d: (
                lambda i, *a: d.get(i)(*a)
                if (i) in (d)
                else (print(f'Command "{i}" Not Found.'))
            )(*input(f'{n}@{h}: ').split())
        )(
            {
                "clear": lambda: o.system("cls")
                if (o.name) == ("nt")
                else (o.system("clear")),
                "exit": lambda: s.exit("Process Killed Successfully."),
                "echo": lambda *a: print(*a),
            }
        )
    )(
        __import__("os"),
        __import__("sys"),
        (lambda _o: (_o.read(), _o.close())[0])(open("storage/user.txt")),
        (lambda _o: (_o.read(), _o.close())[0])(open("storage/host.txt")
        )
    )

#

currently doing this because i can't figure out how to do it

snow beacon
#

I tend to like pathlib for files. It means not worrying about closing them.

next flame
#

i mean, you don't have to close the file

toxic jewel
#

yea ik i just wanna go that extra length to close it and all

#

i wanna make a fully functioning command line

#

i made rmdir/mkdir/mkfile/rmfile today

#

not sure how ill do file management

snow beacon
#

I think Pathlib has commands for all of those.

floral meteor
toxic jewel
#

so i use lambda to compensate

floral meteor
#

I use lambda already as I use it within a dunder method

#

So I make it an array of operations and return the relevant value by indexing it

toxic jewel
#

i was originally gonna do something like elif _input == "echo": but then i remembered dictionaries are just python switch statements

floral meteor
#

Yeah almost a replacement

toxic jewel
#

"rmfile": lambda *a: (o.remove(a[0] if type(a) == tuple else a))if o.path.exists(a[0] if type(a) == tuple else a) else print("Lambda: File does not exist.")

#

weird workaround but somehow works

floral meteor
#

What would be another tuple element?

#

Oh o.path.exists

#

I'm dumb aha

#

I did a whole try except suite

#

With open with read perms dot close

toxic jewel
#

idk how to condense a try/except into one line

#

so i just manually checked

floral meteor
#

Yeah there was a python enhancement protocol for that that got rejected

#

Probably by some pep8 purist

toxic jewel
#

pep8!? cringe!

#
while 1:(lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if i in d else print(f'Lambda: Command "{i}" Not Found.'))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a),'mkfile':lambda *a:open(a[0]if type(a)==tuple else a,'w').close(),'rmfile':lambda *a:o.remove(a[0]if type(a)==tuple else a)if o.path.exists(a[0]if type(a)==tuple else a)else print('Lambda: File does not exist.')}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt')))
#

not at all the right place

sick hound
#

i checked multiple times to make sure its in the right place

toxic jewel
#

perhaps get a help channel?

sick hound
#

i did not realize this was the channel i was typing in my bad

toxic jewel
#

no problem

formal sandal
#

!e
@toxic jewel
You can use iter and call a function repeatedly.

sum(iter(lambda: print("hi") or 0, object()))
night quarryBOT
#

Sorry, an unexpected error occurred. Please let us know!

ClientResponseError: 500, message='Internal Server Error', url=URL('http://snekbox.default.svc.cluster.local/eval')

formal sandal
#

argh

#

well, this should print hi repeatedly

twilit grotto
#

oop

formal sandal
#

This way, you turn while into an expression instead of a statement

toxic jewel
#

ooh

#

nice

formal sandal
#

pro tip: use proper formatting, and only remove whitespace as a final step

#

maybe just run black on the thing or something like that

earnest wing
toxic jewel
#

yeah i originally had it all spread out but ran it through a minifier

formal sandal
#

!d iter

night quarryBOT
#
iter(object[, sentinel])```
Return an [iterator](../glossary.html#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the iteration protocol (the [`__iter__()`](../reference/datamodel.html#object.__iter__ "object.__iter__") method), or it must support the sequence protocol (the [`__getitem__()`](../reference/datamodel.html#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object... [read more](https://docs.python.org/3/library/functions.html#iter)
formal sandal
#

!e

x = 0
def f():
    global x
    x += 1
    return x - 1

print(list(iter(f, 10)))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
toxic jewel
#

hm

earnest wing
#

You're probably trying iter(print(...), ...) or something

#

wrap the inner function in a lambda

tribal moon
#

Make a new "language" type thingy by using classes and stuff

#

(something like this) ```py
System = Language()

square = (System+System.function)("a", "b") & ValueError > (
f"squared = System.Math().pow(a, b){newline}"
"System[::].Stdout(int).write(squared)"
)

System.loop(0, 7, 1, square, 5)```

#

with code that looks like #bot-commands message

earnest wing
#

DSL-s in python are my favorite

silver flint
#

wait dsl stands for domain specific language right

#

or is my memory broken

earnest wing
#

yes

silver flint
#

kool

toxic jewel
#

could I use a for loop as a while loop?

tribal moon
#

yeah

toxic jewel
#

how

tribal moon
#

using iter I forgot how but it went along the lines of: py [thing for thing in iter(0, condition)]

toxic jewel
#

'v must be callable'

earnest wing
#

you swapped the params but yeah, iter(lambda: condition, 0)

toxic jewel
#

what would condition be?

earnest wing
#

whatever you would put in while

toxic jewel
#

not sure if im doing this right

snow beacon
#

Which lambda is for the loop?

#

iter's first argument has to be a function that takes no args, so it's a lambda: rather than a lambda anything:.

tribal moon
#

is there a way to run code without having it in a string

#

so like py run( custom_function_in_the_file(a, b) )

#

because right now run calls exec on the string passed into it

#

like I have esoteric code that goes like: py func = (System+System.function)({"a": language.int64, "System": language.Language}) & throws(Exception) > ( "num = System[::].Stdin(int64).scan()", "System[::].Stdout(int64).write(a + num);" )

#

I want the code part though to be not a string

floral meteor
#

Technically

earnest wing
#

If you want it to be outside a string, you'll have to make sure everything is a valid expression

#

So something like x = y isn't an expression but (x:=y) is

floral meteor
#

Do you want it hardcoded or simply not using str objects?

earnest wing
#

So realistically you'll have to change your syntax slightly, and to wrap things in lambdas

#

(for delayed execution)

floral meteor
#

Trailing semicolon alert!

#

Here come the Pep8 police...
And they died of shock seeing everything else in this channel

#

How do I make a class with __repr__ override detect whether it's being used in a terminal or running file?

snow beacon
#

It's probably in sys somewhere.

#

Or __name__.

floral meteor
#

Essentially so I can make a special string subclass that, when printed, I can return it's value without echoing it's representation

#

Name equals main in terminal and file

#

Or is something else when imported

floral meteor
#

Perhaps file but that accesses module globals not running globals

snow beacon
#

print uses __str__ rather than __repr__.

floral meteor
#

Ik but the terminal echoes the representation rather than the string

#

When a raw expression is thrown in there

snow beacon
#

Try checking stack frames.

snow beacon
#

If you can put some code in brackets and it gives back a value, it's an expression. If it has to be on a line of its own, it's a statement.

tribal moon
#

the reason why it's in a String is so that it doesn't run immediately before being called

snow beacon
#

You can use lambda to delay evaluation of expressions.

tribal moon
#

delay it how?

floral meteor
#

So I want

ls

In the terminal to have a repr of its empty call, which I have achieved,

_=-ls

to store data in _
But

std << ls 

To return the data as well as execute the write to stdout but the data shouldn't display when represented hence I have to set it's representation to blank but I want this to happen only in terminal where representation gets echoed

snow beacon
#

lambda: print("hello") does nothing, but (lambda: print("hello"))() prints hello.

tribal moon
#

oh wow

#

I guess I can do that

#

I'll try

snow beacon
floral meteor
#

But it isn't esoteric

#

Is it?

snow beacon
floral meteor
#

Also, additionally if it's being sub-repred I.e. error involving this object, or repr of an array of these to be a string that's not empty

snow beacon
tribal moon
#

I know

#

I can't do the lambda thing

#

it cannot be an expression

#

it has to be a statement

snow beacon
#

Why?

#

In this channel we have a very specific set of skills, one being turning code into expressions.

tribal moon
#

because of names

snow beacon
#
num = System[::].Stdin(int64).scan()
System[::].Stdout(int64).write(a + num)
```is just `(num := System[::].Stdin(int64).scan(), System[::].Stdout(int64).write(a + num))` in Python 3.9.
tribal moon
#

what if I wanna reference an argument in the function

#

it won't be defined in the expression

#

because of how the function is called

#
func: language.Function = (System+System.function)({"a": language.int64, "System": language.Language}) & throws(Exception) > (
    lambda: num := System[::].Stdin(int64).scan(),
    lambda: System[::].Stdout(int64).write(a + num)
    )``` the arguments here are `a` and `System`
#

it won't work with expressions because it runs exec on the string code with the second argument as a dictionary of the arguments for globals

snow beacon
#

Were you using them as exec's globals dictionary?

tribal moon
#

Yes

#

exec(code, args)

#

something like that

snow beacon
#

Well, you can do globals().update(dictionary goes here).

#

It's not as contained as with exec though, if that matters.

tribal moon
#

where would I have to put that line?

#

the globals update line

snow beacon
#

Before calling the functions (the lambdas, I mean).

#

It's equivalent to ```python
a = language.int64
System = language.Language

tribal moon
#

well I've have to completely change the code

#

but the code is esoteric

#

there's a lot to take in

snow beacon
#

An alternative is to give the lambdas a parameter, like lambda dictionary: num := dictionary["System"][::].Stdin(int64).scan()

tribal moon
#
class Function:

    def __init__(self, args: dict): # {"name": type} so... {"x": languages.int64}
        self.args = args
        
    def __and__(self, exception: throws):
        self.exception = exception.exception 
        return self._handleFunction(self.exception, self.args)
                                    
        
    class _handleFunction:
        def __init__(hf, exception, *args):
            hf.exception = exception
            hf.args = args
            
        def __gt__(hf, code: tuple):
            return functools.partial(hf._function, code, hf.exception, hf.args)
        
        def _function(hf, code, exc, arguments, *args):

            if (length := len(list(arguments[0].keys()))) != len(args):
                raise exc(f"Function takes {length} arguments, instead, {len(args)} arguments were passed")

            for index, value in enumerate(list(arguments[0].values())):
                if type(args[index]) != value:
                    raise exc(f"Type '{type(args[index])}' of Argument {index} does not match type {type(value)}")
            try:
                code_globals = {**globals(), **dict(zip(list(arguments[0].keys()), args))}
                #print(code_globals, dict(zip(arguments, args)))
                exec("\n".join(code), code_globals)

            except Exception as e:
                raise exc(e)``` here's how it is now
snow beacon
#

{**globals(), **dict(zip(list(arguments[0].keys()), args))} is globals() | dict(zip(list(arguments[0].keys()), args)), incidentally.

tribal moon
#

I'm on 3.8

#

not going to 3.9

snow beacon
#

I expect you have your reasons.

tribal moon
#

well it doesn't really matter

#

it can be the second one

snow beacon
#

I guess given what channel we're in I shouldn't be suggesting ways to simplify code.

tribal moon
#

It's fine, but all I need right now is a way to pass something into the function that takes in statements but doesn't run them until the function is called

#

I don't even think that's possible

#

maybe strings is the only way

floral meteor
#

Nest the expression

#

Don't assign variables to spread it unnecessarily over lines

#

That's unesoteric id say as it follows the Zen

snow beacon
#

(lambda dictionary: dictionary["System"])({"System": "foo"}) is "foo", which is pretty much your goal. Simply call the lambda with the parameters you want later.

floral meteor
snow beacon
#

It's not quite zen.

#

I called it "Stress".

tribal moon
#

well what else do I need to add to this language

#

I should add loops right?

#

I don't know exactly how though

snow beacon
#

It depends on your goal.

floral meteor
#

What about the antiZen above it?

tribal moon
#

my goal is to mock Java

#

or imitate it using Python

floral meteor
#

I've mocked c++

tribal moon
#

so like I want a way to do it how Java does it

snow beacon
#

Having never used Java, I'd suggest yes loops.

floral meteor
#

Abstract away a whole bunch of java commands then import these

tribal moon
#

I just don't know how to like make it look like

#

like the syntax

floral meteor
#

dunders

#

Make classes with dunder methods

tribal moon
#

dunders of what

floral meteor
#

You can do anything

tribal moon
#

I was thinking of like operators or something

#

idk

#

maybe something like

floral meteor
#

Dunders of operstors

#

Operators are deceptive

#

They are really shortcuts to calling dunders

#

Change what those dunders do

tribal moon
#

Loop(i=0) @ "i < 5" @ "i + 1" something like this

#
Loop(i=0) @ "i < 5" @ "i + 1" > (
  "code"
)```
#

I need to know how to implement the i < 5 and i + 1 part though

floral meteor
tribal moon
#

could be challenging

floral meteor
#

If you're doing that then you know what I'm talking about I guess

tribal moon
#

I just can't figure it out

floral meteor
#

Not really you can turn a lambda of multiple inputs into nested lambdas

tribal moon
floral meteor
#

Not really to challenging soz I'm on phone

tribal moon
#

I really don't want for x in thing to be left in because it looks too good

floral meteor
#

Laptop died

tribal moon
#

it needs to look bad like Java

floral meteor
#

Yeah, easy,

#

You want it to loop through code? With step 1 and end when i no longer less than 5?

#

Show me your code so far

tribal moon
#

I think this would be easier py Loop() @ lambda i: ({i: 0}, i < 5, i + 1) > ( code )

floral meteor
#

All I have is marshmallows and an old phon

#

The source I mean

tribal moon
#

There is no source yet

#

for Loop?

#

no soruce

#

the rest there is source

floral meteor
#

.

#

Oh you want help starting?

tribal moon
#

I just need help for Loop

floral meteor
#

!dunder

tribal moon
#

the function is alreadt written out

#

everything is written out

floral meteor
#

Bad bot

tribal moon
#

I know all of it already

#

you want the code right?

floral meteor
#

Yeah that's what source means

tribal moon
#

!paste

night quarryBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

tribal moon
#

lemme paste it

floral meteor
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

floral meteor
#

Do that

tribal moon
#

it's more than 2k chars

floral meteor
#

Split it up then lol

#

Or only past the relevant bit

tribal moon
#

okay here it is for the loop

#
class Loop:
    def __matmul__(self, function) # Loop() @  lambda i: ({i: 0}, i < 5, i + 1)```
#

that's all I have now

#

I just started

#

__matmul__ is the dunder here

floral meteor
#

Alrighty then that's what i needed lol

#

Ty0u g up cos eognkd0heone gonna e.g. wpreyy dhit

#

Ahem

tribal moon
#

must tough typing on the phone

floral meteor
#

Typing up code on phone gonna be pretty shit

#

Might take me a few hours

tribal moon
#

busy day tomorrow

floral meteor
#

Hyperbole

tribal moon
#

yes

#

this could be a start py n = 0 a = lambda i: ({i: 0}, i < 5, i + 1) while True: if a(n)[1]: print("hi") n = a(n)[2]

#

the only problem is the initial value of the specific index

#

i

#

it's supposed to be 0, but n is hardcoded as 0

#

so that's one problem

#

I'll way for you to finish typing your code

snow beacon
twilit mountain
#

Is it easy to make a code obfuscater myself?

snow beacon
#

You want your initial value of i to be outside the lambda, or better yet lambda i=0: (i < 5, i + 1).

tribal moon
#

but it look a long time

#

a really long time

snow beacon
#

If you only have a little code, it's more fun to obfuscate by hand.

tribal moon
#

so like

twilit mountain
#

@tribal moon and can I get a link to the same?

floral meteor
#
class Loop:
  __new__=lambda s,**k:type("",(),dict(
   __matmul__ =lambda s, t:type("",(),dict(
    __matmul__=lambda u,v:type("",(),dict(
     __gt__=lambda w,x:(lambda ...:...)(k,t,v,x)
    )
   )
  )
 )
tribal moon
#
Loop(i=0) @ lambda i: (i < 5, i + 1)```
floral meteor
#

Something like that

tribal moon
floral meteor
#

Replacing ...s with some crazy esoteric code

twilit mountain
snow beacon
floral meteor
#

That nesting I made above will pass all those arguments down across the syntax methods

tribal moon
#

for lambda?

twilit mountain
#

?

snow beacon
#

Personally, I'd do it Loop @ lambda i=0: (i < 5, i + 1) and keep feeding the right of the tuple back into the function until the left of the tuple is False.

floral meteor
#

x could be string or lamnda

#

Make it test for type and execute the relevant code

snow beacon
#

You'd call the lambda, and since i is 0 by default, you'd receive (True, 1), so you'd pass 1 in and get (True, 2) and so on, until you pass in 5 and get (False, 6).

floral meteor
#

Well I'm a slow typer so my solution is for the original syntax

tribal moon
#

I wanna do the lambda one now

twilit mountain
#

@snow beacon can I use yr code obfuscater, which is in the Python Discord Repo?

tribal moon
#

the lmabda i

twilit mountain
#

Nvm

snow beacon
#

But yes, I give my blessing.

twilit mountain
#

Wait, I can't encode whole Python files with yr obfuscater?

snow beacon
#

You should be able to.

floral meteor
#

Could you make a computer think in ND instead of 3D?

snow beacon
#

Keep in mind: it takes a string and returns a string, so if you feed it code, you'll need to exec or eval the result.

snow beacon
twilit mountain
floral meteor
#

I.e. not be limited to thinking in 3d, an AI could visualise and solve higher dimension puzzles like minesweeper

snow beacon
#

Do you want to obfuscate the code before or after compilation?

twilit mountain
snow beacon
twilit mountain
#

I think I would do before compilation

floral meteor
#

Well, I can flatten 4d to 2d if it's discrete data rather than continuous

snow beacon
twilit mountain
#

Oh well

floral meteor
#

I do be making 4d minesweeper puzzles

twilit mountain
#

Thanks for telling!

floral meteor
#

They're fun

#

But the buttons are tiny

snow beacon
#

There's a free 4d minesweeper game on Steam.

#

Unfortunately it has no guess-free mode.

#

Most 3d programs can be generalised. A computer doesn't inherently understand physical space, so doesn't have the reasons we have to avoid four-dimensional conceptualisation.

tribal moon
#

I need to make it so the i attribute of the lambda function is accessible

#

so should the third element of the tuple just be an i/? Alone?

snow beacon
#

That depends.

#

In your lambda i=0: (i < 5, i + 1) example, do you want the first loop iteration to be on 0 or on 1?

tribal moon
#

0

#

wait

#

does this make sense

#
class Loop:
    def __matmul__(self, function): # Loop() @  lambda i=0: (i, i < 5, i + 1)
        return _handleLoop(function)

    class _handleLoop:
        def __init__(hl, function):
            hl.function = function

        def __gt__(hl, code: tuple):
            System = Language()

            loopFunction: Function = (System+System.function)({"i": int, "System": Language}) & throws(InterruptedError) > code
            called = hl.function()

            while called[1]:
                loopFunction(int(called[-1]), System)
                called = hl.function(i + 1)```
snow beacon
#

The hl.function(i + 1) part looks off, at the very least.

#

You're getting your i + 1 from the last element of the tuple.

tribal moon
#

yeah I did that by accdient

#

I mean called[0] + 1

#

because i alone is passed first

snow beacon
#

That implies it only ever increases by 1.

tribal moon
#

wait

#

yeah

snow beacon
#

I figured the lambda was there to specify what the transition is.

tribal moon
#

so the last argument should only be an int?

snow beacon
#

In this case i + 1.

#

I'm still grappling with how to get the i out of the lambda and into an i variable in the body.

tribal moon
#

it's going good so far ```py

Loop() @ (lambda i=0: (i, i < 5, i + 1)) > (
"print('hello')",
)
hello
hello
hello
hello
hello
Loop() @ (lambda i=0: (i, i < 5, i + 1)) > (
"print(i)",
)
1
2
3
4
5
``` but the i part

#

the incremental part

#

and the name

#

how do I get the name of the arg in the lambda

#

like just treat it as any other function

#

is there such thing as a lambda i=0: i to lambda_function.__code__.co_argnames -> ('i',)

snow beacon
#

I'm sure there is, let me check...

tribal moon
#

maybe there's a way with inspect

#

there has to be

#

there most likely is

snow beacon
#

inspect.getfullargspec?

tribal moon
#

lemme see

#

yeah that works

snow beacon
#

There might be a simpler function.

tribal moon
#

yesss awesome it works

#
>>> loop_it = Loop() @ (lambda x=0: (x, x < 10, x + 2)) > (
    "print(x)",
    )
2
4
6
8
10
>>> ```
#

I don't know why I set a variable to it

#

that's useless lol

#

but works

snow beacon
#

inspect.getargvalues looks similar to .getfullargspec.

#

You could make the loop body another lambda if you want — that would obviate the need for figuring out the argument names, but mean more repetition.

#

Or you could mix both and make the loop body a function with no arguments, and call it with an appropriate global.

tribal moon
#

here's how it is now

floral meteor
#

I don't avoid higher dimensions for pretty much the same reason we are all hanging out in esoteric python channel

rugged sparrow
#

@floral meteor do a 4 dimensional conways game of life

floral meteor
#

I could do that omg

#

that would be fun to code

twilit grotto
#

😔 advent of conway's game of life 😔

rugged sparrow
#

yea i remember having to implement the 4d conway for that

#

not as bad as day 20 was tho

floral meteor
#

O_[]

#

I should make 4d CGoL esoterically...

#

Hehehehehehe

#

Wait that's almost the same algorithm minesweeper uses

#

Just without... displaying it?

#

Or do we have to show results?

#

should i take two minutes to write code up here? :P

#
import itertools, numpy
def ___(__):
  ___=[__];_____=lambda _:_[-1]not in _[:-1];_=__;dims=(len(_),)
  while _[0].__class__==list:_=_[0];dims+=(len(_),)
  while _____(___):
    for i, j,k, l in itertools.product(*(range(_)for _ in dims)):
            count=0
            for I in range(-1,2):
              for J in range(-1,2):
                for K in range(-1,2):
                  for L in range(-1,2):
                    try:
                      if __[i+I][j+J][k+K][l+L]:
                        count+=1
                    except:pass
            if count<=1 or count>3: __[i][j][k][l]=0
            elif count==3:__[i][j][k][l]=1
  return __
#

boom

snow beacon
#

Now do it for an arbitrary amount of dimensions.

#

Oh, and no recursion.

#

Recursion is too easy.

formal sandal
#

Type-safe routing in Python using continuation-passing style (sort of, not really, I guess).
https://paste.pythondiscord.com/ugejanerug.py

r = Const("foo", Str(Int(Const("bar", Int(Empty())))))
match = r.extract("/foo/some-string/1/bar/42")

match is inferred as Tuple[str, Tuple[int, Tuple[int, None]]] | None

The idea is quite simple. We have a generic Route type parametrized by the type it 'captures'.
Some basic examples:

class Rest(Route[str]):
    """
    Captures the rest of the path unconditionally
    """
    def extract(self, path: str) -> str:
        return path

class Empty(Route[Literal[None]]):
    """
    Captures None unconditionally
    """
    def extract(self, _: str) -> None:
        return None

more sophisticated routes are done by passing the "rest of the path" as an argument to the constructor:

class Str(Generic[A], Route[Tuple[str, A]]):
    """
    Captures a piece of the path as a string
    """
    def __init__(self, rest: Route[A]):
        self.rest = rest

    def extract(self, path: str):
        m = re.match(r"/([^/]*)(.*)", path)
        if m is None:
            return None
        return (m[0], self.rest.extract(m[1]))
#

So if you want to have a route like /abc/{str}, you write

Const("abc", Str(Empty()))

If your route is /abc/{str}/def/{str}/{str}/{ghi}, it's going to be

Const("abc", Str(Const("def", Str(Str(Const("ghi", Empty()))))))
toxic jewel
#

all of that just to have a statement at the beginning

#
(print("Console loaded successfully.")),[x for x in iter(lambda: (lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if i in d else print(f'Lambda: Command "{i}" Not Found.'))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a),'mkfile':lambda *a:open(a[0]if type(a)==tuple else a,'w').close(),'rmfile':lambda *a:o.remove(a[0]if type(a)==tuple else a)if o.path.exists(a[0]if type(a)==tuple else a)else print('Lambda: File does not exist.')}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt'))), 1)]
tribal moon
#

looping a function: ```py

System = Language()
from numpy import int64
function =(System+System.function)({"x": int64, "y": int64, "System": type(System)}) & throws(Exception) > (
"System[::].Stdout(int64).write(System.Math().pow(x, y))",
)
Loop() @ (lambda i=1: (i, i < 10, i + 1)) & inherits({"function": function}) > (
"function(int64(i), int64(i), System)",
)
4
27
256
3125
46656
823543
16777216
387420489
10000000000```

#

this is what I have now

#

too bad I didn't document it

toxic jewel
#

attempt to remove all spaces except for strings and lambda variables: ... because idk how

#
print('Console loaded successfully.'),[(x)for(x)in(iter(lambda:(lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if(i)in(d)else(print(f'Lambda: Command "{i}" Not Found.')))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda*a:print(*a),'mkfile':lambda*a:open(a[0]if(type(a))==(tuple)else(a),'w').close(),'rmfile':lambda*a:o.remove(a[0]if(type(a)==tuple)else(a))if(o.path.exists(a[0])if(type(a))==(tuple)else(a))else(print('Lambda: File does not exist.'))}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt'))),1))]
toxic jewel
#

also added some error handling

tribal moon
#

Look! ```py

isPrime: Function = (System+System.function)({"n": int, "i": int, "System": type(System)}) & throws(ValueError) > (
"if (System.Math().mod(n, i)) == 0:",
" System[::].Stdout(bool).write(False)",
" System.exit()",
"else:",
" System[::].Stdout(bool).write(True)",
" System.exit()",
)
checkPrimeNumber = System[::].Stdin(int).scan()
1471
Loop() @ (lambda i=2: (i, i < checkPrimeNumber, i + 1)) & inherits({"isPrime": isPrime}) > (
"isPrime(checkPrimeNumber, i, System)",
)
True```

#

this checks for prime number

#

it works!

#

I need to add arrays now

#

I was thinking of something like this ```py

var = 0
class Array:
def gt(self, a):
return self

class _:
def eq(self, b):
return b

var<Array()>_() == 335
335

rugged sparrow
#

type[num] could declare an array of type that is num long

tribal moon
#

Is there a way to get variable annotations?

#

Because I can just use Python's built in variable type hinting mechanism to do it

#

but I need a way to get a variable's annotations

#

so like ```py

var: Array(int) = [1, 2, 3 4]
var.annotations
(Array,)```

rugged sparrow
#

so the upper scope should have an __annotations__dictionary

#

so to get the annotations for a certain variable name you need details from the upper scope

tribal moon
#

Well I need to make a way to make strong typing in this Python script

rugged sparrow
#

one sec i can write a frame hacky thing to do it

#

@tribal moon so the issue is that when Array(int) is called nothing has been stored as an annotation yet

tribal moon
#

why not?

rugged sparrow
#

because the result of Array(int) is what is stored as an annotation

#

it also wont work inside functions

tribal moon
#

So how do I make strong typing?

rugged sparrow
#

well when ```py
def func():
x: int = 1

#

the int type hint isnt saved anywhere

#

its stripped

#

!e ```py
def func():
x: this_name_doesnt_exist

func()```

night quarryBOT
#

@rugged sparrow :warning: Your eval job has completed with return code 0.

[No output]
rugged sparrow
#

^ see its stripped. Its never even ran

tribal moon
#

I know

rugged sparrow
#

you could use inspect.getsource and parse it yourself

tribal moon
#

Nah I can't do that

#

the code is meant to be used in a file and a shell

#

the shell doesn't work for that

tribal moon
#
>>> array = Array(int)
>>> array.addItem(26)
[26]
>>> array.addItem(26)
[26, 26]
>>> array.getItem(3)
IndexError: Item {index} could not be found.
>>> array.getItem(1)
26``` any way to make the syntax more Java-like? (more esoteric)
#

also ignore the {index} part I forgot to make it an fstring

proper vault
#

I think Array<int>() is possible, but not 100% sure

tribal moon
#

it looks like it could work

#

but how would I make Array?

#

Like it'd need to be a class because of the operators and dunders

#

but without calling it, it's type

#

is there a dunder for that?

proper vault
#

metaclasses

tribal moon
#

what would I make the metaclass?

formal sandal
proper vault
#

aww

formal sandal
#

You could just do Array[int](), right?

proper vault
#

yes

#

but that isn't java like

#

it is scala like

formal sandal
#

I guess you can redefine int

#

or make Array < int falsey, while introspecting the line when < is called

tribal moon
#

How am I supposed to make that falsey?

#

I'm still trying to figure out how to change the value of Array without calling it

#

with metaclasses

rugged sparrow
#

You make a subclass of type

#

Then you do class Array(metaclass=typ_subcls): ...

tribal moon
#

I don

#

yes

#

the only way to do the most java like thing is to (Array<type)()>()

rugged sparrow
#

I can write an implementation that'll work with Array<int>(args) in like an hour

#

*it should work

tribal moon
#

I don't think it's possible

#

can you really?

#

how?

proper vault
#

you probably have to modify int or sth

rugged sparrow
#

You can parse bytecode to get the args

proper vault
#

or that

rugged sparrow
#

Yea. It'll work. Gimme an hour

tribal moon
#

alright

#

ping me when you're done

#

in my program, the thing uses int64 from numpy because it feels like it makes more sense that way

lone gust
#

ok I think I got my vim extensions set up 😄

#

thanks for the help @proper vault

verbal geode
#

!e

import sys
print(sys.version())
night quarryBOT
#

@verbal geode :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: 'str' object is not callable
verbal geode
#

!e

import sys
print(sys.version)
night quarryBOT
#

@verbal geode :white_check_mark: Your eval job has completed with return code 0.

001 | 3.9.2 (default, Feb 19 2021, 17:23:45) 
002 | [GCC 8.3.0]
verbal geode
#

3.9.2?

#

😳

#

update, i must

rugged sparrow
#

@tribal moon so my logic i use is this:
scan until we hit COMPARE_OP (>) Followed by JUMP_FORWARD, ROT_TWO, POP_TOP
replace those ops with LOAD_NAME(cls.__name__) LOAD_METHOD(cls.__name__) CALL_METHOD(0) NOP
cls.(cls.name)() will retrieve the TOP two stack items (ocls, args) of the upper frame and shift stack pointer of upper frame
it will then return cls(ocls, args)

tribal moon
#

I'm sorry I'm not good with bytecode and code frames

rugged sparrow
#

!e ```py
import sys, dis
from ctypes import *

def getmem(addr, size):
return (c_char*size).from_address(addr)

class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
idx = 0
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
setattr(cls, cls.name, cls.magic)
nm_idx = frame.f_code.co_names.index(cls.name)
inj_code = bytes([
dis.opmap['LOAD_NAME'], nm_idx,
dis.opmap['LOAD_METHOD'], nm_idx,
dis.opmap['CALL_METHOD'], 0,
dis.opmap['NOP'], 0
])
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize + idx - 1, len(inj_code))
mem[:] = inj_code
idx += 2
return True

def _magic_(cls):
    frame = sys._getframe(1)
    stack = POINTER(py_object).from_address(id(frame) + 8 * sizeof(c_ssize_t))
    ocls = stack[0]
    args = stack[1]
    c_void_p.from_address(addressof(stack)).value -= 2 * sizeof(py_object)
    return cls(ocls, args)

class Array(metaclass=Tmeta):
def init(self, T, args):
print('Array called with:', T, args)

var = Array<int>(1, 2, 3)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

Array called with: <class 'int'> (1, 2, 3)
rugged sparrow
#

@tribal moon ^ example

tribal moon
#

Wow

#

I'm speechless

rugged sparrow
#

has a bit of everything

tribal moon
#

How did you learn how to do this? This is incredible

rugged sparrow
#

basically when it hits Array<int>(1,2,3) ^ Array.__lt__(Array, int) is called

#

oh lots of too much free time

#

inside Array.__lt__ it converts the bytecode of Array<int>(1,2,3) to roughly Array<int;(1,2,3);Array._magic_()

#

then Array._magic_ grabs int and (1,2,3) off of the stack using ctypes, then shifts the stack by 2, then returns Array(int, (1,2,3))

tribal moon
#

that sounds very complicated

rugged sparrow
#

its a bit complex. it helps to understand the interpreter itself

#

@tribal moon that code should work in most cases

tribal moon
#

should work?

#

in some cases?

#

wdym

#

for some reason it restarts the shell

#

IDLE shell btw

#

it could just be IDLE because IDLE is like that

rugged sparrow
#

acc wait

tribal moon
#

No it's not your code

#

it's mine

rugged sparrow
#

i messed up the stack stuff

#

dont use my code yet imma fix it

tribal moon
#

when I add a __repr__ function to Array, it breaks

#

oh

formal sandal
#

pattern matching is implemented on cpython/master, prepare your most brutal esoteric ideas

tribal moon
#

I can't wait to see it

formal sandal
#

works for me

floral meteor
floral meteor
#

But I'll also make a switch statement

tribal moon
#

Do you know how to make a Java-like syntax for HashMap

#

so like in the Python Shell: py hashmap = HashMap<str, int>{ "3": 2, "5": 6 } using gt, lt, and altering frame bytecode>

#

like like what chilaxan did before

floral meteor
#

Nope

#

Well

#

Not altering frame bytecode

tribal moon
#

well maybe I worded it wrong

#

just what chilaxan did up

floral meteor
#

I struggle to get past read only in a code object

tribal moon
floral meteor
#

I get a lot of it

#

Those if nests could be side effected

tribal moon
#

actually I don't think the code really makes sense that I gave for the hashmap thing lol

#
hashmap = HashMap<(str, int)>{
  "3": 2,
  "5": 6
}``` it'd make a bit more sense if the type where in a tuple or something?
#

because I don't think it's possible without

#

or at all maybe....

floral meteor
#

There's no such thing as impossible here

#

Could do something like the above but when HashMap < str, make tuple packing turn into what you want

tribal moon
#

I don't know how to do this code lol

#

It's really cool how people can do this

#

like there obviously aren't any online tutorials for this bytecode thing

#

it's really cool

rugged sparrow
#

@tribal moon i fixed the weird stack bugs

#

cleaning it up then ill send it

tribal moon
#

Oooh Tysm

rugged sparrow
#

@floral meteor i could implement that alternative syntax

#

but it would be way longer

#

but typ<(int,int)>{} works tho

#

!e ```py
import sys, dis
from ctypes import *

def getmem(addr, size):
return (c_char*size).from_address(addr)

replace JUMP_IF_FALSE_OR_POP with NOP then

scan until we hit COMPARE_OP (>) Followed by JUMP_FORWARD, ROT_TWO, POP_TOP

replace those ops with ROT_TWO, ROT_THREE, CALL_FUNCTION(2), NOP

This rearranges the stack to be [cls, T, args], then calls cls(T, args)

and returns it

class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
idx = 0
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
mem[frame.f_lasti + 2] = dis.opmap['NOP']
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[idx:idx + len(inj_code)] = inj_code
idx += 2
return cls

class Array(metaclass=Tmeta):
def init(self, T, args):
print('Array called with:', T, args)

class HashMap(metaclass=Tmeta):
def init(self, T, args):
print('HashMap called with:', T, args)

a = Array<int>(1,2,3)
b = HashMap<(str, int)>{
'a': 0,
'b': 1
}```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | Array called with: <class 'int'> (1, 2, 3)
002 | HashMap called with: (<class 'str'>, <class 'int'>) {'a': 0, 'b': 1}
tribal moon
#

Wow

#

Can I add my own functions to Array?

rugged sparrow
#

yea

#

they should work like regular classes

#

just remember to do metaclass=Tmeta

#

the reason it didnt work before is because i didnt handle the stack correctly

tribal moon
#

this is amazing

#

How can I learn how to do this?

#

Like the bytecode part

#

how does it work?

rugged sparrow
#

so python uses frames to handle function calls and what not

#

every frame has its own bytecode

#

you cant normally modify it like this, but with ctypes you can do it inplace, while it is running

tribal moon
#

What do you mean by modifying the bytecode?

#

Like how does it look like

rugged sparrow
#

!e ```py
def f():
print('hello world')

print(f.code.co_code)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

b't\x00d\x01\x83\x01\x01\x00d\x00S\x00'
rugged sparrow
#

thats the bytecode of that function ^

elder vault
#

pro

#

print ("hello world")

astral rover
#

@rugged sparrow what's bytes.basicsize I cant find anything in the c docs for it

rugged sparrow
#

its the size of a bytes object before any additional data is added to it.

#

its the sizeof the raw c struct

astral rover
#

Ah

rugged sparrow
#

i use it there because bytes holds its char[] right after its base data (-1 to account for the 0x00 at the end of the array)

astral rover
#

Ohhh

tribal moon
#

So now we have Arrays

#

what code should I make now

#

including arrays

#

with this custom Java-like syntax in Python 😆

earnest wing
#

Structs

#

And not just weirder dataclasses

#

or struct I guess

rugged sparrow
#

i actually wrote an implementation of c structs in pure python (that could interface with c code) using the fact that LOAD_CONST can load arbitrary python objects

tribal moon
#

If you wanna add your own things to the code I can send the full code

#

just in case anyone wants to see

rugged sparrow
#

you can remove _magic_

#

its not used anymore

tribal moon
#

it ain't good but it's good at mocking Java

#

oh lol okay

floral meteor
#

!e ```py
class switch:
def init(self,value=True):
self.value=value
def getattr(self,kw):
if kw=='case':return type("Case",(),dict(getitem=lambda s,v:type("CaseStatement",(),dict(init=lambda _,f:[self.value==v and setattr(self,'return',f()),self][1])))
elif not hasattr(self,kw): return None
def otherwise(self, f,*a):
if not hasattr(self,'return'): self.return=f(*a)
return type("returnable",(),{'return':self.return})

i=4
print(switch(i). case[2](lambda: print("haha")). case[4](lambda: print("i can't believe it but it works")or 69). otherwise(lambda: "I'm dumb").return)

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 6
002 |     elif not hasattr(self,kw): return None
003 |     ^
004 | SyntaxError: invalid syntax
tribal moon
#

Now what else to add to this language?

floral meteor
#

I'm on phone which can't fixed width pls fix my code

#

Or screenshot it

tribal moon
#

🤔

rugged sparrow
#

you cant use return as an attribute name

floral meteor
#

What about a 'soft' attribute?

rugged sparrow
#

!e ```py
class x:
pass

setattr(x, 'return', 1)
print(x.return)```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 |     print(x.return)
003 |             ^
004 | SyntaxError: invalid syntax
tribal moon
#

Now I need to make code

#

what code should I make for my language

#

maybe a fibonacci sequence calculator?

#

there's a problem with looping inside of functions

floral meteor
#

!e ```py
w1=print
w2=lambda :getattr(,'..')
class :init=lambda s:s.setattr('..',"()...")
w1(w2(__()))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

__()...
floral meteor
#

Soft coded attributes go brrrrrr

rugged sparrow
#

!e ```py
import sys, dis
from ctypes import *

def getmem(addr, size):
return (c_char*size).from_address(addr)

def builtinexc(exc):
# inject raise after upper function
frame = sys._getframe(2)
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc

def func():
return builtinexc(TypeError('testing'))

func() # raises exc in upper scope and does not reveal internals of func

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 18, in <module>
003 | TypeError: testing
rugged sparrow
#

^ that basically lets you write functions that can emulate c exceptions (with the stripped traceback)

#

!e py int('a')

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'a'
rugged sparrow
#

^ like that

tribal moon
#

@rugged sparrow for some reason the array is not working

#

it's restarting the shell

#

I'm defining one inside of an if statement in the code

rugged sparrow
#

what usage is breaking it

#

send the code

#

@tribal moon ^

tribal moon
#

Okay

#
fibFunction = (System+System.function)({"n": Integer, "value1": Integer, "value2": Integer}) & throws(KeyboardInterrupt) > (
        "value1, value2 = value2, value1+value2",
        );

    System[::].Stdout(String).write("Enter a number here: ");
    n = System[::].Stdin(Integer).scan();
    value1, value2 = 1, 1;

    if (n == 0):
        System[::].Stdout(Integer).write(0);
        System.exit()

    array = Array<int>(0, 0, 1, 1)
    Loop() @ (lambda i=n: (i, i > 2, i - 1)) & inherits({"array": array}) > (
        "array.addItem(4)",
        "System.globalsUpdate('array', array)",
    )```
rugged sparrow
#

Can you try initializing the array normally?

tribal moon
#

you mean array = Array(1, 2, 3, 4)?

#

array = Array(int, (1, 2, 3, 4))

rugged sparrow
#

like Array(int, (1,2,3,4))

tribal moon
#

yeah that works

#

it works

#

not restarting

rugged sparrow
#

can you send all of the code in a paste?

#

@tribal moon

tribal moon
#

yeah sure

#

give me a second

rugged sparrow
#

its working for me

tribal moon
#

maybe it's because I'm using IDLE

#

I get this

#
>>> import language
Enter a number here:
10
Segmentation fault```
#

I have no idea why this happened lol

#

can you try running this: ```py
System[::].Stdout(String).write("Enter a number here: ");
n = System[::].Stdin(Integer).scan();
value1, value2 = 1, 1;

if (n == 0):
    System[::].Stdout(Integer).write(0);
    System.exit()

array = Array<int>(0, 0, 1, 1)
Loop() @ (lambda i=2: (i, i < (n - 1), i + 1)) & inherits({"array": array}) > (
    "array = array.addItem(array.getItem(i) + array.getItem(i - 1))",
    "System.globalsUpdate('array', array)",
)

System[::].Stdout(Integer).write(array.getItem(-1))
input()
System.exit()```
rugged sparrow
#

sure

tribal moon
#

yeah how does it work for you?

rugged sparrow
#

that seg faulted

tribal moon
#

ohhh wait

rugged sparrow
#

interesting

tribal moon
#

it works for you because I sent the code with the other non-esoteric way to define the array

#

why is it doing that?

rugged sparrow
#

no idea

#

its weird

tribal moon
#

for some reason it only works in the shell and not in that if statement

#

looks like it can't get passed array = Array<int>(0, 0, 1, 1)

#

oh

#

wow

#

okay for some reason I got it working

rugged sparrow
#

found the reason

tribal moon
#

but the only way it fix it was to do exec("array = Array<int>(0, 0, 1, 1)")

rugged sparrow
#

gimme a min ill send a new Tmeta

tribal moon
#

Oh

#

okay

rugged sparrow
#

its because the file is so long lmao

#

there is an EXTENDED_ARG opcode

#

one sec

#
class Tmeta(type):
    def __lt__(cls, ocls):
        frame = sys._getframe(1)
        idx = 0
        mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
        i = frame.f_lasti
        while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
            i += 2
        mem[i] = dis.opmap['NOP']
        instructions = [*dis.get_instructions(frame.f_code)]
        for instruction in instructions:
            if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
                if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
                    if instructions[(idx//2)+2].opname == 'ROT_TWO':
                        if instructions[(idx//2)+3].opname == 'POP_TOP':
                            inj_code = bytes([
                                dis.opmap['ROT_TWO'], 0,
                                dis.opmap['ROT_THREE'], 0,
                                dis.opmap['CALL_FUNCTION'], 2,
                                dis.opmap['NOP'], 0,
                            ])
                            mem[idx:idx + len(inj_code)] = inj_code
            idx += 2
        return cls``` @tribal moon new Tmeta
tribal moon
#

alright lemme see

rugged sparrow
#

wait its still broken

tribal moon
#

yeah I keep getting IndexError: tuple index out of range

#

I don't know if that's my code or the Tmeta though

rugged sparrow
#

no ik the issue

#
class Tmeta(type):
    def __lt__(cls, ocls):
        frame = sys._getframe(1)
        idx = 0
        mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
        i = frame.f_lasti
        while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
            if dis.opname[ord(mem[i])] == 'EXTENDED_ARG':
                mem[i] = dis.opmap['NOP']
            i += 2
        mem[i] = dis.opmap['NOP']
        instructions = [*dis.get_instructions(frame.f_code)]
        for instruction in instructions:
            if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
                if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
                    if instructions[(idx//2)+2].opname == 'ROT_TWO':
                        if instructions[(idx//2)+3].opname == 'POP_TOP':
                            inj_code = bytes([
                                dis.opmap['ROT_TWO'], 0,
                                dis.opmap['ROT_THREE'], 0,
                                dis.opmap['CALL_FUNCTION'], 2,
                                dis.opmap['NOP'], 0,
                            ])
                            mem[idx:idx + len(inj_code)] = inj_code
            idx += 2
        return cls``` @tribal moon actually fixed it
tribal moon
#

alright lemme see

#

works

rugged sparrow
#

basically the JUMP_IF_FALSE_OR_POP was jumping to more than 255 so it was generating opcodes that i didnt expect there

tribal moon
#

I get another error

#

the same thing

#

restarting

#

code that probably causes it: py numbers = Array<Integer>() done: Boolean = False while (not done): try: n = System[::].Stdin(Integer).scan() except TypeError: break numbers = Array<Integer>numbers.addItem(n)

rugged sparrow
#

why are you doing code like that?

#

that wouldnt work for java

tribal moon
#

wdym

#

it's supposed to mock Java

#

well I should've probably indented it

#

but still

rugged sparrow
#

anyways that code shouldnt cause an issue

tribal moon
#

Well for some reason it does

#

here's how it goes

#

it asks me for a number

#

I write 1

#

it works

#

it asks me again

#

I write 2

#

then it stops

rugged sparrow
#

yea i see where it breaks

tribal moon
#

bytecode must be hard to work with lol

#

also

#

is there a way to do System::Stdout instead of System[::].Stdout?

#

like similar to C++

#

using bytecode or something maybe?

earnest wing
#

_[System::Stdout] is as close as you can get

floral meteor
#

@rugged sparrow why not use ands instead of nested ifs?

rugged sparrow
#

@tribal moon it is because python optimizes it

#

also your file is massive which leads to python mucking with the bytecode more

#

@floral meteor it would look messier

tribal moon
#

yeah I don't want a 100 char line with just ands

#

the nested if looks cleaner imo

#

my file is massive?

#

like the code I'm writing or the code that makes the code that I'm writing?

rugged sparrow
#

all of your code is in one file

tribal moon
#

I can make it multiples files

rugged sparrow
#

so the bytecode is getting annoying to handle

tribal moon
#

Oh

#

so I'll make it multiple files

steep mural
#

what if you flip the annotation and the name somehow boolean: x = 7 lol would look a bit more like Java i guess

tribal moon
#

so it's easier

floral meteor
#

This is esoteric python readability is overrated

rugged sparrow
#

@tribal moon the reason it breaks is due to my EXTENDED_ARG fix

#

im not gonna fix it

#

to much effort for a joke program

tribal moon
#

lol

#

Yeah my mistake for putting the code where the code that makes that code work

#

I'll put it in another file

#

that could fix it right?

rugged sparrow
#

¯_(ツ)_/¯

#

probably?

tribal moon
#

well it does fix something

#

but I still get an error

floral meteor
#

Meanwhile I have iostreams/bash

tribal moon
#

this time it's a bit weird

#
    while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
IndexError: invalid index```
#

I don't know what that means

rugged sparrow
#

yea thats cause my EXTENED_ARG fix was hacky af

tribal moon
#

Now that the code is in a completely new file, can I roll back to the old TMeta where it was made for short bytecode?

rugged sparrow
#

Probably

#

If you broke the code up into multiple files

floral meteor
#

Add iostreams and "<include import>" syntax

tribal moon
#

what is iostreams

floral meteor
#

Input output streams
Stdout
Stdin
Stderr
Terminal
Using gt and lt signs to pipe to or from files

tribal moon
#

oh my god FINALLY

#

IT WORKED

#
from language import *

System = Language()

System[::].Stdout(String).write("Enter numbers here (write a letter if you're done): ");
numbers = Array<Integer>()

done: Boolean = False
while (not done):
    try:
        n = System[::].Stdin(Integer).scan()
    except TypeError:
        break
    numbers = numbers.addItem(n)
    numbers = Array<Integer>numbers
    
#n = System[::].Stdin(Integer).scan();
value1, value2 = 1, 1;

if (n == 0):
    System[::].Stdout(Integer).write(0);
    System.exit()

hashMap = HashMap<(String, Integer)>{}

    
Loop() @ (lambda x=0: (x, x < len(numbers), x + 1)) & inherits(
    {"Loop": Loop,
     "numbers": numbers,
     "hashMap": hashMap}) > (
         
    "array = Array<Integer>(0, 0, 1, 1)",
    "n = numbers.getItem(x - 1)",
    'Loop() @ (lambda i=2: (i, i < n, i + 1)) & inherits({"array": array}) > (',
    "         'array = array.addItem(array.getItem(i) + array.getItem(i - 1))',",
    "         'System.globalsUpdate(\"array\", Array<Integer>array)',",
    ')',
    "hashMap.putValue(String(n), array.getItem(-1))",
    "System.customGlobalsUpdate('hashMap', hashMap, globals())"
)

writeToFile = (System+System.function)(
    {"hashMap": HashMap,
     "fileName": String,
     "subSystem": System.getType()
     }) & throws(IOError) > (
                "fileReader = subSystem[IOReader].FileIOReader;",
                'fileObj = fileReader(subSystem[::].IOFileMode()[subSystem[::].File:"w"]) >> fileName;',
                'fileObj.write(repr(hashMap))'
                )
         
writeToFile(hashMap, "calculated_fibonacci_sequence.txt", System)
System.exit()


print(fib(n))
``` here's the code
grand urchin
#

Yo’, @bitter iris told me I should check this out—but I have no idea what’s going on here.

bitter iris
#

crazy stuff

grand urchin
#

I wonder if I have anything recent that’s cool enough to show off. Maybe peek on a generator?

#

Here’s something I struggled with the other day: presumably since the data of list are likely to be discontiguous in memory, you could show an appreciable performance difference between a loop on xs and on sorted(xs, key=id) for a sufficiently large structure. Presumably the former would involve more loads as a consequence of cache miss, and you’d see it in a naïve timing. But I was never able to make that materialize, and I ran out of time trying to simulate a pathological case using ctypes to control exact memory layout.

rugged sparrow
#

@grand urchin lists are not discontiguous