#esoteric-python
1 messages Β· Page 147 of 1
also i can't believe j, n, r, and y are all not taken
all the other letters are taken
yeah
same happens if it starts with a number
because you cant have a name that starts with one
2 is taken??
probably by someone at xbox
ok well i can't reproduce the error
probably because i'm in the REPL
i'll try with a file
ok
no i also can't
oh
if ur down im down
yeah I couldn't reproduce either
but @rich hound honestly you want to use async for this
99% of the work is waiting
Same, I always wished I could have kids.
wait did you mean reproduce an erorr
i think im in the wrong channel mb
..................
by the way we should probably ignore that
Hello, is there a way to get siginfo_t (or siginfo->si_addr) directly from python? (like with ctypes)
what's siginfo
is that a python object by itself
typedef struct {
int si_signo;
int si_code;
union sigval si_value;
int si_errno;
pid_t si_pid;
uid_t si_uid;
void *si_addr;
int si_status;
int si_band;
} siginfo_t;
its from sys/siginfo.h
I'm just writing a port of google/glog for python so I need it to print info about received signal
I already have basic handler but that's not enough
Here's example what glog can do if receives SIGSEGV:
*** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
*** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
PC: @ 0x412eb1 TestWaitingLogSink::send()
@ 0x7f892fb417d0 (unknown)
@ 0x412eb1 TestWaitingLogSink::send()
@ 0x7f89304f7f06 google::LogMessage::SendToLog()
@ 0x7f89304f35af google::LogMessage::Flush()
@ 0x7f89304f3739 google::LogMessage::~LogMessage()
@ 0x408cf4 TestLogSinkWaitTillSent()
@ 0x4115de main
@ 0x7f892f7ef1c4 (unknown)
@ 0x4046f9 (unknown)
I have:
*** Aborted at 1650603124 (unix time) try "date -d @1650603124" if you are using GNU date ***
*** SIGSEGV (@0x0) received by PID 11790 (TID 0x7110cde4f8) from PID 11789; stack trace ***```
hexed siginfo->si_addr must be instead of (@0x0) on the second line
from ctypes import *
pid_t = c_int
uid_t = c_uint
class sigval(Union):
_fields_ = [
('sival_int', c_int),
('sival_ptr', c_void_p),
]
class siginfo_t(Structure):
_fields_ = [
('si_signo', c_int),
('si_code', c_int),
('si_value', sigval),
('si_errno', c_int),
('si_pid', pid_t),
('si_uid', uid_t),
('si_addr', c_void_p),
('si_status', c_int),
('si_band', c_int),
]
to get a field from the struct do struct_instance.field
get_info(&struct_variable)
``` in C is equal to ```py
get_info(byref(struct_variable))
``` in python
Okay, thanks
have you tried printing out full traceback instead of just the error text?
you can't catch a fatal error
fatal errors always end abruptly
if you scroll up more you'd probably read it
this
this is the real error
the "list index out of range" is to be ignored
Code and output using Pure Python library
im currently coding a discord bot that runs the python code safely but my crippling OMORI addiction is preventing me from finishing it faster
you know that u can just use an api to run it right?
what do you mean
theres many python 'emulators' out there
i just send the code off to some server and i get the output as data
just use their private api to run ur code
i think repl has an api but ive never looked into it
just copy @night quarry u just have to change the config.yaml file and everything else will be taken care of by docker
even easier code stealing

Make your own wallpaper with math and a pure Python GL
!e ```py
def abbrev_name(name):
return '.'.join([''.join([c for c in i if c.isupper()]) for i in name.title().split(' ')])
print(abbrev_name("suck your mom"))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
S.Y.M
fr
!e ```py
def abbreviate_word(word):
return '.'.join(map(lambda word: word.title()[0], (word.split(' '))))
print(abbreviate_word("suck your mom"))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
S.Y.M
@upbeat sonnet
!e ```py
import math
auth_check = 'some guys password' #input('password? ')
finalized = ''.join(map(lambda encrypt: auth_check[encrypt::math.ceil(math.sqrt(len(auth_check)))].replace(' ',''), range(math.ceil(math.sqrt(len(auth_check))))))
if finalized in ('sgpoouarmysdessw', 'example1', 'example2'):
print('Access Granted.')```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Access Granted.
if u can make this shorter please send it
smushed @sick hound
import math
a='some guys password'
f,z=''.join(map(lambda e:a[e::math.ceil(math.sqrt(len(a)))].replace(' ',''),range(math.ceil(math.sqrt(len(a)))))),"example"
print('Access Granted.'*f in('sgpoouarmysdessw','%s1'%z,'%s2'%z))
cool thing about multiplying strings
you can multiply them by 0
to make it empty
what is this doing exactly though?
(ryuga is prolly gonna upload a 10 byte version of this later lmao)
@upbeat sonnet :warning: Your eval job has completed with return code 0.
[No output]
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
baconbaconbacon
ah icic
code
!e ```py
A=lambda w:'.'.join(w.title()[0]for w in w.split())
print(A("stop yelling man"))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
S.Y.M
I used to post some eso art ...nao i post it with full source
spam of arts
No documentation found for the requested symbol.
!d lambda
An anonymous inline function consisting of a single expression
which is evaluated when the function is called. The syntax to create
a lambda function is lambda [parameters]: expression
oh
bro that is trippy
i got no clue i just found a string encryptor and decided to remake it
!e py w='stop yelling man';print('.'.join(i[0]for i in w.upper().split())) # 69 CHARS w='stop yelling man';print(".".join(e[0]for e in w.title().split())) # 69 CHARS w='stop yelling man';print('.'.join(w[0].upper()for w in w.split())) # 69 CHARS a=lambda w:'.'.join(w.title()[0]for w in w.split());print(a("stop yelling man")) # 80 CHARS @quartz wave π
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | S.Y.M
002 | S.Y.M
003 | S.Y.M
004 | S.Y.M
tried to get it as small as possible but couldnt get it less than 69 chars
i will personally congratulate anyone that can get in under 69 chars
w='stop yelling man';print('.'.join(i[0]for i in w.upper().split())) # 69 CHARS
π
cool we tied
same length but cooler
'.'.join(i.upper()for i,*_ in w.split())
# comparing to:
'.'.join(i[0]for i in w.upper().split())
'.'.join(i.upper()for i in __import__('re').findall(r'\b[a-z]',w))
way longer...
2 chars shorter
w='stop yelling man';print('.'.join(filter(str.isupper,w.title())))
Seems optimal
Moar to come soon lmao
!e ```py
w='stop yelling man';print(*filter(str.isupper,w.title()),sep='.')
print(*filter(str.isupper,'stop yelling man'.title()),sep='.')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | S.Y.M
002 | S.Y.M
lowest is 62 chars
Not that hard to make trippy art see the code....then check the library...done this before in JS but they one off art nao a framework for trippy art lmao
he is slowly brainwashing us using this image
into wanting to use python_bmp
r u sure?
oh...
it only works with 2 words strings π
w='stop yelling man'.split();print('.'.join(i[0]for i in w))
is 60
print(*(i[0].upper()for i in'stop yelling man'.split()))
56
the requirement is that it's joined by dots and all the letters in the result are uppercase
@sick hound your code fits neither of those requirements ```py
w='stop yelling man'.split();print('.'.join(i[0]for i in w)) # should be uppercase
s.y.m
print(*(i[0].upper()for i in'stop yelling man'.split())) # should be joined by dots
S Y M
almost
but now i know that print(* exists
thanks
next challenge is to print hello world with no strings and using only in-built libraries π
map chr a list of numbers
lemme try
!e
print(*map(chr, [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]), sep=chr(1).split(chr(1))[0])
@languid hare :white_check_mark: Your eval job has completed with return code 0.
hello, world!
!e py print(''.join(chr(i)for i in [104,101,108,108,111,32,119,111,114,108,100]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world
technically theres a string in mine
!e ```py
import hello
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e print(str().join(str(i)for i in [1,2,3]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
123
str() = '' lmao
overthinking gets the best of us
!e ```py
import hello, inspect
print(inspect.getsource(hello))
@sick hound :x: Your eval job has completed with return code 1.
001 | Hello world!
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | File "/usr/local/lib/python3.10/inspect.py", line 1147, in getsource
005 | lines, lnum = getsourcelines(object)
006 | File "/usr/local/lib/python3.10/inspect.py", line 1129, in getsourcelines
007 | lines, lnum = findsource(object)
008 | File "/usr/local/lib/python3.10/inspect.py", line 940, in findsource
009 | file = getsourcefile(object)
010 | File "/usr/local/lib/python3.10/inspect.py", line 817, in getsourcefile
011 | filename = getfile(object)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/vudidogiji.txt?noredirect
ugh i hate how python is built sometimes
can't do that
__hello__ is a frozen module
but it is frozen some time in the building process
How do i make a like bot on TikTok using proxies Pls help me Ping me
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

!silence
β silenced current channel for 10 minute(s).
if the topic is dead, revive it with relevant discussion, don't just post drivel
!unsilence
β unsilenced current channel.
nobody participates here except for me ryuga and 3 other dudes plus some random guy asking for code help
this place is dead
some guy even posted this before
then report it to moderation team via modmail, my point above still stands
no one forces you to participate and our rules always apply
darko, chilaxan, me, greyblue, jack, olivia, javalim
those are the other guys i remember (which you definitely miscounted)
occasionally me too
Scroll up i post here too
for showing pictures for demonstration of your library yes
are type annotations strs in 3.11 alpha?
yes
π
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hi
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
And me to occasionally
When I am golfing something
I think that this channel is far from being dead
everybody is welcomed in this channel :)
!e
def set_tz(
new_tz: str,
) -> __import__("typing").NamedTuple(
"TimeState", [["tz", str], ["daylight", int], ["timezone", int], ["tzname", str]]
):
from ctypes import POINTER, c_char, c_int, c_long, pythonapi
from os import environ, getenv
from sys import platform
if platform == "win32":
from ctypes import windll
pythonapi = windll.msvcrt
pfx = "_"
else:
pfx = ""
tzset = pythonapi[pfx+"tzset"]
tzset.argtypes = []
tzset.restype = None
from collections import namedtuple
TimeState = namedtuple("TimeState", ["tz", "daylight", "timezone", "tzname"])
get_time_state = lambda: TimeState(
getenv("TZ"),
c_int.in_dll(pythonapi, pfx+"daylight").value,
c_long.in_dll(pythonapi, pfx+"timezone").value,
POINTER(c_char * 3).in_dll(pythonapi, pfx+"tzname").contents.value.decode(),
)
ts0 = get_time_state()
environ["TZ"] = new_tz
tzset()
ts1 = get_time_state()
print("Before tzset:", ts0)
print("After tzset:", ts1)
return ts1
print(set_tz("EST5EDT"))
print(set_tz("UTC"))```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | Before tzset: TimeState(tz=None, daylight=0, timezone=0, tzname='UTC')
002 | After tzset: TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
003 | TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
004 | Before tzset: TimeState(tz='EST5EDT', daylight=1, timezone=18000, tzname='EST')
005 | After tzset: TimeState(tz='UTC', daylight=0, timezone=0, tzname='UTC')
006 | TimeState(tz='UTC', daylight=0, timezone=0, tzname='UTC')
cross-platform tzset function
I needed it because some machines have TZ not set to UTC (grrr)
!e
import os
os.system("pip install requests")
a = requests.get("https://google.com")
print(a.content[:30])
@humble portal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'requests' is not defined
!e
import os
os.system("pip install requests")
import requests
a = requests.get("https://google.com")
print(a.content[:30])
@humble portal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | ModuleNotFoundError: No module named 'requests'
!e Not happening
import os
os.system("python -m pip install requests")
import requests
@sacred umbra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | ModuleNotFoundError: No module named 'requests'
Lol, it was promising tho
They really made sure to make it secure
As far as I know they do have some 3rd party libraries already
!e
import numpy
print(numpy)
@sacred umbra :white_check_mark: Your eval job has completed with return code 0.
<module 'numpy' from '/snekbox/user_base/lib/python3.10/site-packages/numpy/__init__.py'>
Or, what will happen if I use urlib3
Well, try it
the bot doesn't connect to the net to get the request, so nothing will happen
Ohh
you forgot to import ... but snekbox has no internet access
yo
what the hell
at least that'd be the most esoteric thing ever
not sure why but my decompiler remake is heavily typed
like what problems did you face with it
I'm sure a large part of that is the fact that I'm using an ast visitor and branch-processing which makes it even worse
oh branching is easy
you just check if the op is an instance of JumpOp, and then place invisible markers at every place you can jump to
ah, I was using my pyasm project for parsing bytecode
i can't discern whether i use or/and/conditional expressions/if-statements for stuff
>>> from asm import *
>>>
>>> def my_function(x: int = 1) -> int:
... if x > 20:
... return x / 20
... return x
...
>>> deserializer = Deserializer(my_function.__code__)
>>> deserializer.deserialize() # Below is formatted for readability
[
LOAD_FAST(id=124, arg='x'),
LOAD_CONST(id=100, arg=20),
COMPARE_OP(id=107, arg=4),
POP_JUMP_IF_FALSE(id=114, arg=Label(0x7fd2fbeb0d60)),
LOAD_FAST(id=124, arg='x'),
LOAD_CONST(id=100, arg=20),
BINARY_TRUE_DIVIDE(id=27, arg=0),
RETURN_VALUE(id=83, arg=0),
Label(0x7fd2fbeb0d60),
LOAD_FAST(id=124, arg='x'),
RETURN_VALUE(id=83, arg=0)
]```
having these labels available is incredibly nice to have
i can do those blocks just fine but the hard part is figuring out what it actually is
i could always opt for the if statement
step 1: split into blocks
step 2: when finding a block, check for JUMP_ABSOLUTE or similar to detect loops
hmm yeah problem is i'm using 3.11.0a7+ and JUMP_ABSOLUTE is like nowhere to be found
made a lot of it relative
like POP_JUMP_BACKWARD_IF_FALSE
step 3: profit
>>> dis("while a: b = 3")
0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 POP_JUMP_FORWARD_IF_FALSE 6 (to 18)
>> 6 LOAD_CONST 0 (3)
8 STORE_NAME 1 (b)
10 LOAD_NAME 0 (a)
12 POP_JUMP_BACKWARD_IF_TRUE 4 (to 6)
14 LOAD_CONST 1 (None)
16 RETURN_VALUE
>> 18 LOAD_CONST 1 (None)
20 RETURN_VALUE
>>> dis("if a: b = 3")
0 RESUME 0
1 2 LOAD_NAME 0 (a)
4 POP_JUMP_FORWARD_IF_FALSE 4 (to 14)
6 LOAD_CONST 0 (3)
8 STORE_NAME 1 (b)
10 LOAD_CONST 1 (None)
12 RETURN_VALUE
>> 14 LOAD_CONST 1 (None)
16 RETURN_VALUE
``` hmm yeah i think detecting loops are gonna be much harder
ok i think "much harder" is an overestimation
i can just check for bytecode[POP_JUMP_FORWARD_IF_FALSE_destination-1].opcode is RETURN_VALUE
there's a clear difference between "there's code after it" and "there's no code after it" and it's just the above check
from random import choice
print("Press the enter key to generate new ones");p,v="hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split("-"),"tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split("-")
while True:input("You %s, ill have you %s"%(choice(p),choice(v)))
can i get a code golfer in the chat
π₯Ί
true, true
from random import choice
print("Press the enter key to generate new ones")
while True:input("You %s, ill have you %s"%(choice("hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split("-")),choice("tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split("-"))))
i can also replace True with 1
if i do that it only outputs
You neck-ruffian-yob-yobbo-tearaway-malefactor, ill have you and
from random import choice
print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan-hoodlum-rough_neck-ruffian-yob-yobbo-tearaway-malefactor".replace("_"," ").split()),choice("tarred_and_feathered-dismembered-drawn_and_quartered-blemished-crippled-defaced-disfigured-hurt-impaired-marred-soiled-vitiated-battered-contused-gored-lacerated-scalded-scarred-maimed-mangled-mutilated".replace("_"," ").split())))
i need that for the first item in the actions list
wait i dont need that for the first one im dumb
from random import choice
print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split())))β
Also
I think
Nvm
from random import choice;print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".replace("_"," ").split())))
current code
why?
i need it for "tarred_and_feathered" and "drawn_and_quartered"
but then it would split one statement and use them as separate items of the list
from random import choice;print("Press the enter key to generate new ones");while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split())}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split())}")
just use fstring
because drawn_and_quartered is one action but if i used spaces it would process it as
["drawn","and","quartered"]
i meant to put the replace after the split sorry
Ah now it makes sense
also for some reason i cant put the while loop with a semicolon after this part from random import choice;print("Press the enter key to generate new ones");
so my current code is:
from random import choice;print("Press the enter key to generate new ones")
while 1:input("You %s, ill have you %s"%(choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split()),choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split().replace("_"," "))))
anyone know why this says invalid syntax?
from random import choice;print("Press the enter key to generate new ones")
while 1:input(f"You {choice("hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor".split())}, ill have you {choice("tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated".split().replace("_", " "))}")
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split())}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split())}")β
You use "" in wrong places
And you miss some ' '
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan hoodlum rough_neck ruffian yob yobbo tearaway malefactor'.split().replace("_"," "))}, ill have you {choice('tarred_and_feathered dismembered drawn_and_quartered blemished crippled defaced disfigured hurt impaired marred soiled vitiated battered contused gored lacerated scalded scarred maimed mangled mutilated'.split().replace("_"," "))}")
the replace is needed for rough_neck in the first string and the second string needs it for tarred and feathered and drawn and quartered
but it can be shifted to one replace by putting it after the " in the input statement
from random import choice;print("Press the enter key to generate new ones");
while 1:input(f"You {choice('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(","))}, ill have you {choice('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(","))}.")
removed the replace
import choice as c and just use that throughout
thanks
from random import choice as c;print("Press the enter key to generate new ones")
while 1:input(f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(","))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(","))}.")
maybe shortened it
nope doesnt work
bruh it just broke
bruh it says unmatched (
where
you used " in both the fstring and the split
The last " symbol shoud be before . Operator
"."
Hey esoteric people
Hallo
Question for you all, its a bit low level
Hello!
If I wanted to implement a relationship between classes such as between type and object
Such that the object class was built using the type class as its metaclass, but the type class inherited from the object class
Would I have to essentially write my own PyObject and PyTypeObject classes? And if I did so, beyond all the nastiness, would it be possible to simple not inherit the base type and object classes at all (i.e. they are not present in mro, super calls, etc)
>>> class A:
... def A_method(self):
... print(self, 'A_method')
...
>>> class B(A, type):
... pass
...
>>> class C(A, metaclass=B):
... pass
...
>>> super(B, C).A_method()
<class '__main__.C'> A_method
>>> c = C()
>>> c.A_method()
<__main__.C object at 0x10b8904c0> A_method
>>> ``` like this?
why do i do this to myself
!e ```py
def get_sum(a,b): return sum([i for i in range(a, b + 1)] if a < b else [i for i in range(b, a + 1)])
print(get_sum(6, 9))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
30
yay
That's pretty darn close
what is your goal then?
!e
def s(a,b): return sum([i for i in range(a,b+1)] if a<b else[i for i in range(b,a+1)])
print(s(6,9))
!e
def s(a,b):return sum([i for i in range(a,b+1)]if a<b else[i for i in range(b,a+1)])
print(s(6,9))
!e
s=lambda a,b:sum([i for i in range(a,b+1)]if a<b else[i for i in range(b,a+1)])
print(s(6,9))
poggers
@upbeat sonnet
!e
from random import choice as c
hehe=lambda:f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(','))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(','))}."
print(hehe())
!e
from random import choice as c
hehe=lambda:f"You {c('hooligan,hoodlum,rough neck,ruffian,yob,yobbo,tearaway,malefactor'.split(','))}, ill have you {c('fit with concrete galoshes,tarred and feathered,dismembered,drawn and quartered,blemished,crippled,defaced,disfigured,hurt,impaired,marred,soiled,vitiated,battered,contused,gored,lacerated,scalded,scarred,maimed,mangled,mutilated'.split(','))}."
for i in range(10):print(hehe())
ofc the lambda
lambda > def
and whitespace removal
not when pycharm yells at me
π
just use hamming codes to protect against stuff like ripped paper or errors while reading
obv
pc not working rn i think i overheated it
put ice on it
im gonna go make the creator of python cringe in pain
at what i have created
!e
print(sum(range(6, 9 + 1)))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
30
Me: *makes a program*
Ryuga: Heres the same program but in 5 characters
!e py print((s:=lambda a,b:sum(range(a,b+1) if a<b else range(b,a+1)))(6,9))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
30
s=lambda x,y:(y-x+1)*(x+y)//2
i would use this, this is much faster than generating an iterable and getting the sum
lord-
!e py print((s:=lambda x,y:(y-x+1)*(x+y)//2)(6,9))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
30
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
-15
jah jah
bro but it kinda broke there
!e py print((s:=lambda a,b:sum(range(a,b+1) if a<b else range(b,a+1)))(9,6))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
30
ya that only works for ascending order
needs the if condition
s=lambda x,y:(abs(y-x)+1)*(x+y)//2
!e
s=lambda x,y:(abs(y-x)+1)*(x+y)//2
print(s(9,6))
print(s(6,9))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 30
002 | 30
π
abs func fr
!e ```
s=lambda a,b:abs(b+1-a)*(a+b)/2
print(s(6,9))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
30.0
!e
s=lambda a,b:abs(b+1-a)*(a+b)/2
print(s(6,9))
print(s(9,6))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 30.0
002 | 15.0
thats why we need to abs(b-a)
its going to do the same thing as +1
def to_alternating_case(string): return "".join([i.upper() if i.islower() else i.lower()for i in string])```
!d str.swapcase
str.swapcase()```
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that `s.swapcase().swapcase() == s`.
jah jah
why life have to be so sad
and why make a method for something so easy to do
lol
@next flame comparing to this
s=lambda x:''.join(chr(i+32)if i<=97 else chr(i-32)for i in map(ord,x))
ah yes
s=lambda x,y:-~abs(y-x)*(x+y)//2
i^32?
its the same length-
?
oh
got it
s=lambda x:''.join(chr(i^32)for i in map(ord,x))
π
probably needs a check to only casefold alphabetic chars
hmm yea
s=lambda x:''.join(chr(i^32)if 64<i<122else chr(i)for i in map(ord,x))
bitwise xor
oh
def alphabet_position(text): return " ".join([str(ord(i) - 96) for i in text.lower() if i.isalpha()])```
jah
just doing codewars katas then sending my weird 1 liner answers
def number(lines): return [f"{n + 1}: {i}" for n, i in enumerate(lines)]```
s=lambda x:''.join(chr(64<i<122and i^32or i)for i in map(ord,x))
def capitals(word): return [*sorted([n for n, i in enumerate(word) if i.isupper()])]```
i feel like i have a specific programming style
i always feel like im doing the same exact thing
you are
def alphabet_position(text): return " ".join([str(ord(i) - 96) for i in text.lower() if i.isalpha()])
^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named function one arg list comprehension
def number(lines): return [f"{n + 1}: {i}" for n, i in enumerate(lines)]
^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named func ||||| list comprehension
one arg
def capitals(word): return [*sorted([n for n, i in enumerate(word) if i.isupper()])]
^^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
named func |||| list comprehension
one arg
LMFAO
crazy
thats insane
def run_coro(coro, loop):
from asyncio import ensure_future, gather
from threading import Event
from asyncio.exceptions import InvalidStateError
fut = ensure_future(loop.create_task(coro))
g = gather(fut)
sentinel = object()
def getter():
while True:
yield sentinel
try:
yield g.result()
break
except InvalidStateError:
pass
try:
yield g.exception()
break
except InvalidStateError:
pass
return next(filter(lambda o: o is not sentinel, getter()))
imports inside function -- check
two-space indent -- check
what I am trying to do here is "block" on a coroutine (and actually running it) until the result is set @gritty mesa
it appeared to work after some fiddling .. I was surprised
coz I was getting those warnings until I did the yield stuff
Interesting
s=lambda x:''.join(chr(i^32if 64<i<122else i)for i in map(ord,x))
``` removed `)chr(`
@floral meteor 1 byte shorter
what if i = 32?
False and 0 or 32 == False or 32 == 32
!e
s=lambda x:''.join(chr(i^(32*(64<i<122)))for i in map(ord,x))
print("Hello`")
print(ord('`'))
@dark cosmos :white_check_mark: Your eval job has completed with return code 0.
001 | Hello`
002 | 96
uhh
oh nvm i'm dumb
!e
s=lambda x:''.join(chr(i^(32*(64<i<122)))for i in map(ord,x))
print(s("Hello`"))
print(ord('`'))
@dark cosmos :white_check_mark: Your eval job has completed with return code 0.
001 | hELLO@
002 | 96
the ` character is a problem
a problem no longer
s=lambda x:''.join(chr(i^(32*(64<i<122and i!=96)))for i in map(ord,x))
though admittedly it's a bit longer than the previous ones
the previous ones don't account for it either
fair enough
!e py s=str.swapcase print(s("Hello`"))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hELLO`
fair
Esoteric python has so much math
!e py s=lambda x,r=range:x.translate([*r(65),*r(97,123),*r(91,97),*r(65,91)]) print(s("Hello`"))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hELLO`
wondering if there was any side effects if i transform the assignments ```py
a = b = c = d
into ```py
((a := d), (b := a), (c := a))
can't think of any
i never understood str.translate π
usually people make a dictionary {42: 'asterisk', 32: '_'}
it looks up every ord, if there's no such key, it stays untranslated
indexerror is the same class as look up error
looks the same
contrived, but i suppose a getitem/setitem could evaluate differently
specfically on a
!e
from dis import dis
print('= = =')
dis("a = b = c = d")
print(':= := :=')
dis("(a := d), (b := a), (c := a)")
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | = = =
002 | 1 0 LOAD_NAME 0 (d)
003 | 2 DUP_TOP
004 | 4 STORE_NAME 1 (a)
005 | 6 DUP_TOP
006 | 8 STORE_NAME 2 (b)
007 | 10 STORE_NAME 3 (c)
008 | 12 LOAD_CONST 0 (None)
009 | 14 RETURN_VALUE
010 | := := :=
011 | 1 0 LOAD_NAME 0 (d)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tirocuvuli.txt?noredirect
!timeit
a = b = c = d = 10
@wheat river :white_check_mark: Your timeit job has completed with return code 0.
5000000 loops, best of 5: 48.8 nsec per loop
!timeit
((d:=10), (a := d), (b := a), (c := a))
@wheat river :white_check_mark: Your timeit job has completed with return code 0.
2000000 loops, best of 5: 156 nsec per loop
hmm im making a tuple in the second one
!timeit why don't you just do this py (c := (b := (a := (d := 10))))
@rugged sparrow :white_check_mark: Your timeit job has completed with return code 0.
5000000 loops, best of 5: 58.2 nsec per loop
!e ```py
from dis import dis
dis("a = b = c = d = 10")
print()
dis("(c := (b := (a := (d := 10))))")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (10)
002 | 2 DUP_TOP
003 | 4 STORE_NAME 0 (a)
004 | 6 DUP_TOP
005 | 8 STORE_NAME 1 (b)
006 | 10 DUP_TOP
007 | 12 STORE_NAME 2 (c)
008 | 14 STORE_NAME 3 (d)
009 | 16 LOAD_CONST 1 (None)
010 | 18 RETURN_VALUE
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/cagobayaga.txt?noredirect
!e py from dis import dis dis("a = b = c = d = 10") print() dis("d = (c := (b := (a := 10)))")
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (10)
002 | 2 DUP_TOP
003 | 4 STORE_NAME 0 (a)
004 | 6 DUP_TOP
005 | 8 STORE_NAME 1 (b)
006 | 10 DUP_TOP
007 | 12 STORE_NAME 2 (c)
008 | 14 STORE_NAME 3 (d)
009 | 16 LOAD_CONST 1 (None)
010 | 18 RETURN_VALUE
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ibabalahik.txt?noredirect
this generates the same bytecode
that's not how assigning works though, here's a case:```py
a, b = a[b] = {}, 5
I was responding to this one ^
!e ```py
from dis import dis
dis("a,b=a[b]={},5")
print()
dis("a[b]=(a:={},b:=5)")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 BUILD_MAP 0
002 | 2 LOAD_CONST 0 (5)
003 | 4 BUILD_TUPLE 2
004 | 6 DUP_TOP
005 | 8 UNPACK_SEQUENCE 2
006 | 10 STORE_NAME 0 (a)
007 | 12 STORE_NAME 1 (b)
008 | 14 LOAD_NAME 0 (a)
009 | 16 LOAD_NAME 1 (b)
010 | 18 STORE_SUBSCR
011 | 20 LOAD_CONST 1 (None)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jexumamigi.txt?noredirect
ah okay
from dataclasses import dataclass
class Tree():
pass
@dataclass
class Leaf(Tree):
v: int
@dataclass
class Node(Tree):
left: Tree
right: Tree
def lambda_match_wrapper(instance, locals): return type("MatchWrapper", (), {"__getattribute__": (lambda self, __name: type("EqWrapper", (), {"__eq__": (lambda self, __o: eval(__o, None, dict(locals, self=instance)))})() if __name == "_lambda" else instance.__getattribute__(__name))})()
def exists_leaf(tree, test):
match lambda_match_wrapper(tree, locals()):
case Leaf(_lambda="test(self.v)") \
| Node(_lambda=\
"exists_leaf(self.left, test)" \
| "exists_leaf(self.right, test)"):
return True
case _:
return False
def has_even_leaf(tree):
return exists_leaf(tree, lambda n: n % 2 == 0)
print(has_even_leaf(Leaf(0)))
print(has_even_leaf(Node(Leaf(3), Node(Leaf(7), Leaf(6)))))
print(has_even_leaf(Node(Leaf(3), Node(Node(Leaf(5), Leaf(27)), Leaf(3)))))
I wanted to recreate the example on the ocaml homepage (https://ocaml.org/), but in python
so I created a hack to let match cases support lambdas
a cool side-effect is that you can OR together multiple lambda strings with |
noice
I kinda want to have my "lambdas" support named arguments, like _lambda=(("v",), "test(v)")
but I couldn't get that to work
for whatever reason, my __eq__ doesn't get called
update: I'm an idiot
def exists_leaf(tree: Tree, test):
match tree:
case Leaf(v) if test(v) \
| Node(left, right) if
exists_leaf(left, test)
or exists_leaf(right, test):
return True
return False
def better_than_average(class_points, your_points): return sum([*class_points, your_points]) / (len(class_points) + 1) < your_points ```
whats class_points? list?
lambda c,y:sum(c)<y*len(c)
oh wait no this doesn't work, I was running the wrong test file rip
If you used something like forbiddenfruit or fishhook to mess with tuple initialisation, then you might be able to create a side effect
initialisation just needs to detect repeated elements that could match with locals() entries 1 frame out.
that is if you don't want all tuple creations to exhibit these side effects.
otherwise they're the same semantic operation.
replying to this to get documentation on one of my old projects
!e I'm feeling particularly evil, so no more smoke and mirrors using annotations I'm making 2+2=5 ```py
from ctypes import*
c_int.from_address(id(4)+24).value = 5
print( 2 + 2 )
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
i've seen it so much i even think that's regular code
excellent, then the chaos shall reign that much more
yeah, just wanted to make sure it was the same operation
Hey hello, how can i let python interpret my variable in a string like
variable1 = "test1"
variable2 = "hello variable1"
but interpret the variable 1
thank you for your help
variable1 = "test1"
variable2 = f"hello {variable1}"
``` or ```py
variable1 = "test1"
variable2 = "hello {}".format(variable1)
reimplemented ```py
a=lambda:5;a.code = a.code.replace(co_code=b'\x97\0d\1d\1d\1d\1f\4S\0',co_stacksize=3);a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line -1, in <lambda>
SystemError: PUSH() operation resulted in a stack overflow (current stack size 4 is greater than maximum stack size 3) (in opcode LOAD_CONST, in file C:\Users\user\Documents\cpython-main\Python\ceval.c at line 1810)
a=lambda:5;a.code = a.code.replace(co_code=b'\x97\0d\1d\1d\1f\4S\0',co_stacksize=3);a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line -1, in <lambda>
SystemError: POP() operation resulted in a stack underflow (current stack size -1 is less than 0) (in opcode BUILD_TUPLE, in file C:\Users\user\Documents\cpython-main\Python\ceval.c at line 3228)
from fishhook import hook, orig
@hook(str)
def __repr__(self, *args, **kwargs):
string = orig(self)
for word in string.strip("'").split():
if word in globals():
string = string.replace(word, globals()[word])
return string
var1 = "hello World!"
foo = 'var1 :)'
print(repr(foo))
tahnk you very much!
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]```
!e ```py
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]
print(high('i have no friends'))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
friends
π
!e
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]
print(high('i have no frie1nds'))
@wheat river :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 1, in high
004 | IndexError: list index out of range
code
!e ```py
def high(x): return [word for word in x.split(' ') if sum([ord(i) - 96 for i in word.lower() if i.isalpha()]) == max([sum([(ord(i) - 96) for i in word.lower() if i.isalpha()]) for word in x.split(' ')])][0]
print(high('i have no frie1nds'))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
frie1nds
jes
π
take it a step further and make it a lambda function
been sometime since seen u here, welcome
Yeah i disappear for a good while then come back now and again
jah
>>> class A:
... def __add__(self, y):
... self._ = 5
... self.y = y
...
>>> import ctypes
>>> class PyDictValues(ctypes.Structure):
... _fields_ = [('values', ctypes.py_object*2)] # specifically *2 to fit our case
...
>>> a = A();a+7;ctypes.POINTER(PyDictValues).from_address(id(a)-32).contents.values[1] # a.y
7
>>> a = A();a+7;ctypes.POINTER(PyDictValues).from_address(id(a)-32).contents.values[0] # a._
5
``` how to get instance attributes in python
need help in #help-donut
@quartz wave hah, seems a lot better than my +16 in https://blog.raylu.net/2020/06/03/python_hash.html
yeah i'm pretty sure that ctypes code is outdated now in python 3.11 ```py
import ctypes
class Five:
... def init(self):
... self.number = 5
...
five = Five()
pyobject = ctypes.cast(id(five)+16, ctypes.POINTER(ctypes.py_object))
pyobject.contents
py_object(<NULL>)
RIP
a = A();
a + 7;
ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]
Traceback (most recent call last):
File "C:\Users\ryuga\AppData\Roaming\Python\Python310\site-packages\IPython\core\interactiveshell.py", line 3251, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-a493d47e36e2>", line 3, in <module>
ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]
ValueError: PyObject is NULL
a = A();
a + 7;
ctypes.POINTER(PyDictValues).from_address(id(a) - 32).contents.values[1]
Process finished with exit code -1073741819 (0xC0000005)
huh?
you're on 3.10
@rose beacon's trick still works on 3.10 so you can maybe test that out
ah thats why
aight, thanks
wouldnt this only work if the dict keys/values for the instance were allocated directly before the actual instance mem? (is that guaranteed?)
idk
only works for Py_TPFLAGS_MANAGED_DICT stuff though
How do i learn how to do esoteric python
Like how the fuck does this even work
in 64-bit systems, int.__basicsize__ is 24
id(integer)+24 will point to the first number in an integer's internal list of numbers
c_int.from_address(id(integer)+24) is basically getting the first number and making it a c_int object
then it's assigned to using .value = 5
all positive integers up to 256 (end-inclusive) are required to be cached
so anywhere, 4 is now equal to 5
and you can't change it back
so it sucks
Wtf
So every number's size is 24?
So 24+24+24 will add up to 3?
no
π
int.__basicsize__ just means the "header" of the integer structure
Why do people like doing esoteric python what the fuck
interesting stuff
I still don't get it
π
basically it's like this ```py
reference count: int
type of object: type
size of object: int
size of those stuff add up to 24
Okay
they're not like that though i just used python to show a "basically"
Why do you add 24 to the id of 4
!e `print('ggg')
so we get the "list" of the numbers used to make a python integer
it's impossible to make a number that can go very big without using a "list"
The more you explain this to me the more my confidence in python plummets
you shouldn't really know this if you're just a beginner
I don't think i'm a beginner
I hope so
the first element in the "list" is the equivalent of the actual integer itself if it's small enough
so we change that to 5
and the 4 becomes 5
Yeah i get that 4 becomes 5 i'm confused about the "list"
i just say it's a "list" instead of an array of C unsigned ints
because i'm not sure if you know what that means yet
I do not
!e import os
os.system('calc.exe')
@rigid bone :warning: Your eval job has completed with return code 0.
[No output]
Is this the list of numbers
!e import os
while True:
os.system('calc.exe')
@rigid bone :warning: Your eval job timed out or ran out of memory.
[No output]
!e ```py
print(id(4))
@granite flax :white_check_mark: Your eval job has completed with return code 0.
139839520358736
import os
while True:
os.system('calc.exe')
!e import os
while True:
os.system('calc.exe')
@rigid bone :warning: Your eval job timed out or ran out of memory.
[No output]
!e import os
while True:
os.system('calc.exe')
@rigid bone :warning: Your eval job timed out or ran out of memory.
[No output]
wdym by "this"
This
no that's the place of the object in memory
Where did you learn this
real "list" is more like [4]
except you can't see it like that
unless you use a function i made
What function
i explored the insides of python
!e import os
n = 1
while n > 0:
os.system('calc.exe')
n += 1
print(n)
@rigid bone :x: Your eval job timed out or ran out of memory.
001 | 2
002 | 3
003 | 4
004 | 5
005 | 6
006 | 7
007 | 8
008 | 9
009 | 10
010 | 11
011 | 12
... (truncated - too many lines)
Full output: too long to upload
stop testing here go to #bot-commands
I may need to use the function to understand whatever this is
Why will it point to the first number in the list
there's no "why", it's just how the object is stored in memory
Damn this is so confusing
under the hood, a python integer is a C struct instance
if you read the C source you'll find what the members of the struct are
these members are stored one after the other in memory
the first few members are stuff like the refcount, a pointer to the type, etc
and then comes the actual data of the number
id(4) gives you the address where the struct begins
by adding 24 to the address you skip past the initial members and come to the address where the number begins
This slightly made me understand it more i think
Thanks
How about the thing in pins
This thing
when you add what is love evaluates to True
we want to change the type of True to be NoMore, instead of bool
remember that all objects store a pointer to their type
id(True) is the id of True, id(True) + 8 is the address of the pointer, and we change this value to point to our NoMore class
so when it tries to print True, it looks up __str__ on the NoMore class
which returns whatever you want it to
Why do we add 8
to skip past the first member(s) that we do not care about and to get to the address of the member that is the type pointer
Why specifically 8 though
the members before the type pointer take up the first 8 bytes
Do you guys just memorize this
Any video or website i can check to understand this stuff
I really want to understand what the hell is happening
But can't
i would say learning little bit of c should help u understand this stuff, although c is a very large lang so it might take a long time
I just want to be esoteric
π
i mean, being esoteric isn't just about messing with the internals of python
But i think it's cool and i want to do it
Can't do it without understanding what it does or how it does it
google i guess?
Google what
i mean- i don't even understand python internals so i can't really help you here :/
hi i want to learn #esoteric-python
What exactly?
so you want to learn golfing
uh whats that?
im talking about these kind of stuff too
so you want to learn golfing
hello and welcome
π
golfing means writing the shortest possible code (pretty much)
okay
we overlook stuff like performance/readability basically all the things that guarantee a job at a company π
..
!e ```py
def diamond(n): return '\n'.join(['*' * (i + 1) for i in list(range(n)) + list(reversed(range(n - 2)))]) if n > 0 and n % 2 == 1 else None
print(diamond(5))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
001 | *
002 | **
003 | ***
004 | ****
005 | *****
006 | ***
007 | **
008 | *
wait does python store 24 bits + memory to store the datatype?
for integers, yes
!e ```py
print(int.basicsize) # refcount: uint8, type: uint8 pointer, size: uint8, data: uint8[]
print(str.basicsize) # a lot more stuff
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 24
002 | 80
(bytes btw, not bits)
I did not pick that up lol
π
π
is_prime=lambda num:1<num<4or num>3and num%2and num%3and(all(num%i and num%(i+2) for i in range(5,int(num**.5)+1,6)))
credits : xelf#7577
!e
import re
def is_prime(n: int) -> bool:
return re.match(r'^.?$|^(..+?)\1+$', ' ' * n) is None
assert not is_prime(0)
assert not is_prime(1)
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(6)
assert is_prime(7)
assert not is_prime(8)
assert not is_prime(9)
assert not is_prime(10)
assert is_prime(11)
print('ok!')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
ok!
ping
Cute!
People told me to put this here so ..
def Ack(m, n):
if m==0: return n+1
if m>0 and n==0: return Ack(m-1, 1)
if m>0 and n>0: return Ack(m-1, Ack(m, n-1))
v0 = 69420
for i in range(69420):
v0 = v0 ** v0
for i in range(1, 69421):
globals()[f"v{i}"] = Ack(globals()[f"v{i-1}"] ** globals()[f"v{i-1}"], globals()[f"v{i-1}"] ** globals()[f"v{i-1}"])
while True:
input()
v69420 = v69420 - 1
print(v69420)
if v69420 == 0:
print('gg')
exit()β
uh oh i see Ackermann's function
It's mostly used as part of code test suites
Not sure where the python help channel is so here I am. That's what happens when your server has a billion channels and most with weird names.
Makes no sense.
this channel makes no sense
Most of the channels make no sense.
I've been here before and no one has ever helped. Smaller servers are more useful.
this channel makes less sense
This server is very helpful you just can't find your way
just claim a help channel and wait there
Hard to find your way in this mess.
How do I do that? # the channel.
just post your error in one of the available help channels
I can't type there. How would I post my error there?
and don't leave that channel or just memorize the name
Give me a # to post my error in.
you don't type there
Duh.
you read the instructions
Did. Make no sense.
Thanks for being "helpful" in the end.
πΏ

hello ryuga
wait wha- how does this work
Hi
regex which im not smart enough to understand
is there a practical use to xor
he was being very respectful and helpful bro how old are you πΏ
i would not have the patience
if you match nothing, it's not a prime
if you match one character, it's not a prime
if you match a number of characters that are divisible by anything other than itself and 1, it's not a prime
i do
how ^(..+?)\1+$ works is that you take this capture group ((..+?)) that matches ONLY when needed
(..+?) basically matches any character then matches anything else only when needed (but it is required)
\1+ repeats the capture group match until it can't
if $ doesn't match, the regex thing tries again with more numbers of characters to match with the capture group because the capture group matches only when needed
then \1+ is tried again
and so on
@fleet bridge i somehow figured this out
regex sometimes looks like random keys smashed
there has to be a lot of backtracking here (and also string multiplication) which kinda sucks in performance and memory
"make no sense" π€£
There are some websites that could help you understand how it works
regex101.com for example
Or regexr.com
Yeah i know but as of right now i'm trying to understand ctypes ;-;
it's like C:
everything is just raw memory
ah
"mosquito speaker" ?
probably something that plays super high frequency sound
kind of annoying to hear
something like https://www.youtube.com/watch?v=djzfofmhe1s
YouTube's stupid compression takes out anything above 16 kHz, so if you are hearing nothing at all, change the video quality to 720p.
===PLEASE READ DESCRIPTION===
Welcome, welcome, welcome to the home of the most comprehensive collection of beeps, rumbles, chirps and noise on teh Internets!
Although this channel has very many sine wave frequ...
oh
i mean that's what i think is the sound based on the experience that they thought they had tinnitus
real
boutta say ooga booga bro πΏ
@bot.command()
async def coro():
...
How do I convert this to a one liner?
coro = bot.command(lambda: ...)
pylance doesnt like my expression
can't imagine why
looks perfectly fine to me
i maybe "found" a new tech for removing characters in strings golfed
nevermind its slightly larger in most cases unless you have to do it for a lot of characters (like me)
its using "string".translate({(UNICODE FOR A CHARACTER):None})
shortened my string obfuscator by a bunch though
maybe like 20 some characters
from random import choices as z
import string as s
a=s.ascii_letters+s.digits+s.punctuation+" "
a,s,n,o=list(a.translate({92:None,39:None,34:None})),input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(s)):o+=s[i]+"".join(z(a,k=n))
print("'%s'[::%i]"%(o,n+1))
i gtg
When the order doesn't matter, like in this case, you can just subtract sets:
from random import choices as z
import string as s
a=s.ascii_letters+s.digits+s.punctuation+" "
a,s,n,o=[*set(a)-{*"'\"\\"}],input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(s)):o+=s[i]+"".join(z(a,k=n))
print("'%s'[::%i]"%(o,n+1))
NICEEEE
Golfed a little bit further:
from string import*
s,n,o=input("String to obfuscate: "),int(input("Split number: ")),""
for i in range(len(s)):o+=s[i]+"".join(__import__("random").choices([*set(ascii_letters+digits+punctuation+" ")-{*"'\"\\"}],k=n))
print("'%s'[::%i]"%(o,n+1))
Oh, you save lots by not writing C :P
from string import*
s,n,o=input("String to obfuscate: "),int(input("Split number: ")),""
for i in s:o+=i+"".join(__import__("random").choices([*set(ascii_letters+digits+punctuation+" ")-{*"'\"\\"}],k=n))
print("'%s'[::%i]"%(o,n+1))
No need to do the random import inline
Crazy, making it more idiomatic actually shrinks the size for once
Yeah, I guess you're right..
golfed list cloning function i made in like 3 minutes
c = lambda l : [i if type(i)!=type([]) else c(i) for i in l]
i dont even know why i did this python already has a method for cloning lists
Actually, it looks like not inlining it makes it 5 chars bigger. Am I missing something?
It's one char shorter
WAIT i can golf it further
c=lambda l:[i if type(i)!=type([])else c(i)for i in l]
(i removed spaces!)
c=lambda l:[i*(type(i)!=list)or c(i)for i in l]
π
OH that thing with the * symbol i. Get it now its like
because its * in the duplicating item stuff way and. the
Doesn't work with custom objects
so like if you do print("string"*True) then True is 1 so itll print "string" once and if its false itll print it 0 times and. The empty string/list is false so itll
wow why am i only just figuring this out
!e
L = [..., 23, 42]
c=lambda l:[i if type(i)!=type([])else c(i)for i in l]
print(c(L))
c=lambda l:[i*(type(i)!=list)or c(i)for i in l]
print(c(L))
@restive void :x: Your eval job has completed with return code 1.
001 | [Ellipsis, 23, 42]
002 | Traceback (most recent call last):
003 | File "<string>", line 6, in <module>
004 | File "<string>", line 5, in <lambda>
005 | File "<string>", line 5, in <listcomp>
006 | TypeError: unsupported operand type(s) for *: 'ellipsis' and 'bool'
Yes :)
Now put something that's neither a number nor a sequence in it

the boys cooking up new methods of golf
python code golfing has truly advanced
it is kinda sad though that we cant mix whitespace and tabs anymore
c=lambda l:[type(i)!=list and i or c(i)for i in l]
should fix it
!e ```py
m = getpass.getpass(prompt='hi')
print(m)
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'getpass' is not defined
[*set(__import__('string').printable)-{*"'\"\\\r\n\n"}]
can also use this
things out of context
π
[*{*__import__('string').printable}-{*"'\"\\\r\n"}]
!e ```py
print(f"{5:=}", f"{5:>}")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
5 5
yeah := centers it while :> right aligns it
!e ```py
print(f"a{5:=7}a")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
a 5a
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | a
ah nvm i assumed it was = that centered
^ is
ah yeah thats right i was right about > tho
c=lambda l:[eval(str(i)[:])for i in l]
we dont even need the [:] if we are going to type cast it
c=lambda l:[eval(str(i))for i in l]
why the eval?
im dumb we can just do eval(str(l))
im type casting to str i want the original type of the obj back
ah
g'day, esoteric python people
this is probably the right place to put it since my program as a whole is esoteric
class Foo:
def call_on_subclass_creation(self,*subclass_stuff):
print(subclass_stuff)
class Bar(Foo):0
how could I achieve something along these lines?
I could use metaclasses
yeah, build_class isn't actually properly documented
I fiddled with it a few months back
the reference implementation doesn't work
see this
but most importantly, this
__init_subclass__?
don't think that works?
did you try it yet
what do you want the output to be
Is it bad that I'm using python instead of photoshop/mspaint?
str(l) will include the list brackets and commas, that might not work depending on what you want
It'll evaluate the list, not just its elements.
they are going to have diff ids, tho, the goal i belive is to create a copy of the list but [:] doesn't create a copy of a potential sub list
Why not just list.copy()?
It's not worse than MS Paint, that's for sure
guys
what does var1 = var2 = var3 mean
like
!e py var1 = var2 = True print(var1, '\n', var2)
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
oh
ctypes easter egg
!e py import ctypes useless_pointer = ctypes.POINTER(ctypes.c_void_p) ctypes.SetPointerType(ctypes.POINTER(ctypes.c_int), useless_pointer)
@tribal moon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "/usr/local/lib/python3.10/ctypes/__init__.py", line 307, in SetPointerType
004 | raise RuntimeError("What's this???")
005 | RuntimeError: What's this???
!e ```py
import ctypes
ctypes.SetPointerType(3, 6)
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.10/ctypes/__init__.py", line 307, in SetPointerType
004 | raise RuntimeError("What's this???")
005 | RuntimeError: What's this???
π
its serious when the devs had to write a message saying What's this with 3 question marks
@ctypes_devs why?
getattr((bot:=getattr(__import__("importlib").import_module("discord.ext.commands"),'Bot')(command_prefix='^',intents=getattr(__import__('discord'),'Intents').all())), 'command')(name='quack')(lambda ctx:(await ctx.send('quack')for _ in '_').__anext__())
so i made this which is equivalent to
from discord.ext import commands
import discord
bot = commands.Bot(prefix'^', intents=discord.Intents.all())
@bot.command(name='quack')
async def _quack(ctx):
await ctx.send('quack')
but the thing is in commands.command's init there is this check
if not asyncio.iscoroutinefunction(func):
raise TypeError('Callback must be a coroutine.')
how do i bypass that?
replace py lambda ctx:(await ctx.send('quack')for _ in '_').__anext__() with ```py
import('asyncio').coroutine(lambda ctx:(await ctx.send('quack')for _ in '_').anext())
it's deprecated though
And their IDs are the same, too, I think
oof
ay tyvm
isn't manually using __anext__() a generator based coro?
ic ic
I'm using python scripts to mass produce desktop backgrounds.
I have a python script to print matrix rain, which I screenshot and save to an assets folder, then run a script which uses it to generate a desktop background using several other existing assets.
here is a guessing game on one line
(lambda x, holder1=0: [(lambda guess: (lambda: print('Too high!') if guess > x else (lambda: print('Too low!') if guess < x else (holder1:=1, print('Correct!'), __import__('sys').exit()))())()if i!=10 else (lambda: (holder1:=1) if holder1==1 else print(f'Sorry, the correct answer was {x}.'))())(int(input('Guess a number!: '))) if holder1!=1 else holder1 for i in range(1, 11)])(__import__('random').randint(1, 101))```
.bm
gotta overwrite the file it's in now
.bm
π¨
My mental state has deteriorated sufficiently to return to this channel
class ModuleUtils:
hooks={}
modules={}
class Hook:
def __init__(self,hookf):
self.hookf=hookf
class OnMessageHook(Hook):
pass
class OnReadyHook(Hook):
pass
class OnTypingHook(Hook):
pass
def load_optional_modules(*modules):
output('Loading optional modules\n')
for module in modules:
ModuleUtils.modules[module.__name__]=module
output(f' Loading {module.__name__}\n')
if hasattr(module,'service'):
output(f' Spawning service\n')
module.service.start()
output(f' Spawned service\n')
@lambda c:c(module)
class service_respawner:
def __init__(self,module):
self.module=module
self.respawner.start()
@tasks.loop(seconds=5)
async def respawner(self):
if not self.module.service.is_running():
self.module.service.start()
print(f'restarted {self.module.__name__} service at {datetime.datetime.today().strftime("%d/%m/%Y, %H:%M:%S")}')
output(f' Spawned respawner\n')
for attr in dir(module):
if issubclass(type(getattr(module,attr)),ModuleUtils.Hook):
output(f' Hooked method {getattr(module,attr).hookf.__name__} to event {type(getattr(module,attr)).__name__}\n')
if type(getattr(module,attr)) in ModuleUtils.hooks:
ModuleUtils.hooks[type(getattr(module,attr))].append(getattr(module,attr).hookf)
else:
ModuleUtils.hooks[type(getattr(module,attr))]=[getattr(module,attr).hookf]
output('\n')
handle_hooks=lambda event,*arguments:[hook(*arguments)for hook in ModuleUtils.hooks[event]]if event in ModuleUtils.hooks else[]

Almost 7000 lines of eso code what happens if you put in docstrings to most of one liner functions seen here ...not yet done https://github.com/TechnoTanuki/Python_BMP/blob/main/Python_BMP/BITMAPlib.py
oh-
Errors after 10 guesses
Yeah
and i love how the mods didn't put a cooldown for this channel
we'd probably just end up making webhooks or something
π first time?
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 1, in <module>
File "<string>", line 1, in <lambda>
File "<string>", line 1, in <listcomp>
File "<string>", line 1, in <lambda>
File "<string>", line 1, in <lambda>
UnboundLocalError: local variable 'holder1' referenced before assignment
nope, relapse
huh
lemme see
See what
see the error myself
rip
improves my code
leads to abominations like this
here ya go py (lambda x: [(lambda guess: (lambda: print('Too high!') if guess > x else (lambda: print('Too low!') if guess < x else (print('Correct!'), __import__('sys').exit()))())()if i!=10 else print(f'Sorry, the correct answer was {x}.'))(int(input('Guess a number!: '))) for i in range(1, 11)])(__import__('random').randint(1, 101))
fixed
its actually pretty quiet most of the time
more for us :p
mhm, ya know there are only a few mentally unstable people in this server, enough to post here.
this channel attracts a specific kind of person
the newbs occasionally popping in here to ask for help don't know what hits them
lol
kinda weird how often that happens
they seem to pick this channel more often than most
#bot-commands
just as I was saying
my bad
@unreal echo :white_check_mark: Your eval job has completed with return code 0.
104 101 108 108 111
I find this place leaks into my code even when I try to keep it out
!e print(*'hello'.encode())
@vestal solstice :white_check_mark: Your eval job has completed with return code 0.
104 101 108 108 111
#bot-commands
u can just do map(ord, word)
yeah
i sure hope i just remember what this channel is and just scare the hell out of them
I just found multiprocessing in python and core affinity in task manager.
now I can use all of my cpu to torture python
How do you guys have the patience to learn this stuff haha
Do you mind explaining this a tiny bit? I have no clue how this works but is it like setting the address to the value True to the value baby don't hurt me?
You're gonna get so confused
Really fucks your brain
the type of the object is stored (or was stored in the version I did it in) at an offset of 8 from its start, then it just replaces the bool type with the NoMore type so when it searches for the str method it finds the custom one instead of bool's
So said you just printed out True that that print it out too?
Yes, it went to print out True, but because True's type was changed to NoMore, it called the str method from there to get its string
Ahh alright thank you, I believe it makes sense now!
you just found multiprocessing???
improved ```py
from ctypes import py_object
class NoMore:
... def repr(self):
... return "baby don't hurt me"
...
py_object.from_address(id(True)+tuple.itemsize).value = NoMore
what = love = object()
what is love
baby don't hurt me
probably works in 32-bit systems now
!e double improved ```py
import('ctypes').py_object.from_address(id(True)+tuple.itemsize).value=what=love=globals()[print(what is love)]=type('',(int,),{'new':lambda _:super().new(1),'str':lambda _:"baby don't hurt me"})
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
baby don't hurt me
me when i relapse into python coding normally with readable code (bad): π’
my when i make an abomination of unreadable code to save 21 characters: 
I don't understand why people are like this, but I love it
Hey @magic wraith!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
it works but it messes up idle https://paste.pythondiscord.com/siyefupuno
yeah the IDLE probably needs True
>>> from ctypes import py_object
>>> class NoMore(int):
... def __new__(cls):
... return super().__new__(1)
... def __repr__(self):
... return "baby don't hurt me"
...
...
>>> py_object.from_address(id(True)+tuple.__itemsize__).value = NoMore
>>> what = love = object()
>>> what is love
baby don't hurt me
fixed
!e import pickle; print(pickle.loads(b'\x80\x04\x95,\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x07getattr\x94\x93\x94J,\x0f\x01\x00\x8c\x08__hash__\x94\x86\x94R\x94.')())
@split salmon :white_check_mark: Your eval job has completed with return code 0.
69420
Why does type.__call__ when used as a class decorator create a new instance of that class?
a class is an object of type type
when the calling syntax is done, it does type.__call__(ClassExample) which is basically the same thing as ClassExample.__new__()
mhm
I got that far
Well, why is ClassExample.__new__ the same as type.__call__(ClassExample)? What's going on in there?
gonna have to search the internals for that
@golden finch it searches for __new__, errors if it can't find it, else calls it, returns the object if it isn't an instance of the class, else searches for __init__ and calls it if it finds it
good lord
and then returns the __init__ed object?
yes
roughly equivalent to this (only including the highlighted code) ```py
def type_call(cls, *args, **kwargs):
if cls.new is None:
raise TypeError(f"cannot create '{cls.name}' instances")
obj = cls.new(*args, **kwargs)
if not isinstance(obj, cls):
return obj
if cls.init is not None:
cls.init(obj, *args, **kwargs)
return obj
Is it possible for us to change the objects in our favor? example: making a new bool (useless, but it's my only idea in mind).
yes
class newBool(bool):
# your extra features here
but
but
i reccomend using dunder methods instead
unless you just want to add a few things
I'm gonna max out all 16 processors and take my laptop in bed with me to keep me warm at night
ok
Very esoteric use for python, right?
You can't subclass bool though
i mean yeah
just don't win a darwin award
damn TIL you can't subclass bool
makes sense though
Where is that check performed?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'bool' is not an acceptable base type
Ah
yep
Ig the only part you inherit would be a __bool__
Goddamn thag was hard to do on mobile
yeah
LMAO all the backslashes
imagine though ```py
class true(bool):
def bool(self):
return False
print(true() is True) # this line is kinda cursed
https://github.com/python/cpython/blob/main/Objects/boolobject.c#L99-L104
found this but dont see the check :/
Objects/boolobject.c lines 99 to 104
PyDoc_STRVAR(bool_doc,
"bool(x) -> bool\n\
\n\
Returns True when the argument x is true, False otherwise.\n\
The builtins True and False are the only two instances of the class bool.\n\
The class bool is a subclass of the class int, and cannot be subclassed.");```
Isn't this false even if bool returns true?
If bool returned True when instantiated it would be true since they are singletons
"singletons"
bool is a doubleton xD
instantiating a bool is cursed
I mean, it is as cursed as instantiating int I guess
fair enough
!e
@lambda _: _()
class true:
def __new__(self):
return False
print(true is False)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
True
damn i did not need to know that it was possible
!e
from ctypes import py_object
@lambda _: _()
class true:
def __new__(self):
return False
class trueOrIsIt:
def __repr__(self):
return 'true'
py_object.from_address(id(True)+tuple.__itemsize__).value = trueOrIsIt
print(true is False)
i saw this in this channel the other day
@wheat river :white_check_mark: Your eval job has completed with return code 0.
true
Objects/typeobject.c lines 2201 to 2205
if (!_PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
PyErr_Format(PyExc_TypeError,
"type '%.100s' is not an acceptable base type",
base_i->tp_name);
return NULL;```
Also donβt forget bool is a number :P
mining crypto using a calculator api powered by python
tuple.__itemsize__ is Py_ssize_t?
tuple.__itemsize__ is the size of a pointer = size of a Py_ssize_t

