#esoteric-python
1 messages · Page 17 of 1
@lapis root, well...
it's the silly side of python xD
In [1]: def main():
...: try:
...: main()
...: except RecursionError:
...: main()
...:
i ran this and got ```
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
File "<ipython-input-1-396208332caf>", line 3 in main
...
Aborted (core dumped)
any more volunteers?
Aborted mission failed
xD
core dumped lmao
def main():
try:
try:
int(input())
except ValueError:
main()
except RecursionError:
main()
It would cause another Recursion error right after it won't it
Bruh
the problem with linux -.-
Why is your language set to alien tho
wdym?
Oh nothing〜
heres something fun to play around with
!e
__import__("ctypes").py_object.from_address(id(globals())+8).value=type("",(dict,),{"__getitem__":(lambda s,i:{}.__class__.__getitem__(s,i)if i in s else ({}.__class__.__getitem__(s,"__builtins__").__getattribute__(i)if {}.__class__.__getitem__(s,"__builtins__").hasattr({}.__class__.__getitem__(s,"__builtins__"),i)else i))})
print(undefined, variables)
@versed eagle :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
undefined variables
I hate you 🖤
!e ```py
import("ctypes").py_object.from_address(id(globals())+8).value=type("",(dict,),{"slots":(),"getitem":(lambda s,i:{}.class.getitem(s,i)if i in s else ({}.class.getitem(s,"builtins").getattribute(i)if {}.class.getitem(s,"builtins").hasattr({}.class.getitem(s,"builtins"),i)else i))})
print(undefined, variables)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
undefined variables
@versed eagle add __slots__ and it won't crash on close
@versed eagle ```ipython
In [4]: import("ctypes").py_object.from_address(id(globals())+8).value=type("",(dict,
...: ),{"getitem":(lambda s,i:{}.class.getitem(s,i)if i in s else ({}.cl
...: ass.getitem(s,"builtins").getattribute(i)if {}.class._getitem
...: _(s,"builtins").hasattr({}.class.getitem(s,"builtins"),i)else i))
...: })
SystemError Traceback (most recent call last)
/usr/lib/python3/dist-packages/IPython/core/async_helpers.py in _pseudo_sync_runner(coro)
66 """
67 try:
---> 68 coro.send(None)
69 except StopIteration as exc:
70 return exc.value
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in run_cell_async(self, raw_cell, store_history, silent, shell_futures)
2985 # Store raw and processed history
2986 if store_history:
-> 2987 self.history_manager.store_inputs(self.execution_count,
2988 cell, raw_cell)
2989 if not silent:
/usr/lib/python3/dist-packages/IPython/core/history.py in store_inputs(self, line_num, source, source_raw)
737
738 if self.shell is not None:
--> 739 self.shell.push(to_main, interactive=False)
740
741 def store_output(self, line_num):
/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in push(self, variables, interactive)
1569
1570 # Propagate variables to user namespace
-> 1571 self.user_ns.update(vdict)
1572
1573 # And configure interactive visibility
SystemError: ../Objects/dictobject.c:1438: bad argument to internal function
In [4]:
You guys tryna break python or do you hate your pc or what :v
yeah it wont work with ipython
In [4]: iSegmentation fault (core dumped)
!e
shorter :D
__import__("ctypes").py_object.from_address(id(globals())+8).value=type("",(dict,),{"__getitem__":(lambda s,i:((g:={}.__class__.__getitem__,b:=g(s,"__builtins__")),g(s,i)if i in s else (b.getattr(b,i)if b.hasattr(b,i)else i))[1])})
print(undefined, variables)
@versed eagle :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
undefined variables
!e upgraded my cursed input thing to allow for different messages
from typing import Callable
from attrs import define
# Overriding input because python bot can't take inputs
inputs = map(str, [1, 3.1415, -12, 1729, 'hello world', 0x603b5, 1+0j, 3, 'END', 10])
def input(_): return print(str(_), w:=next(inputs)) or w
@define(str=False)
class Message:
msg: str
def __str__(self):
return self.msg
@define(eq=False)
class Verify:
msg: Message
fn: Callable[[str, Message], bool]
def __eq__(self, other: str):
return self.fn(other, self.msg)
def check_end(inp: str, msg: Message) -> bool:
msg.msg = ['Invalid number, please try again: ', 'Enter another one: '][inp.isnumeric()]
return inp.lower() in ('', 'stop', 'exit', 'end')
m = Message('Enter numbers: ')
numbers = [int(w) for w in iter(lambda: input(m), Verify(m, check_end)) if w.isnumeric()]
print(numbers)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Enter numbers: 1
002 | Enter another one: 3.1415
003 | Invalid number, please try again: -12
004 | Invalid number, please try again: 1729
005 | Enter another one: hello world
006 | Invalid number, please try again: 394165
007 | Enter another one: (1+0j)
008 | Invalid number, please try again: 3
009 | Enter another one: END
010 | [1, 1729, 394165, 3]
yeah some funny errors i get while using it
!e there are useful things you can do with this knowledge ```py
from fishhook import *
@hook(dict)
def setattr(self, attr, name):
self[attr] = name
@hook(dict)
def getattr(self, attr):
if attr in self:
return self[attr]
return orig(self, attr)
x = {}
x.a = 1
print(x)
print(x.a)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {'a': 1}
002 | 1
!e```py
a = []
a.append(a)
print(a)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[...]]
the fishhook module looks pretty cool
i'll try it out
fishhook is very cool indeed
Ayo what the fuck
hmm
!e
from fishhook import hook
@hook(int)
def __iter__(self):
return map(int, iter(str(self)))
print(sum(1729))
fishhook not fishook
two hs
sum has a default start arg of 0
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
19
it was because the iterator returned strs
that's actually pretty cool
need digit sum? just override int.__iter__ and use normal sum()
!e ```py
from fishhook import *
@hook(int)
def iter(self):
yield from range(self)
print([*10])```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
!e ```py
from fishhook import *
@hook(int)
def getitem(self, idx):
return list(map(int, str(self)))[idx]
print(12345[0:2])```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:7: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
002 | [1, 2]
!e
from itertools import product
from fishhook import *
@hook(int)
def __iter__(self):
yield from range(self)
for x, y, z in product(*[3]*3):
print(x, y, z, end=' ')
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 0 2 1 0 2 2 1 0 0 1 0 1 1 0 2 1 1 0 1 1 1 1 1 2 1 2 0 1 2 1 1 2 2 2 0 0 2 0 1 2 0 2 2 1 0 2 1 1 2 1 2 2 2 0 2 2 1 2 2 2
!e fishhook also supports nested hooks ```py
from fishhook import *
@hook(int)
def add(self, other):
print('hook 1', self, other)
return orig(self, other)
@hook(int)
def add(self, other):
print('hook 2', self, other)
return orig(self, other)
x = 5
print(x + 5)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hook 2 5 5
002 | hook 1 5 5
003 | 10
Wow, nice
orig will refer to the next level up function, so it will chain hooks if you always call orig
@rugged sparrow ```ipython
In [1]: from fishhook import hook
In [2]: bak = dict.setitem
In [3]: @hook(dict)
...: def setitem(self, name, value):
...: if name == 'foo':
...: value = not value
...: return bak(self, name, value)
...:
Unhandled exception in event loop:
File "/usr/lib/python3/dist-packages/prompt_toolkit/eventloop/coroutine.py", line 92, in step_next
new_f = coroutine.throw(exc)
File "/usr/lib/python3/dist-packages/prompt_toolkit/buffer.py", line 1654, in new_coroutine
yield From(coroutine(*a, **kw))
File "/usr/lib/python3/dist-packages/prompt_toolkit/eventloop/coroutine.py", line 92, in step_next
new_f = coroutine.throw(exc)
File "/usr/lib/python3/dist-packages/prompt_toolkit/buffer.py", line 1611, in async_validator
yield From(self._validate_async())
File "/usr/lib/python3/dist-packages/prompt_toolkit/eventloop/coroutine.py", line 88, in step_next
new_f = coroutine.send(None)
File "/usr/lib/python3/dist-packages/prompt_toolkit/buffer.py", line 1202, in coroutine
document = self.document
File "/usr/lib/python3/dist-packages/prompt_toolkit/buffer.py", line 478, in document
return self._document_cache[
File "/usr/lib/python3/dist-packages/prompt_toolkit/cache.py", line 91, in missing
result = self.get_value(*key)
File "/usr/lib/python3/dist-packages/prompt_toolkit/document.py", line 111, in init
self._cache = _text_to_document_cache[self.text]
File "/usr/lib/python3.8/weakref.py", line 131, in getitem
o = self.datakey
Exception 'bool' object is not callable
Press ENTER to continue...
ipython crashed because of your hook, not because of fishhook
Ctrl-Z + Enter on windows, Ctrl-D on unix
!e
from fishhook import *
@hook(int)
def __eq__(self, _):
return False
print(*iter(int, 0))
heh
doesn't work
@low lynx :warning: Your 3.11 eval job timed out or ran out of memory.
[No output]
nice
use task manager to kill the process then
ipython does strange things
!e
from fishhook import *
@hook(tuple)
def __call__(self, *other):
return tuple(map(lambda t:t[0]*t[1], zip(self, other)))
print((1, 2, 3)(1, 2, 3))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:5: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
002 | (1, 4, 9)
i created an new tab and manually closed the former one.. thx btw
your hook changed everything into a bool in dictionaries if the name was foo so ipython broke
i don't remember initializing foo at any point tho
it pulls the strings from your current scope
!e
from fishhook import *
@hook(bool)
def __call__(self, *args, **kwargs):
return [map, filter][self](*args, **kwargs)
print(*False(lambda x: x*x, True(lambda x: x%2, range(10))))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:6: SyntaxWarning: 'bool' object is not callable; perhaps you missed a comma?
002 | <string>:6: SyntaxWarning: 'bool' object is not callable; perhaps you missed a comma?
003 | 1 9 25 49 81
xd
@rugged sparrow, can you use fishhook to bypass setting read only attributes?
probably, it provides force_setattr
ah that one crashes because it tries to free the original string
>>> from fishhook import hook
>>> bak = globals().__setitem__
>>> @hook(dict)
... def __setitem__(self, name, value):
... if name == 'foo':
... value = not value
... return bak(name, value)
...
>>> foo = True
>>> foo
True
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'hook': <function hook at 0x7fb6b1b8c1f0>, 'bak': <method-wrapper '__setitem__' of dict object at 0x7fb6b1dc0680>, 'Foo': <class '__main__.Foo'>, 'f': <__main__.Foo object at 0x7fb6b138ac10>, '__setitem__': None, 'foo': True, 'cStringIO': <weakref at 0x7fb6b1359360; to '_ModuleLock' at 0x7fb6b1d83d00>, 140422651197248: _ModuleLock('cStringIO') at 140422644514048}
>>> globals()['foo']
True
>>> globals()['foo'] = True
>>> foo
False
i'm trying to make fishhook automatically change the value of foo in the global namespace
any ideas?
@rugged sparrow @versed eagle @lapis root @low lynx
i mean it seemed to work already
>>> globals()['foo'] = True
>>> foo
False
without calling globals :/
you shouldnt need to
oh actually nvm it wouldnt call the method on the python object
in that case, change the type of globals
globals is handled weird by bytecode, it bypasses the regular code path
is there any hope left without threading/multiprocessing?
!e
from ctypes import py_object
class globals_overload(dict):
__slots__ = ()
def __setitem__(self, item, value):
{}.__class__.__setitem__(self, item, not value if item == "foo" else value)
py_object.from_address(id(globals()) + 8).value = globals_overload
foo = True
print(foo)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
i guess there is xD
fun
i haven't really messed about with fishhook.asm
that asm.hook doesnt seem to be working anymore, it might have been inlined by the compiler
it works for other stuff tho
it lets you hook functions defined in C by patching assembly at runtime
ooh
thats a fun idea
*currently it only explicitly supports 64bit intel
since when does fishhook support dunders
since forever?
!e py from ctypes import c_byte import sys n, v = 68, 69 (c_byte * sys.getsizeof(n)).from_address(id(n))[-4] = v print(68, 67 + 1, 69 - 1)
@arctic kettle :white_check_mark: Your 3.11 eval job has completed with return code 0.
69 69 69
😎
I think it's always supported dunders
!e ```py
import fishhook
print(dir(fishhook))
print(fishhook.doc)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['BYTES_HEADER', 'NOT_FOUND', 'NULL', 'Py_TPFLAGS_HEAPTYPE', 'Py_TPFLAGS_IMMUTABLE', 'Py_TPFLAGS_READY', 'TYPE_BASICSIZE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'add_cache', 'alloc', 'allocate_structs', 'assert_cls', 'build_unlock_lock', 'c_char', 'classproperty', 'dis', 'find_offset', 'fishhook', 'force_delattr', 'force_setattr', 'get_cache', 'get_structs', 'getdict', 'getmem', 'hook', 'hook_cls', 'hook_property', 'hook_var', 'lock', 'newref', 'orig', 'patch_object', 'py_object', 'pythonapi', 'sizeof', 'sys', 'unhook', 'unlock', 'version']
002 |
003 | This module allows for swapping out the slot pointers contained in static
004 | classes with the `generic` slot pointers used by python for heap classes.
005 | This allows for assigning arbitrary python functions to static class dunders
006 | using `hook` and `hook_cls` and for applying new functionality to previously
007 | un
... (truncated - too long)
Full output: https://paste.pythondiscord.com/goyizuwefo.txt?noredirect
!e
from fishhook import *
@hook(list)
def __setattr__(self, attr, name):
self+=[(attr, name)]
@hook(list)
def __getattr__(self, attr):
for tup in self:
if attr in tup:
return tup[1]
return orig(self, attr)
x = []
x.a = 1
print(x)
print(x.a)
@lapis root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [('a', 1)]
002 | 1
cool
I just fixed it
fishhook has supported dunders since the first version
In that example you can only have tuples in the list
But now:
!e
from fishhook import *
@hook(list)
def __setattr__(self, attr, name):
self+=[(attr, name)]
@hook(list)
def __getattr__(self, attr):
for i in self:
if isinstance(i, tuple) and attr in i:
return i[1]
return orig(self, attr)
x = [10]
x.a = 1
x.append(6)
print(x)
print(x.a)
@lapis root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [10, ('a', 1), 6]
002 | a
Do idea why anyone would wanna do this but I decided to be silly-
i really need to update the docstring for fishhook
Oh crap I forgot I was messing around and forgot to set it to the second value
!e
from fishhook import *
@hook(list)
def __setattr__(self, attr, name):
self+=[(attr, name)]
@hook(list)
def __getattr__(self, attr):
for i in self:
if isinstance(i, tuple) and attr in i:
return i[1]
return orig(self, attr)
x = [10]
x.a = 1
x.append(6)
print(x)
print(x.a)
@lapis root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [10, ('a', 1), 6]
002 | 1
There we goo
maybe i'm thinking of forbiddenfruit
I'm trying to think of how to do it with a string
Seems kinda impossible but eh
forbiddenfruit also had dunders, but only specific ones
(it also did not support exceptions inside hooks)
fishhook's original purpose was for me to find a way around those limitations
Strings are immutable.. so it really is impossible. How could I forget
laughs in ctypes
look at einspect by @dry mirage it could be used to do what you want
it has structure definitions for most builting types
!e
from fishhook import *
@hook(str)
def __setattr__(self, attr, name):
global x
x = self+"{}:{}-".format(attr, name)
@hook(str)
def __getattr__(self, attr):
for i in x.split("-"):
if ":" in i:
atr, e = i.split(":")
if attr == atr:
return e
x = ""
x.a = 1
x.b = 2
print(x.a)
print(x.b)
@lapis root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
I was able to get this far
Only 1 problem
How tf do I reference the variable name without hard coding it in
also, suppose you set one of the attributes to "-"
then the .split won't do what you want it to
or set it to ":"
Then split by space
so this string will mess with you then "- :"
Split by some fucking unicode character then 💀
"".join(map(chr, range(149_186)))
thats a string containing every unicode character
whatcha gonna do now :P
That plus my social security number
hm
well, you've got a problem then
bc if i look at the code object for str.__getattr__ and str.__setattr__, i could get your number
XD
from .__code__.co_consts
i thought it was a bad thing if other people had your number
Only if they do bad things ┐('~`;)┌
What are ctypes
import ctypes
gives a way to access c stuff directly from python
lets you do interesting stuff like control globals().__getitem__
Bruh I'm too illiterate to read all dat-
!e
from fishhook import hook
from einspect import view
@hook(str)
def append(self, value):
size = len(enc := value.encode())
with view(self).unsafe() as v:
v.length += size
v.buffer[-size:] = enc
@hook(str)
def __setitem__(self, index, value):
size = len(enc := value.encode())
view(self).buffer[index:index+size] = enc
s = "hello"
s.append("!")
print(s)
s[1] = "3"
s[4] = "0"
print(s)
print("hello")
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hello!
002 | h3ll0!
003 | h3ll0!
basically, it exposes a whole bunch of python wrappers to types and functions from C
Excuse me but wutdafuk
Time to study python from scratch then cuz my life issa lie
!e or mutate ints as well 🥴
from einspect import view
t = 100
view(t).value = 500
print(100)
print(100 == 500)
print(list(range(98, 103)))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 500
002 | True
003 | [98, 99, 500, 101, 102]
You're banned
!e ```py
print("".join(map(chr, range(55296))))
too long to upload?
never seen that
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | �
002 |
003 | !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̀́̂ͰͱͲͳʹ͵Ͷͷͺͻͼͽ;Ϳ΄΅Ά·ΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕ
... (truncated - too long)
Full output: too long to upload
!e
print(len("".join(map(chr, range(55296)))))
@flint hollow :white_check_mark: Your 3.11 eval job has completed with return code 0.
55296
i suppose that's obvious
i've seen this a few times - it occurs over 10,000 characters
!e print(''.join('a' for _ in range(10001)))
@flint hollow :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
... (truncated - too long)
Full output: too long to upload
!e why not just
print('a'*10001)
```?
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
... (truncated - too long)
Full output: too long to upload
I wonder if it's possible to print hello world without using any numbers or letters
no letters is a problem
restricted letters can be done, though, with just aelrstv
i would have pybot run it, but at 6019 characters, it's too long to paste in
the trick to reduce the character space is using either exec or eval, and they both take arguments, which require parentheses
there's also a version that drops to just 9 characters: https://github.com/satoki/PyFuck
!e
exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
@flint hollow :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
each of the chrs creates one of the letters of print('hello world'), they're concatenated together with +, and then sent to exec to be run
the very first, for example, is chr(111+1), or chr(112), which is just p
simplest version of obfuscation
it uses the ASCII set of characters + the extension that Unicode provides
Alriht I’ll try it later
!e
_ = __builtins__.int();
while _ < (((x:=(o:=(-~__builtins__.int().__add__(-~__builtins__.int())))).__pow__(o.__add__(-~__builtins__.int()))).__add__(o)):
getattr(__builtins__, dir(__builtins__)[(o.__pow__(o.__pow__((o.__add__(-~__builtins__.int()))).__sub__(-~__builtins__.int())).__add__(((o.__pow__(o)).__add__(-~__builtins__.int()))))])(_:=(_.__add__(-~__builtins__.int())))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
btw this code is unstable
there is a huge chance that it wont work on your machine
because for some reason dir(__builtins__) differs from person to person 🤷
!e
for e, i in enumerate(dir(__builtins__)):
print(e, i)
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 ArithmeticError
002 | 1 AssertionError
003 | 2 AttributeError
004 | 3 BaseException
005 | 4 BaseExceptionGroup
006 | 5 BlockingIOError
007 | 6 BrokenPipeError
008 | 7 BufferError
009 | 8 BytesWarning
010 | 9 ChildProcessError
011 | 10 ConnectionAbortedError
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wajaluqabi.txt?noredirect
as you can see here, print is at the 133 index for the bot (in dir builtins)
whats wroing with this
for me its 139 tho
How does that even work?
wdym how does that work?
it just assigns characters by their number in ascii table
chr(97) = 'a'
Explain
Like I'm 5
My brain hurts
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
€
it's changes based on what version of python you're using
Soke implementations can assign new items into builtins.
Also sitebuiltins is adding stuff like help, exit, quit, copyright...
I have custom sitecustomize where i am assigning several helper functions like dis (so i can use dis.dis without importing).
So, relying on dir(__builtins__) is a bad idea even in this channel :-)
yeah ik
sometimes you just want to write funky stuff 🤷
I once wrote code that was relying on object.__subclasses__(). Its behaviour differs in 3.10 and 3.11, and it also differs in REPL and non-REPL mode. And for some reason it behaved differently in snekbox, iirc
bored so I made a script for this.. ```py
def fuck(line: str) -> str:
numbers: list[list[int]] = [[] for _ in range(len(line))]
for i, c in enumerate(line):
remainder = ord(c)
for j in range(len(str(remainder)), 0, -1):
n = int('1'*j)
amount, remainder = divmod(remainder, n)
numbers[i].extend(n for _ in range(amount))
return 'exec(' + '+'.join('chr(' + '+'.join(map(str, n))+ ')' for n in numbers) + ')'
line = '''print('Hello World!')'''
print(fuck(line=line))
exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1+1))```
!e exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1)+chr(11+11+11)+chr(11+11+11+1+1+1+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1+1))
@arctic kettle :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
!e ```py
='=%r;exec(%%)';exec(%)
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <module>
004 | File "<string>", line 1, in <module>
005 | [Previous line repeated 497 more times]
006 | RecursionError: maximum recursion depth exceeded during compilation
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <module>
004 | File "<string>", line 1, in <module>
005 | [Previous line repeated 497 more times]
006 | RecursionError: maximum recursion depth exceeded during compilation
i got it: ```py
sys.setrecursionlimit(1000)
s = 'exec(s)'; exec(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "<string>", line 1, in <module>
File "<string>", line 1, in <module>
[Previous line repeated 496 more times]
RecursionError: maximum recursion depth exceeded during compilation
sys.setrecursionlimit(1001)
s = 'exec(s)'; exec(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "<string>", line 1, in <module>
File "<string>", line 1, in <module>
[Previous line repeated 497 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
hi guys, want to share this thing with you. Its a function that allows you to convert an int into a sum of powers of 2 but only uses -~int() and dunder add and pow.
import pyperclip
def power_find(n: int) -> list[int]:
"""Convert an integer into a list of powers of 2.
Args:
n (int): Integer to convert
Returns:
list[int]: List of powers
"""
result = []
binary = bin(n)[:1:-1]
for x in range(len(binary)):
if int(binary[x]):
result.append(x)
return result
def int_to_eso(n: int):
"""Convert an integer into a esoteric implementation of itself
Args:
n (int): Positive only integer that is going to be converted to an esoteric monster
Returns:
str: Esoteric implementation of the number {n}
"""
powers = power_find(n)
buf = []
for power in powers:
if power == 0:
buf.append(f"(-~int().__add__(-~int())).__pow__(int())")
else:
buf.append(f"(-~int().__add__(-~int())).__pow__(-~int(){''.join([f'.__add__(-~int())' for _ in range(power-1)])})")
res = f"sum({str(buf).translate({39: None})})"
pyperclip.copy(res)
return res
Example input -> Output:
int_to_eso(123001)
>>> sum([(-~int().__add__(-~int())).__pow__(int()), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()))])
!e
print(sum([(-~int().__add__(-~int())).__pow__(int()), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())), (-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()))]))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
123001
🤷
lol
#esoteric-python message
similar idea, but here i am costructing integers using only lists literals and math operations
ooh thats interesting too
lmao, the implementation of the number 1234567891234567890 takes 11.5K chars with my method
Hey @karmic pumice!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
there are some optimisations you could make
long addition sections can be turned into powers
e.g.
-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())
->
(-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()))
that example is a bit contrived, since i picked the number of operations to be a power of 2, but the strategy extends past powers of 2
yeah i would like to do that somehow
well, if you know the number of additions that you're going to do in a section
you can check if doing it with pows would be shorter
i was actually thinking of making it with walruses originally so i would just add the difference between closest powers to the latest walrus assigned power
this was my first thing that converted something to a code implementation so im still kinda proud that i made it work 🤷
this is beautiful haha
yeah true
k i cant think of a way of how to actually implement this without some stupid ifs 🤷
want a hint?
i think im on the right way right now, ill test it a bit
yeah i did it, lets go
maybe there are now some 1 extra () but 🤷
Hey @karmic pumice!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
well yeah with large numbers the amount of adds it has to do to get the powers is.. something
i actually want to make that package now lmao
never created one, think that this is a good one to start with
💀
!e this is a compressed version: ```py
exec(eval("'print%@$#@$&!$)#%@$#@$&!@$~??~..~..?~..??~;~;?~;.~,?~,;~,;.??~,,?~,,??~,,.??~,,..~,,;?~,,;.~,,;.?~,,;.??~,,,?~,,,.~,,,.?~,,,..~,,,..??~,,,;~,,,;??~,,,,~,,,,..``.?.??....?..??;?;.?;.?:..?:;,;:;?:,,,:,?:,.:,.?:,;,,;:,;?:,;.,,;.:,,#@$&&)'" + '''z;y...xz:y?,xz,y.....xz.y???xz`y~"+"?"*69)z~y#@$&&#%@$#@$&!@$xz?y#@$)xz&y))xz%y((xz#y.add(xz$yint()xz@y-~xz!y.pow(x'''.replace("z",".replace("").replace("y","","").replace("x","")")))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
123456789123456789123456789123456789
If you don't segfault an interpreted language, are you even trying?
!e import("ctypes").py_object.from_address(0)
@old socket :warning: Your 3.11 eval job has completed with return code 0.
[No output]
what
!e ```py
print(import("ctypes").py_object.from_address(0))
@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
import("ctypes").py_object.from_address(0)
print("it's fine")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
it's fine
Well if it's just a pointer to an out-of-bounds address then it doesn't matter - you have to dereference the pointer
Classic python memory and pointer management
!e ```py
import("ctypes").py_object.from_address(214912748963731)
print("it's fine")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
it's fine
!e ```py
import("ctypes").py_object.from_address(214912748963731)
print("it's fine")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
it's fine
bro used a corruptor on the code
oh so that’s how you check adresses
!e ```py
exec(bytes('汣獡\u2073㩟彟瑳彲㵟慬扭慤张∺效汬Ɐ眠牯摬∡眊瑩⡨㩳弽楟灭牯彴⡟攢湩灳捥≴⸩楶睥猨牴⤩甮獮晡⡥㨩\u2e73祴数弽','u16')[2:])
print(type('Foo bar.'))
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 2, in <module>
004 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_type.py", line 111, in __setattr__
005 | super().__setattr__(key, value)
006 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_base.py", line 107, in type
007 | self._pyobject.ob_type = value
008 | ^^^^^^^^^^^^^^^^^^^^^^
009 | TypeError: expected LP_PyTypeObject instance, got type
you guys know that percentage bar meme with the if else
lambda n:("⚪"*(10-int(n*10))).rjust(10,"🔵")
1 liner
Here's the actual output:
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
['⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪', '🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪', '🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪', '🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪', '🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪', '🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪', '🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪', '🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪', '🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪', '🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪', '🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵']
the actual function:
lambda m:[("🔵"*n).ljust(m,"⚪")for n in range(-~m)]
mine is shorter 😎
yours makes a single bar
well yeah
that's the point
it's not supposed to make the whole thing
cool using ~ tho
mine is shorter and is a single bar 😎
lambda n:("🔵"*(n//1)).ljust(10,"⚪")
that uses an int value
round it
!epy print('''⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪ 🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵''')
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪
002 | 🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵
best progress bar
using //1 is the same amount of chars as int()
well //.1 is less
we need to multiply it by 10, no?
!epy print('''⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪ 🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪ 🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪ 🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵''')
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪
002 | 🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪
003 | 🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪
004 | 🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪
005 | 🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪
006 | 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪
007 | 🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪
008 | 🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪
009 | 🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪
010 | 🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪
011 | 🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵
Now thats ok
//.1 returns 1.0
what?
print("abcdefg"[0.1//.1])
~~~~~~~~~^^^^^^^^^
TypeError: string indices must be integers, not 'float'
hm
!epy print('abc'[1.0])
@arctic skiff :x: Your 3.11 eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: str indices must be integers or slices, not float; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: string indices must be integers, not 'float'
maybe its different for multiplication
wait it doesn't floor it?
wat
but it doesnt return int
but it's a float....
print("abcdefg"*(0.1//.1))
~~~~~~~~~^^~~~~~~~~
TypeError: can't multiply sequence by non-int of type 'float'
!e print(0.1//0.1)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
1.0
boo
I would just pull a
from fishhook import hook
@hook(float)
def __div__(self, other):
return __import__("math").floor(self / other)
cheating!!
nothing is cheating in #esoteric-python
in a way
shortest so far ig
lambda n:("🔵"*int(n*10)).ljust(10,"⚪")
!e```py
(lambda n:("🔵"int(n10)).ljust(10,"⚪") )()
@arctic skiff :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda n:("🔵"*int(n*10)).ljust(10,"⚪") )()
003 | ^
004 | SyntaxError: invalid non-printable character U+200A
that happens to me sometimes when i copy and paste stuff
it inserts extra characters
wait this is actually shorter by a bit:
#prev
lambda n:("🔵"*int(n*10)).ljust(10,"⚪")
#new
lambda n:("🔵"*(a:=int(n))*10)+"⚪"*a
bonk discord
@rough moat
wait nevermind
you have to subtract from 10
so its longer
i made one thats exactly the same length
lambda n:(("🔵"*int(n*10))+"⚪"*10)[:10]
smart
ooh thats fun
oh i shaved off two chars
it'd be too long
never used walrus
darn
cause it'd only save 1 char per use of 10
lambda n:("🔵"*int(n*10)+"⚪"*10)[:10]
36 chars
I always miss this
lambda n:(("🔵"*int(n*10))+"⚪"*10)[:10]
# ^ ^
lambda n:("🔵"*int(n*10)+"⚪"*10)[:10]
Hey
what
def progress_bar(n):
match n:
case 1:return '🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪'
case 2:return '🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪'
case 3:return '🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪'
case 4:return '🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪'
case 5:return '🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪'
case 6:return '🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪'
case 7:return '🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪'
case 8:return '🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪'
case 9:return '🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪'
return '🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵'```
💀
but that uses an int!!!!!
Doesn't matter
!e yoo 2 chars (())
#ignore this line, doesn't do anything important
__import__('fishhook').hook(float,'__call__',lambda n:("🔵"*int(n*10)+"⚪"*10)[:10])
print(.5())
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:4: SyntaxWarning: 'float' object is not callable; perhaps you missed a comma?
002 | 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪
grrr non stdlib
!e
stdlib :D
__import__("ctypes").py_object.from_address(id(f:=.5)+8).value=type("",(float,),{"__slots__":(),"__call__":(lambda n:("🔵"*int(n*10)+"⚪"*10)[:10])})
print(.5())
@versed eagle :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
001 | <string>:3: SyntaxWarning: 'float' object is not callable; perhaps you missed a comma?
002 | 🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪
trying to remove segfault
pathetic
the red x in the result is peer pressuring me 😭
also its like midnight im not at my best here
cut me some slack lmao
lambda n:f"{'🔵'*int(n*10):⚪<10.10}"
``` 35 chars
this is genius damn
I feel like have a m (maximum) argument is shorter and better for actual use
but I think that won't work with the fstring
unless <m.m} would format by the variable m instead of string m
earlier would be shorter ```py
lambda n,m:("🔵"int(nm)+"⚪"*m)[:m]
OR
lambda n,m=10:("🔵"int(nm)+"⚪"*m)[:m]
#❓|how-to-get-help @sick hound
that should probs be considered whitespace
best
!e
print((lambda n: ("🔵"*n).ljust(10, "⚪"))(7))
@dense nova :white_check_mark: Your 3.11 eval job has completed with return code 0.
🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪
!e fishhook and einspect and ctypes are simply perfect for this channel (this uses fishhook)
exec(bytes('彟浩潰瑲彟✨楦桳潨歯⤧栮潯⡫畴汰ⱥ弧损污彬❟氬浡摢\u2061㩟牰湩⡴䠧汥潬眠牯摬✡⤩','u16')[2:])
()()
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:3: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
002 | Hello world!
ops='+-*/%rq'
while 1:
for i in ops[:6]:print(f"Enter '{i}' for {'square root' if i=='r'else i}")
i=input()
if i in ops:
a,b=float(input()),float(input())if i!='r'else None
exec(f'print({a}{i}{b if b else "**0.5"})')
if i=='q':break
Can this be more short
yes
for starters there's whitespace that can be stripped
heres some pretty easy expression shortenings
'square root' if i=='r'else i -> i=='r'and'square root'or i
b if b else "**0.5" -> b or"**0.5"
also you should probably walrus input, and maybe float
and im not sure why you're defining a,b instead of using them inside the fstring directly
(i:='',o:='+-*/%rq',I:=input,{(print("\n".join(map(lambda c:f"Enter '{c}' for {c=='r'and'square root'or c}",o))),exec(f"print({float(I())}{i}{(i!='r')*float(I())or"**0.5"})")if(i:=I())in o else i:='q')for _ in iter(lambda:i=='q',1)})
F:=float is an improvement
alr
it's broken for square root so i fixed it while golfing, 204 ```py
ops=i='+-/%rq'
I=input
while'q'!=i:[print(f"Enter {i!r} for {['square root',i][i!='r']}")for i in ops[:6]];exec(((i:=I())in ops)"exec(f'print({float(I())}{i*(d:=i!="r")}{d and float(I())or"**.5"})')")
wait
fixed
ops=i='+-*/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in ops[:6]];exec(((i:=I())in ops)*"exec(f'print({F(I())}{i*(d:=i!="r")}{d and F(I())or\"**.5\"})')")
it's ```py
ops=i='+-/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in ops[:6]];exec(((i:=I())in ops)"exec(f'print({F(I())}{i*(d:=i!="r")}{d and F(I())or"**.5"})')")
have to escape the quotes in the latter part
ah
so that's 199
why is the varname ops still here
o=i='+-*/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in o[:6]];exec(((i:=I())in ops)*"exec(f'print({F(I())}{i*(d:=i!=\"r\")}{d and F(I())or\"**.5\"})')")
oh yeah
195 ```py
o=i='+-/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in ops[:6]];i=I();exec((i in o)"exec(f'print({F(I())}{i*(d:=i!="r")}{d and F(I())or"**.5"})')")
you didn't replace the second one
uh huh sure that was just me for sure
193 ```py
o=i='+-/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in o[:6]];i=I();exec((i in o)"exec(f'print({F(I())}{i*(d:=i!="r")}{d and F(I())or"**.5"})')")
sneaky little ops hiding in the corner
187 ```py
o=i='+-/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in o[:6]];i=I();exec(i in o and f"print({F(I())}{i(d:=i!='r')}{d and F(I())or'**.5'})")
186 ```py
o=i='+-/%rq'
I=input
F=float
while'q'!=i:[print(f"Enter {i!r} for {['sqrt',i][i!='r']}")for i in o[:6]];i=I();d=i!='r';exec(i in o and f"print({F(I())}{id}{d and F(I())or'**.5'})"or"")
183 ```py
o,I=i='+-/%rq',input
while'q'!=i:[print("Enter %r for "%i+['sqrt',i][i!='r'])for i in o[:6]];i=I();d=i!='r';exec(i in o and f"print({float(I())}{id}{d and float(I())or'**.5'})"or"")
169 disregarding unsafe input ```py
o,I=i='+-/%rq',input
while'q'!=i:[print("Enter %r for "%i+['sqrt',i][i!='r'])for i in o[:6]];i=I();d=i!='r';exec(i in o and"print("+I()+id+(d and I()or'**.5')+")"or"")
167 with the original interfacepy o=f="+-*/%r" i=input while'q'!=f:[print("Enter %r for "%n+["square root",n][n<'r'])for n in o];f=i();f in o and print(eval("float(i())"+["**.5",f+"eval(i())"][f<'r']))
160 with the shorter sqrt ```py
o=f="+-*/%r"
i=input
while'q'!=f:[print("Enter %r for "%n+["sqrt",n][n<'r'])for n in o];f=i();f in o and print(eval("float(i())"+["**.5",f+"eval(i())"][f<'r']))
159 unsafe input ```py
o=f="+-*/%r"
i=input
while'q'!=f:[print("Enter %r for "%n+["sqrt",n][n<'r'])for n in o];f=i();f in o and print(eval("eval(i())"+["**.5",f+"eval(i())"][f<'r']))
good one
156 ```py
o=f="+-*/%r"
i=input
while'q'!=f:[print("Enter %r for "%n+["sqrt",n][n<'r'])for n in o];f=i();f in o==print(eval("eval(i())"+["**.5",f+"eval(i())"][f<'r']))
150 ```py
o=f="+-*/%r"
c="eval(input())"
while'q'!=f:[print("Enter %r for "%n+["sqrt",n][n<'r'])for n in o];f=input();f in o==print(eval(c+["**.5",f+c][f<'r']))
aaa comparison chaining
b if b else "**0.5"
can be
b or'**.5'
but i'm probably late
it still works weird for square root
your code: sqrt(-2) = -2**0.5 = -(2**0.5) = -1.41
how it should work: sqrt(-2) = sqrt(-1) * sqrt(2) = 1.41*i
>>> -2**0.5
-1.4142135623730951
>>> (-2)**0.5
(8.659560562354934e-17+1.4142135623730951j)
👋
this seems like the right place - WTF is Jython?
8.659560562354934e-17 is FPE noise
ye
so it still needs to handle those properly
lol pava. Is it python syntax or just the interpreter class in Java?
Interpreter class in Java + Module in python that interprets java
So can I write pure python code and run it on the JVM with few changes?
import org.python.util.PythonInterpreter;
public class JythonHelloWorld {
public static void main(String[] args) {
try(PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("print('Hello Python World!')");
}
}
}
``` from Jython docs
@old socket that looks especially brutal
wtf is this
well before just a moment ago I considered Jython in that realm. This is next level crazy and it kind of scares me I must know how it works.
lol
I am ready for my transformation to the dark side
naw, I make python challenges for my friends and that seems like an awesome way to blow their minds.
esoteric python and code golfing are great challenges
I will have to check them out, buried in school work rn. Fate brought me here. Soon young skywalker will be one of us
if you're looking for something fun to play around with try checking out fishhook
is a rather brilliant module made by chilaxan
yeah reading the description it seems over my head
!e
from fishhook import *
@hook(str)
def __mul__(self, other):
if not isinstance(other, float):
return orig(self, other)
integer = int(other)
decimal = int((other - integer) * len(self))
return self * integer + self[:decimal]
print("0123456789" * 1.5)
@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.
012345678901234
@glass stone it lets you replace / add methods onto existing classes
I have been cramming Java for the last week because we got a new professor at school and the class changed from the intro class I took. My brain is at capacity for new ideas at the moment. It looks really neat. Is mul a standard dunder? I haven't delved too deep into the dunders
__mul__ is *
ya that makes sense, like I said my poor brain hurts. CCNA, Java OOP and Ethical hacking I'm hit and it's only monday of week 2.
So its a dunder of the type int eh
mhm, so this code replaces the int __mul__ with the one i wrote, allowing it to work with floats
orig points to the original __mul__ through some inspection magic
dunder is a weird word
means double underscore
i'm aware of what it means
i use the term magic method
ah
i don't like "magic" method, because it implies you can't understand the mechanism.
also dunder is more than just magic methods-
__import__ is a dunder
same with __builtins__
and so on
whereas they aren't methods
__class__, __name__, __dict__ are dunder attributes
Types of dunders:
- dunder methods
2) dunder attributes on instance level (__dict__,__name__,__class__)
3) dunder attributes on class level (__slots__,__bases__) - dunder attributes (
__dict__,__name__,__class__,__slots__,__bases__, ...) - dunder global variables (
__name__,__builtins__,__file__,__loader__,__all__,__path__...) + global methods (__getattr__,__dir__) - dunder builtin variables (
__import__) __debug__- it is replaced with corresponding bool value during comppilation, and you cant assign to it. You also cant assign tox.__debug__- dunder local variables (like
__class__in methods) - dunder string values like in
__name__ == '__main__' - dunder filenames (
__init__.py,__main__.py,__pycache__/) - dunder modules (
__future__,__hello__)
there's also module level __getattr__
and there's __future__
how do I invert bool
why doesn't this work:
__import__("ctypes").py_object.from_address(id(False)+8).value = True
!e dunder
@sharp moon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name '__dunder__' is not defined. Did you mean: '__loader__'?
>>> import ctypes
>>> ctypes.c_uint32.from_address(id(False)+16).value=1 # ob_size
>>> ctypes.c_uint32.from_address(id(False)+24).value=1 # ob_digit
>>> int(False)
1
Where did you get the 16 and 24 From?
Is anybody familiar with Polygon API or where might I be able to go to find an algorithmic trading focused server?
// from https://github.com/python/cpython/blob/main/Include/object.h
#define PyObject_VAR_HEAD PyVarObject ob_base;
// ...
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;
// from https://github.com/python/cpython/blob/main/Include/cpython/longintrepr.h
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
(bools are ints under the hood)
I can't find the source of PyObject right now, but it has 2 fields: ob_refcnt (a ssize_t = 8 bytes on x64) and ob_type (a pointer = 8 bytes)
so ob_size is 16 bytes offset, and the first element of ob_digit is 24 bytes offset
@tough willow
you can, it's just that the repr of bools use the id of the singletons instead of their value
!e
from einspect import view, impl, orig
@impl(bool)
def __repr__(self):
if self is False and int(self):
return repr(True)
return orig(bool).__repr__(self)
with view(False).unsafe() as v:
v <<= True
print(False)
print(True)
print(False == True)
print(False is True)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | True
004 | True
oh nice i didnt know einspect was added to !e
who pinged
why do you need view().unsafe()?
!e cuz the memory move not safe 😔
from einspect import view
v = view(True)
v <<= False
@dry mirage :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/view_base.py", line 243, in __lshift__
004 | return self.move_from(other)
005 | ^^^^^^^^^^^^^^^^^^^^^
006 | File "/snekbox/user_base/lib/python3.11/site-packages/einspect/views/unsafe.py", line 55, in unsafe_call
007 | raise UnsafeError(f"Call to {func.__qualname__} requires unsafe context")
008 | einspect.errors.UnsafeError: Call to View.move_from requires unsafe context
- is just 10) in disguise
fair enough
guessing_game = (lambda number: print("Guess the number!") or (list((lambda itertools = __import__("itertools"): itertools.takewhile(lambda guess: ((not ((guess[1:] if guess.startswith("-") else guess).isnumeric() or print("Enter an integer!"))) or int(guess) != number and ((int(guess) > number and print("Guess lower!")) or (int(guess) < number and print("Guess higher!")) or True)), (input("--> ") for _ in itertools.count())))()) or print("First try! Damn!")) and print("Well done!"))
i believe there exists some other string values that are special to interpreter, but are not variable/method/module/file names, but i cant recall any
Hey, what would be the shortest way to check if a numer is prime?
Numbers from 0 to 10000
Speed doesnt matter
Probs something like all(n%x!=0 for x in range(n))
Or for a fair bit more efficiency, range(int(n**.5)+1)
Why the second one is more efficient?
the first prime factor cannot be greater than the numbers sqrt
they mean all(n%x!=0 for x in range(int(n**.5)+1))
hence you dont need to check anything after that
So it doesn't work
You'd need not all
Or I guess any() rather
!e
is_prime = lambda n:all(n%p for p in range(2,n))
print(is_prime(2), is_prime(17), is_prime(81))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
False False False
ah we need a 1
Yeah
no a 2
x % 1 is
!e
is_prime = lambda n:all(n%p for p in range(2,n))
print(is_prime(2), is_prime(17), is_prime(81))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
True True False
yeah
Right you meant that
you want to check if it isn't divisible and if it isn't divisible then it leaves a nonzero remainder
!e ```py
f=lambda x:all(x%i for i in range(2,x))
print(f(0), f(1), f(5), f(15))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
True True True False
which is truthy
no we don't
it's part of the golf now
fine
!e ```py
f=lambda x:x>1==all(x%i for i in range(2,x))
print(f(0), f(1), f(5), f(15))
ok
5 isn't prime damn
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
False False True False
if you already have a factorial defined then
!e
g=lambda n:0**n or n*g(n-1)
f=lambda x:x>1>~g(x-1)%x
print(*map(f, [0, 1, 2, 5, 13, 15, 19, 53]))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
False False True True True False True True
!e
p=lambda n:not __import__("re").match("1?$|(11+)\\1+$","1"*n)
print(*map(p, [0, 1, 2, 5, 13, 15, 19, 53]))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
False False True True True False True True
wow that's clever
What's going on there?
What's this regex doing?
it basically checks against a string of n 1s
(11+) matches against some number of 1s greater than or equal to 2
and \1+ matches against some number of the above pattern
so if n is divisible by some integer p
then (11+) would be able to match against p and \1+ would match (n/p)-1 times, and you would have a match
but if it's prime and no such p exists, then you don't get a match
i love this trick
need help with this
!e```py
from fishhook import hook
@hook(int)
def add(self, other):
return 11
print(1 + 1)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Constant folding, not much you can do about it..
maybe i can override __new__?
!e
from fishhook import hook
@hook(int)
def __add__(self, other):
return 11
x = 1
print(x+1)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
11
oof
Won't help. The compiler sees 1 + 1 in the code and pretty much replaces it with 2.
yeah you make a point
thx for the help @restive void
oh and one more thing @restive void sry for the ping
!e```py
from future import barry_as_FLUFL
from fishhook import hook
@hook(bool)
def ne(self, _): return False
print(True <> False)```
@plush halo :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 7
002 | print(True <> False)
003 | ^^
004 | SyntaxError: invalid syntax
barry_as_FLUFL doesn't work here :/
weird
I think it's REPL only now
i guess... thx for the tip
and btw @dry mirage , you're the creator of einspect?
yep
im not sure why, though
They usually do that with "april-fools" features
afaik
oh cool.. i just heard of it today
i'll add it to my forbidden modules(along with fishhook)
!e you could do this tho
from __future__ import barry_as_FLUFL
from fishhook import hook
@hook(bool)
def __ne__(self, _):
return False
print(eval("True <> False"))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
since compile inherits futures
i thought eval was cheating 😅
but i guess anything goes in this twisted world of esoteric python xD
from inspect import getouterframes as ___,currentframe as ____
__=setattr
_=lambda _:(__(_,'_',_),print(len(___(____()))-4),_(_._));_(_)
I don't think this is how you are supposed to do a python for loop
Looks right
You sure? Maybe I should rewrite some old programs.
!e
from inspect import getouterframes as ___,currentframe as ____
__=setattr
_=lambda _:(__(_,'_',_),print(len(___(____()))-4),_(_._));_(_)
@rugged owl :x: Your 3.11 eval job timed out or ran out of memory.
001 | -2
002 | -1
003 | 0
004 | 1
005 | 2
006 | 3
007 | 4
008 | 5
009 | 6
010 | 7
011 | 8
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/dafutupodu.txt?noredirect
!e```py
i = -3
while True:
i += 1
print(i)
Weird how that starts at -2
xD yeah weird

Basically what the function is doing is calling itself and counting how deep it is in recursion.
!e ```py
{*iter(lambda n=[]:(print(len(n)),n.append(1))if len(n) < 10 else None, None)}
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
Fun fact, a python scrip can import itself. Like if you have a script called foo.py, you can do import foo. Using that, I came up with this loop
import importlib.util
import sys
from inspect import getouterframes, currentframe
print(len(getouterframes(currentframe()))//3)
spec = importlib.util.spec_from_file_location( __file__[-__file__[::-1].find(r'/'):], __file__)
foo = importlib.util.module_from_spec(spec)
sys.modules[__file__[-__file__[::-1].find(r'/'):]] = foo
spec.loader.exec_module(foo)
If you run into a maximum recursion depth error in this first script I posted, or the one I just posted, you can add something like this to increase the recursion depth ```py
sys.setrecursionlimit(1500)
any way to golf this any further:
Q=range
K=enumerate
G='#'
E='.'
C=len
import sys
for P in sys.argv[1:]:A=P.split('\n')
for H,V in K(A):A[H]=A[H].center(C(A[H])+2,E)
A.insert(0,E*C(A[0]))
A.append(E*C(A[0]))
L=[]
for B,I in K(A):
D=''
for F,W in K(I):
M=[]
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:J=0
else:[[M.append(A[B+N][F+O])for O in Q(-1,2)if N or O]for N in Q(-1,2)]
J=M.count(G)
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:continue
elif A[B][F]==G:D+=G if 1<J<4else E
elif J==3:D+=G
else:D+=E
if B>=1:L.append(D)
for I in L:print(I)```
its incredibly ugly and also long
Indent with 1 space for one
i have no idea what that is tbh
print(*L,sep='\n')
A.append(x)
``` can also be shortened to ```py
A+=x,
how can the insert be shortened?
More unpacking
A.insert(0,x)
A.append(y)
# becomes
*A,=x,*A,y
got this
j=E*C(A[0])
*A,=j,*A,j```
What is this supposed to do though?
its game of life
Ah
for P in sys.argv[1:]:A=P.split('\n')
why are you assigning A in a for loop
oh also got this: (G,E)='#.'
I think its because theres an empty item in argv[0]?
let me check without it
You don't need parens there
yeah if I try A=sys.argv[1:].split('\n') I get:
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
AttributeError: 'list' object has no attribute 'split'
exit status 1```
can't it just be sys.argv[-1]
Q can also be range(-1,2) instead of just range
oh nice
it just puts . on either side I'm pretty sure
changed this py if not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}): if A[B][F]==G:D+=[E,G][1<J<4] elif J==3:D+=G else:D+=E
isn't E+A[H]+E shorter then
yeah its just padding it
honestly lines 7 to 10 could be shortened to one line
yep
A=[E+i+E for i in sys.argv[-1].split('\n')]
this is lines 7-10 now
A=sys.argv[-1].split('\n')
for H,V in K(A):A[H]=E+A[H]+E
j=E*C(A[0])
*A,=j,*A,j```
this can replace 7-8
holy shit its down to 433 now
we're not even onto the body yet lmao
this is what it looks like now:
Q=range(-1,2)
K=enumerate
G,E='#.'
C,*L=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
M=[]
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:J=0
else:[[M.append(A[B+N][F+O])for O in Q if N or O]for N in Q]
J=M.count(G)
if not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}):
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
if B>=1:L+=D,
print(*L,sep='\n')```
this is definitely improvable
Q=range(-1,2)
K=enumerate
G,E='#.'
L,*o=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*L(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
M=[]
if{B}&{0,L(A)-1}or{F}&{0,L(A[B])-1}:J=0
else:[[M.append(A[B+N][F+O])for O in Q if N or O]for N in Q]
J=M.count(G)
if not({B}&{0,L(A)-1}or{F}&{0,L(A[B])-1}):
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
if B>=1:o+=D,
print(*o,sep='\n')
```same thing with single space indent (also I renamed `len` to `L`)
too many if else's
that too
use ternary or [1,2,3][(math involving bools)] for the elifs
you can convert first if/else into ternary
Instead of if N or O you can do if+N+O actually nevermind
yeah I would probably have better variable names but I just run my readable code through a minifier to remove all unnecessary spaces and change variables to a single character
the second condition seems unoptimal
I usually do capital letters for functions and lowercase for variables in golf
usually
same
unless the case of variables matter
and usually I'd make it the first letter of the function (E=enumerate)
what if you're doing something like x.y.z(), same thing?
as in?
for renaming the function name
instead of if N or O, can you use if N|O
depends on the situation
J=''.join?
typically it will be the name of the final function
Z=x.y.z
but again, it depends
Fair
this fails with an error
[[[M.append(A[B+N][F+O])for O in Q if N or O]for N in Q],J=0][{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}]```
if you're importing a module then it definitely depends
use walrus
doesnt work
Using walrus is helpful in other cases too:
Q=range(-1,2)
K=enumerate
G,E='#.'
L,*o=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*L(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
J=[sum(G==A[B+x][F+y]for x in Q for y in Q if x|y),0][L({B}&{0,L(A)-1}|{F}or{0,L(A[B])-1})]
if not({B}&{0,L(A)-1}or{F}&{0,L(A[B])-1}):
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
if B>=1:o+=D,
print(*o,sep='\n')
``` I think this should work
untested though
doesnt work
then show what you did
# WALRUS:
A=[E+i+E for i in sys.argv[-1].split(n:='\n')]
print(*o,sep=n)
nope
n:= is one char less than '\n'
Traceback, logic error, output?
[[[M.append(A[B+N][F+O])for O in Q if N or O]for N in Q],j:=0][{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}]
nvm I made a mistake ```py
Q=range(-1,2)
K=enumerate
G,E='#.'
L,o=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=EL(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
J=[sum(G==A[B+x][F+y]for x in Q for y in Q if x|y),0][L({B}&{0,L(A)-1}or{F}&{0,L(A[B])-1})]
if not({B}&{0,L(A)-1}or{F}&{0,L(A[B])-1}):
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
if B>=1:o+=D,
print(*o,sep='\n')
list index error
Line, traceback?
string index out of range
TypeError: list indices must be integers or slices, not set
line #?
same line?
are you on 3.11 ?
im pretty sure yeah
can you give the detailed traceback?
^
the ... or{F}&{0,L(A[B])-1} is returning a set i think
I put L() around it
of this or this?
it would look like
x[1] / y / [2] / 0
^
ZeroDivisionError
idk why it would be zerodivisonerror there but you get my point
string index should only be the [F+O] in A[B+N][F+O]
this should work
if A[B][F]==G:D+=[E,G][1<J<4]
->
D+=[E,G][1<J<4]*(A[B][F]==G)
this gives SyntaxError: assignment expression cannot be used in a comprehension iterable expression btw
why can't you just loop from 1 to len-1
then you don't need to check if it's an edge cell
oh yeah I forgot about that
its dumb - it should be allowed
maybe I should write a PEP
which one is this for?
the for loops
B,I in K(A) and F,W in K(I)
you don't even use W so you can just use range here
but does that save anything?
if I change it to for F in range(I): it doesnt work
you should be able to do this
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
->
D+=[E,G][1<J<4]*(A[B][F]==G)or(((J==3)*G)or E)
TypeError: 'str' object cannot be interpreted as an integer
why not?
string index out of range
@gleaming lindenthis error
oh
can you provide more context please?
shouldn't it be range(len(i))
oh nvm ik why it broke
yeah you forgot len()
this should work now
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
->
D+=((A[B][F]==G)and[E,G][1<J<4])or(((J==3)*G)or E)
yeah its longer
File "<stdin>", line 12, in <module>
File "<stdin>", line 12, in <genexpr>
IndexError: string index out of range
exit status 1```
as long as neither E or G are empty
we don't need enumerate anymore
why are you telling me
when it breaks on something else
line 12 is not what i was messing with
rangeint()()
enumerate(),W # <-- longer
I didn't include the ,W
oh shit I thought you were trying to fix that code
ah
yeah that works
Q=range(-1,2)
K=enumerate
G,E='#.'
C,*L=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
M=[]
J=0if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}else[[M.append(A[B+N][F+O])for O in Q if N or O]for N in Q]
J=M.count(G)
if not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}):D+=[E,G][1<J<4]*(A[B][F]==G)or(((J==3)*G)or E)
if B>=1:L+=D,
print(*L,sep='\n')```
im having trouble keeping all the changes sorted in my mind
at ty
ok is that one working
yeah that works
this probably doesn't work but just putting this out there ```py
R=range
Q=R(-1,2)
K=enumerate
G,E='#.'
L,*o=len,
import sys
A=[E+i+E for i in sys.argv[-1].split('\n')]
W=L(A[0])-1
H=L(A)-1
A,=EW,A,EW
for B in R(1,H):
D=''
for F in R(1,W):
J=sum(G==A[B+x][F+y]for x in Q for y in Q if x or y)
if A[B][F]==G:D+=[E,G][1<J<4]
elif J==3:D+=G
else:D+=E
o+=D,
print(*o,sep='\n')
File "<stdin>", line 14, in <module>
File "<stdin>", line 14, in <genexpr>
IndexError: string index out of range
exit status 1```
smh
enthusiastic person
you can get rid of the if-elif-else block
!e ```py
c = import('ctypes.util')
c_lib = c.CDLL(c.util.find_library('c'))
c_lib.puts(
c.cast(
b'Hello C!',
c.POINTER(c.c_char),
)
)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello C!
only works on certain pythons
@long fulcrum can you give us a test input + expected output
so we can test it ourselves
wait no hold on
Traceback (most recent call last):
File "C:\Users\Desktop\main.py", line 2, in <module>
c_lib = c.CDLL(c.util.find_library('c'))
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py", line 364, in __init__
if '/' in name or '\\' in name:
TypeError: argument of type 'NoneType' is not iterable
mhm
why does it keep messing up the first line
paste it in a code block
!paste
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.pythondiscord.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.
make sure the first line is on the line after the backticks
.............
this should work
if not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}):D+=[E,G][1<J<4]*(A[B][F]==G)or(((J==3)*G)or E)
```->
```py
D+=not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1})and[E,G][1<J<4]*(A[B][F]==G)or(((J==3)*G)or E)
thats from J=0if{B}&{0,C(...
the 0if
ok no errors but its not removing the left, bottom, and right padding
try now
if not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}):D+=[E,G][1<J<4]*(A[B][F]==G)or(((J==3)*G)or E)
```->
```py
D+=(not({B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}))and[E,G][1<J<4]*(A[B][F]==G)or((J==3)*G)or E
i forgot that not is after and
im tired lol
imo we should just get rid of edge checks altogether
by not looping over them entirely
nope same issue with padding
game of life
you should have seen the code before
individual checks for each of the 4 edges and 4 corners
Hey @long fulcrum!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
yeah that'd be better i think
oh 
well it looked like this
thats why I added the padding
to prevent that
is using a dictset to store alive cells with complex numbers shorter
ooh thats a good idea
i have never used complex numbers in python before
I didnt even think they had a use
the only use we've had for them is 2d coordinates
f=lambda :None
f.f=f
print(f is f.f.f)
#True
#False
#AttributeError
Without running the code, what do you think the answer is?
True
would be my guess
but im also tired as hell
so
can you even assign attributes like that?
who knows
yea, you can assign function attributes
It was indeed True. But still, wierd to me
Also you can only do f.f.f.f (and so on) until the recursion limit
like .__call__
how is it weird?
you can only have a maximum of four nested f-strings without an eval or exec
Never thought about assigning attributes to function like that, and didn't expect it to have the recursive effect, but it makes sense now
its the same as a class returning self for something
@type.__call__
class thing:
def __call__(self):
return self
thing()()()()()()()()()()()() is thing
oh yeah this is what the golfed code was like before padding
M='.'
L=enumerate
G=len
E='#'
import sys
for I in sys.argv[1:]:B=I.split('\n')
H=[]
for A,J in L(B):
F=''
for C,N in L(J):
D=0
if A==0and C==0:D=[B[A][C+1],B[A+1][C],B[A+1][C+1]].count(E)
elif A==0and C==G(B[A])-1:D=[B[A][C-1],B[A+1][C-1],B[A+1][C]].count(E)
elif A==G(B)-1and C==0:D=[B[A-1][C],B[A-1][C+1],B[A][C+1]].count(E)
elif A==G(B)-1and C==G(B[A])-1:D=[B[A-1][C-1],B[A-1][C],B[A][C-1]].count(E)
elif A==0:D=[B[A][C-1],B[A+1][C-1],B[A+1][C],B[A+1][C+1],B[A][C+1]].count(E)
elif A==G(B)-1:D=[B[A][C-1],B[A-1][C-1],B[A-1][C],B[A-1][C+1],B[A][C+1]].count(E)
elif C==0:D=[B[A-1][C],B[A-1][C+1],B[A][C+1],B[A+1][C+1],B[A+1][C]].count(E)
elif C==G(B[A])-1:D=[B[A-1][C],B[A-1][C-1],B[A][C-1],B[A+1][C-1],B[A+1][C]].count(E)
else:D=[B[A-1][C-1],B[A-1][C],B[A-1][C+1],B[A][C-1],B[A][C+1],B[A+1][C-1],B[A+1][C],B[A+1][C+1]].count(E)
if B[A][C]==E:
if 2<=D<=3:F+=E
else:F+=M
elif D==3:F+=E
else:F+=M
H.append(F)
for K in H:print(K)```a complete fucking mess
cause there are 4 different types of string literals?
" ", ' ', """ """, ''' '''
not yet, at least
time for a new PEP o.o
!e and this ```py
this=valid=False
print(f"{this * "is" * not valid}")
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(f"{this * "is" * not valid}")
003 | ^^
004 | SyntaxError: f-string: expecting '}'
discord syntax highlights incorrectly
import sys
Q=range(-1,2)
K=enumerate
G,E='#.'
C,*L=len,
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:continue
J=sum(G==A[B+N][F+O]for O in Q for N in Q if N or O)
D+=[E,G][2-(A[B][F]==G)<J<4]
L+=D,
print(*L,sep='\n')
```still optimizable
its actually more like
print("{this * "is" * not valid}")
f"{"something or other"}" should be possible imo
since it's inside the {, it's not ambiguous
!pep 701 why new?
Ooh
cause im too lazy to read current PEPs until like 3 years after they're accepted and implemented
almost works
do you know if there's a PEP on the usage of := in a comprehension?
it prints a newline at the start
import sys
Q=range(-1,2)
K=enumerate
G,E='#.'
C,*L=len,
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B,I in K(A):
D=''
for F,W in K(I):
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:continue
J=sum(G==A[B+N][F+O]for O in Q for N in Q if N or O)
D+=[E,G][2-(A[B][F]==G)<J<4]
if B!=0:L+=D,
print(*L,sep='\n')```
this works
import sys
R=range
Q=R(-1,2)
K=enumerate
G,E='#.'
C=len
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B in R(1,C(A)):
D=''
for F in R(C(A[0])):
if{B}&{0,C(A)-1}or{F}&{0,C(A[B])-1}:continue
J=sum(G==A[B+N][F+O]for O in Q for N in Q if N or O)
D+=[E,G][2-(A[B][F]==G)<J<4]
print(D)
``` even better
to be expressions
return as well
for example:
[continue if somecondition else x**2 for x in range(whatever)]
410 to 321
ooh yeah
because you don't need to repeat {B}&{0,C(A)-1}or{F}&{0,C(A[B])-1} besides other things
wouldn't this just be [x**2 for x in range(whatever) if somecondition]?
it would, but that was a toy example to demonstrate how im imagining the syntax would work
this is one-linable now
some people have done this in just over 100 chars which is crazy
my code is?
yes
how wtf
import sys
R=range
Q=R(-1,2)
K=enumerate
G,E='#.'
C=len
A=[E+i+E for i in sys.argv[-1].split('\n')]
j=E*C(A[0])
*A,=j,*A,j
for B in R(1,C(A)-1):print(''.join([E,G][2-(A[B][F]==G)<sum(G==A[B+N][F+O]for O in Q for N in Q if N or O)<4]for F in R(1,C(A[0])-1)))
``` just 1 more loop
all i can see is a semicolon to get combine py J=sum(G==A[B+N][F+O]for O in Q for N in Q if N or O) D+=[E,G][2-(A[B][F]==G)<J<4]
holy shit
yeah N|O should work now
i suggested that a while ago 😢
It's also possible with deeply nested lambdas
you did?
whoops sorry
im working on homework in the background rn
great minds think alike ✨
i did that here
x|y
idk where you did
here
i didnt even see when you did it lol
yeah because that was on a nonfunctional version
ah
and I renamed them to x and y
packing is the stupidest way to reduce chars and I hate that it works
like this does everything my code does in one line
exec(bytes('浩潰瑲猠獹刊爽湡敧儊刽ⰱ⤲䬊攽畮敭慲整䜊䔬✽⸣ਧ㵃敬੮㵁䕛椫䔫映牯椠椠祳牡癧ⵛ崱献汰瑩✨湜⤧㵪⩅⡃孁崰䄪㴬ⱪ䄪樬昊牯䈠椠⡒ⰱ⡃⥁ㄭ㨩牰湩⡴✧樮楯⡮䕛䜬孝ⴲ䄨䉛孝嵆㴽⥇猼浵䜨㴽孁⭂嵎䙛伫晝牯传椠⁑潦⁎湩儠椠籎⥏㐼晝牯䘠椠⡒ⰱ⡃孁崰⤱⤩','u16')[2:])```
and it's also longer (if you count bytes instead of chars)
yeah thats its only saving grace

