#esoteric-python
1 messages ยท Page 89 of 1
Ah yeah, since it's only needed in one place now
aren't z and i always the same thing?
Hmm, they could be the same thing
Yeah, they are unrelated but can be the same with no problem^^
z used to be the iteration depth
x=y=0;i=50;q=print
while y<i:
c=p=0;x=-~x%i
if x==1:q();y+=1
while p<i and abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)<2:p+=1
q(" #"[p==i],end=' ')
141 chars now
You don't need to assign to o. It's only used once.
Oh, maybe you do.
For sequencing, that is.
seems to work fine
True, o is never changed therefore the assignment is unnecessary
if will sometimes get different y value though
Could you do something like while abs(c:=c*c+o)<2:p+=p<i? Or might that loop forever?
Can o be 0?
And you still don't need indents that big.
One space is sufficient.
Yeah, my editor forces me to write them
If o can be zero, you could do while(abs(c:=c*c+o)<2)*o:p+=p<i so it doesn't get stuck in a loop.
Wait, no, that's different logic.
Oh, right, o is gone.
is it possible for p to end up being bigger than i?
Yes
Not with the current loop condition?
Well, no
There needs to be some mechanism in place, so that the loop doesn't loop forever, and p does that.
"# "[p<i] is one character shorter than " #"[p==i]
if you flip around both the string and the p<i/p==i then it won't be inverted
Do you need to call complex(a,b)? Can't you do a+b*1j?
Oh, brackets around b.
Still shorter, I believe.
abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)
abs(c:=c*c+(y/i-.8+(x/i-.5)*1j)*2.2)```
2 characters shorter
Works
possibly better if someone figures out how to get rid of some of those brackets
Is this notation a shorthand for complex numbers in Python?
>>> complex(0,1)
1j
>>> 1j
1j```
Ahh okay
abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)
abs(c:=c*c+(y/i-.8+(x/i-.5)*1j)*2.2)
abs(c:=c*c+(y/i-.8+x/i*1j-.5j)*2.2)```
good spot
that should work
i think
and abs(...)<2 -> and-2<(...)<2
that abs is of a complex number
Oh, curse my assumptions.
Excuse the vulgarity of the source, I'm working with a library called "fuckitpy"
https://hastebin.com/guloxanoge.py
I'm trying to implement a custom codec, and I'm having trouble with what I think is the incremental decoder. The final parameter should be true on the very last call to the incremental decoder's decode method, however it seems to be stuck in a loop calling this method with the final parameter set to true with no data being passed. The codec registers and all the source of the file being run is passed to the decode function, but once it reaches the end of the file it passes nothing forever.
Anyone have any idea how I can sort this out?
This is the example I'm working with https://github.com/aroberge/ideas/blob/master/ideas/encoding.py
Easy creation of custom import hooks to experiment on alternatives to Python's syntax; see https://aroberge.github.io/ideas/docs/html/ - aroberge/ideas
Is it the https://github.com/ajalt/fuckitpy ?
x=y=0;i=50;q=print while y<i: c=p=0;x=-~x%i if x==1:q();y+=1 while p<i and abs(c:=c*c+complex(y/i-.8,x/i-.5)*2.2)<2:p+=1 q(" #"[p==i],end=' ')141 chars now
@sick hound what the fuck
@sick hound this is the esoteric python channel, what did you expect? lol
I made the fake windows blue screen more realistic
it makes the cursor invisible as well as restarts the computer
Could you also make it work for Linux? :D
Is this shorter? It has slightly different behaviour because it doesn't print a trailing space before newlines.python x=y=0;i=50 while y<i: c=p=0;x=-~x%i;v=x==1;y+=v while p<i and abs(c:=c*c+(y/i-.8+x/i*1j-.5j)*2.2)<2:p+=1 print(" #"[p==i],end=' \n'[v])
Looks about 6 shorter.
If you want the trailing spaces, though, you can add two characters: end=' \n'[v] -> end=' '+'\n'*v
I can make it work for linux
but I've never used Linux before
so I need to know how it looks like when it has an error
What does a Linux version of a BSoD look like?
Try these. https://askubuntu.com/questions/561224/what-is-the-equivalent-of-blue-screen-of-death-in-linux
Yeah
I don't know if anyone knows this, but what is the font in the error terminal thing
wow.
Thanks
Well I think I can do it
But I don't think I have the time for it
maybe I can do it
just not in one line
and I also can't disguise it as something else
I could if I wanted too
Idea: A program that converts python code to much uglier versions
if True:
print(3)
to
while True:
print(3)
break
and works in multiple steps
so you can convert it to one form, then do it again until it's maximum ugly
It would be horrible to use, but fun to do lmao
i think it should conver to this instead py for _ in range(True): print(3) continue
print(end = '3\n')
sys.stdout.write('3\n')
sys.stdout.write("".join([chr(n) for n in [13, 51]]))
Oh nice one
I am deeply confused
That's the point :D
What's the difference?
!e
import sys
sys.stdout.write("".join([chr(n) for n in [13, 52]]))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | 4
Hmm
?!??!?!?!?
is python effecient in small(est sometimes?) bytes for any particular program?
what the steaming fuck
Different encoding perhaps?
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
same
!e
print(ord('4'), ord('2'))
@thin trout :white_check_mark: Your eval job has completed with return code 0.
52 50
like you know jelly, it takes very less space to execute something
sso how good is python in those cases
what about me
sys.stdout.write("".join([chr(n) for n in [int(i, base=2) for i in [1101, 110100]]]))```you can throw some binary in there too
You could do a PyVM eso language lol
Syntax error
I'm missing a ]
why am i asking here........ how do I install jelly?
I've been working a bit on a stack-based language, now I'm writing a VM in C for it, and it's still gonna have a Python frontend (bytecode compiler, maybe REPL)
If you are going this way, I'd really recommend you to read "the dragon book", it is a book about compiler techniques and stuff, the original python parser (< 3.8) follow this exact implementation
It is really technical, but it is great
@grizzled folio you should take a look at #โ๏ฝhow-to-get-help, this isn't an help channel :D
i wasn't able to find his mention lol
Thanks @thin trout , I'll check it out
@gaunt panther ```
$ git clone -q https://github.com/DennisMitchell/jellylanguage.git
$ cd jellylanguage
$ pip3 install --upgrade --user .
wai wha? jelly is writtin in python?
but how will i type in jelly
I don't actually know how people do that heh
I mean you can copy paste by character
yeah, if only I can i can understand jelly, bye, imma take its tutorial
I guess this is a 'code golf'-ish question.
Is it possible to go from:
a = some_fun(x)
b = some_fun(y)
to
a, b = some_fun(x,y)
``` in some way?
a, b = map(some_fun, [x, y])
Perfect, I forgot about that, thanks.
a, b = map(some_fun, (x, y))``` don't waste memory ๐
!e
import sys sys.stdout.write("".join([chr(n) for n in [13, 52]]))
@formal sandal excuse me why does that not work
@marsh void :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | 4
h u h
that should be 52, 13 but yea
ah
!e python import sys sys.stdout.write("".join(map(chr, (52, 13))))
@marsh void :white_check_mark: Your eval job has completed with return code 0.
4
hm
!e print(chr(52))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
4
some control character magic?
!e print(chr(0x52))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
R
thats.. supposed to say 3
i think it should conver to this instead
py for _ in range(True): print(3) continue
@vague hearth
!eval
import sys
sys.stdout.write("".join([chr(n) for n in [51, 13]]))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
3
writing to stdin?

oh
that took some time
but I just managed to figure out what was happening
so chr(13) is the \r character, and sys.stdout.write returns the amount of chars written
which is why in the terminal/shell you see the 4-2; the 4 is from chr(51) while 2 is from the sys.stdout.write call
import sys;sys.stdin.write("".join(map(chr,(51,13))))```
why use semicolons?
cuz minified
do it in one line without semicolons
use import
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<module 'sys' (built-in)>
OH
__import__('sys').stdin.write("".join(map(chr,(51,13))))```
well I'm not the one who wrote it
when I do this kind of stuff
I usually prefer to put it in lambda functions
so instead of py __import__('sys').stdout.write("".join(map(chr,(51,13))))
I do py (lambda sys: sys.stdout.write("".join(map(chr,(51,13)))))(__import__('sys'))
asdsd
OH OOPS
!e
(lambda ch: list(filter(lambda x: x[0] == ch(str(7772697465)),(lambda y: y.__dict__[ch("6765746d656d62657273")]((lambda x: x.__dict__[ch("7374646f7574")])(__import__(ch(str(737973))))))(__import__(ch("696e7370656374")))))[0][1](ch("68656c6c6f20776f726c642121")))(lambda s: "".join(map(lambda a: chr(int(a, 16)), [s[i * 2:(i + 1) * 2] for i in range((len(s) + 1) // 2)])))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world!!
:D
haha nice
There was a time when I thought hello world was the simplest program in any programming language, it was supposed to be what you started with.
No longer. I am now a changed man, my eyes have been opened.
goes to find bleach
how do I get started on this hell
oh im not done yet
i just discovered you can use builtins with lambdas
!e
a = "123"
print(list((lambda x: x(int, a))(map)))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
and i figured, since i use inspect.getmembers in the code to get write(), why not get __dict__ too
how do I get started on this hell
@limpid crest
basically did
list(filter(lambda x: x == "write", inspect.getmembers(sys.stdout)))[0][1]("hello world!!")
?
you asked how to get started, i assumed you meant reading it
ohhh, you want to make hellish code?
I wanna get started
And idk where to go
I'm an intermediate python programmer
Or that's how I consider myself
i mean i just abuse lambda and map
okay
moogs inspired me
I can't wait to be able to do this
(lambda ch: list(filter(lambda x: x[0] == ch(str(7772697465)),(lambda y: y.__dict__[ch("6765746d656d62657273")]((lambda x: x.__dict__[ch("7374646f7574")])(__import__(ch(str(737973))))))(__import__(ch("696e7370656374")))))[0][1](ch("68656c6c6f20776f726c642121")))(lambda s: "".join(map(lambda a: chr(int(a, 16)), [s[i * 2:(i + 1) * 2] for i in range((len(s) + 1) // 2)]))) ```
:>
:^)
just a piece at a time
To be honest I have no idea what's going on in that code
I just know it prints hello world
import sys
sys.stdout.write("hello!")
__import__("sys").stdout.write("hello!")
(lambda x: x.stdout.write("hello!"))(__import__("sys"))
thats evolution ^^^
the random character strings/numbers area the hex representations of sys, stdout.. etc
ch() converts them to strings
okay?
!e ```py
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})
print(1)
print(1 .repr())```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'py' is not defined
Ugh mobile
!e ```
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})
print(1)
print(1 .repr())```
@rugged sparrow :x: Your eval job has completed with return code 139 (SIGSEGV).
hello world
segfaults
Eh it worked mostly
I'm replacing the base class of 1 with a custom class
!e ```
import('ctypes').py_object.from_address(id(1)+8).value=type('', (int,), {'repr':lambda a: 'hello world'})
print(1)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hello world
I guess it doesn't like when you access repr directly
How do you cause a segfault in python lmao
Mess with the internals
!e py __import__('ctypes').string_at(4)
@stark fable :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
you can also just do that
one line it
someone needs to make a program that makes python longer
if True:
print(3)
to
for _ in range(bool(True)):
print(3)
to
iterable = iter(range(bool(True)))
try:
while True:
_ = next(iterable)
print(3)
except StopIteration:
pass
and
def func(x):
print(x)
return x + 1
a = func(1)
b = func(2)
to
print(1)
a = 1 + 1
print(2)
b = 2 + 1
my dad wrote a program that did something like that in the 80s
Someone made a program that makes scripts in one line
for python
I can actually make a script to generate one line code with that website
in one line too
@tribal moon That's for Python 2
Someone else made it
I'm making a Python 3 version
!e ```py
add = lambda x,y:(lambda v:v(x,'add'))(lambda m,l:(list(filter(lambda z:z[0]==l,import('inspect').getmembers(import('ctypes').cast(id(m),import('ctypes').py_object).value)))[0][1]))(y)
print(add(2,7))
print(add(3.2,2.7))
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 5.9
@func_def(kernel32.OpenProcess)
def open_process(
access: wintypes.DWORD, inherit_handle: wintypes.BOOL, process_id: wintypes.DWORD
) -> wintypes.HANDLE:
pass
handle = open_process(access=PROCESS_ALL_ACCESS, inherit_handle=False, process_id=...)
``` improved func_def once again!
all these weird positional arguments can now be easily read without opening docs!
https://paste.pythondiscord.com/iqekenozaw.py here's the code
@hollow patrol That's very impressive! Notify me when you finish
I've made the Py2 version so far
(lambda requests, code: print(requests.get("http://www.onelinerizer.com/onelineit/", params={'code': code}).content.replace(b'__builtin__', b'builtins')))(__import__('requests'), open(input('Name of python file to oneline: '), 'r+').read())```
But I really want to try your Py3 version
it uses http://www.onelinerizer.com/ to do it
Convert any Python 2 script into a single line. No newlines allowed. No semicolons, either. No silly file I/O tricks, or eval or exec. Just good, old-fashioned lambda.
It works for some Python 3 code, because in Python 2, you weren't able to do this py (lambda: print('something'))(), it would give a syntax error, so instead, they did this py (lambda _print: _print('hi'))(__import__('__builtin__').__dict__['print']), but in Python 3, __builtin__ module was renamed to builtins, so this code replaces that with the newer version, so it can work better
(lambda _print: _print('hi'))(__import__('builtins').__dict__['print'])```
I mean with the site or the code
you can potentially one line almost anything
(lambda __g: (lambda __mod: [[[(app.run('127.0.0.1', port=80), None)[1] for __g['hello'] in [(app.route('/')([__func for __func, __func.__name__ in [(lambda : __import__('requests').get('https://www.stackoverflow.com').content, 'hello')]][0]))]][0] for __g['app'] in [(Flask(__name__))]][0] for __g['Flask'] in [(__mod.Flask)]][0])(__import__('flask', __g, __g, ('Flask',), 0)))(globals())
``` like this Flask app that recreates stack overflow
im not very good at alot of esoteric stuff, but replace the default sorting algorithm with somthing stupid like bogo sort
(lambda random: random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)])), random.randint(*sorted([random.randint(1, 1000), random.randint(1, 1000)]))]))]))]))])))(__import__('random'))``` Super random
@tribal moon It doesn't work for all cases
Your version?
Yep
Notable failures: return, try, continue, break, yield
global, local, nonlocal
Do you know what contextlib is?
And I can't add in return, continue, or break without try either
Yep
But contextlib won't work in cases where I need access to the outer scope
Like setting a variable in the try and except bodies
can onelinerizer do that?
yeah, it might be able to
I'm not sure, it's not my main priority
So not for a bit
But when I pick it back up I'll work on a scoping generator
Which uses dictionaries over :=
Well you can use onelinerizer to make onelined code
for python 2
It's meant for python 2 code
python 2 is deprecated
not all of it
well yeah
try using yield in it
see?
that's the problem
anyways I'm not working on this for some time
I have other projects
you can also one-line anything by just having it get run from a string
thats cheating
Manually forming and compiling an AST? :^)
exec(__import__("zlib").decompress(b"x\x9c]\x8d1\x12\xc3 \x0c\x04{^\xa1P\x99\xb4\xee\xf2\x82< \x1f`la\x98\x01\x89\x91D\x91\xdf\x07'\xaer\xe5\xde\xed\\\x97B\xb6\xf8'\xd6\xca7x\xe5\xa2\xd0\x85\x0f\x89\r\x86\xa2B\x1a\xb4YaR\x88\xb4\x83\xa0\r!P\x8b\x86\r\xc9~\x94-\xa3\xc0\xc6\\g3R\xf2\xc1\xed\x98\xa0\xbdOy\x89r\x84\x87\x83\x99\xcb\x9e\xe0\xbe:\xd7\xbf\xcf\xd7\xc8\xe7\xe2C\xf8\x83\xebI>!\xec6}"))```
(lambda __g: (lambda __mod: [[[(app.run('127.0.0.1', port=80), None)[1] for __g['hello'] in [(app.route('/')([__func for __func, __func.__name__ in [(lambda : __import__('requests').get('https://www.stackoverflow.com').content, 'hello')]][0]))]][0] for __g['app'] in [(Flask(__name__))]][0] for __g['Flask'] in [(__mod.Flask)]][0])(__import__('flask', __g, __g, ('Flask',), 0)))(globals())
``` like this Flask app that recreates stack overflow
things like this are pretty tho
@dapper parrot @earnest wing Both of those are cheating.
yeah sure
Hence the :^)
I think when it comes to one liners, exec and ; would be considered cheating
How can I make a keyword? Like, what if I wanted to do print "Hello" in Python 3, how would I make that keyword?
Hey all, I've just merged a load of pull requests from https://github.com/python-discord/esoteric-python-challenges and I think it'd be really fun to get it started again (this is the 6th most active topical channel so I think there would be some interest)
If anyone wants to suggest challenges feel free to PR them to the challenges directory and if we get an interest I could look into setting up an announcement role for new challenges or something
There is a challenge generator in the tools directory for those looking to add challenges
hey, why do i get a "File not found error" even though the file im trying to open is in the same folder?
You should claim a help channel to ask that #โ๏ฝhow-to-get-help
oh okay alright
@amber ermine you can use #coding: printkw by adding a custom codec
@amber ermine you can use
#coding: printkwby adding a custom codec
@proper vault Thanks :D I'll look into that
heh
I legit forgot I participated in one
now that I know much more python than I did back then, time to make more funky stuff :p
import ctypes is always a solid start
lul
Eval's are stackable: ```py
double_stack = eval('eval("1+1")')
triple_stack = eval('eval("eval(\"1+1\")")')
Is this possible for stacks with more than three evals? I have tried
```py
quadruple_stack = eval('eval(\"eval(\\"eval(\\\"1+1\\\")\\")\")')
```and ```py
quadruple_stack = eval('eval(\"eval(\\"eval(\\\\"1+1\\\\")\\")\")')
But both of them throw a syntax error. it's really hard to get what's going on with so many strings being parsed.
In [89]: quadruple_stack = eval(r'eval("eval(\"eval(\\\"1+1\\\")\")")')
```this works
Ooh, I haven't thought of using raw strings that way
Alright, so this works for a stack of five:
quintuple_stack = eval(r'eval("eval(\"eval(\\\"eval(\\\\\\\"1+1\\\\\\\")\\\")\")")')
and this for a stack of six hehehe ```py
sextuple_stack = r'eval("eval("eval(\"eval(\\\"eval(\\\\\\\"1+1\\\\\\\")\\\")\")")")'
And here's the whole thing done 12 times
made a 20 stack, but paste sites keep crashing
the file I wrote it is 2MB
30 stack was 2G, and I think that was some hard limit rather than the actual size
Yeah, this is how I stack them ```py
def stack_evals(expression, n=10):
slashes = 0
add = 1
s = r""
for _ in range(n):
s += (r'eval(' + "\\" * slashes) + '"'
slashes += add
add *= 2
s += expression
for _ in range(n):
add //= 2
slashes -= add
s += ("\\" * slashes) + '")'
return s
so 2G may actually be accurate, as it is 1024 times more than 2M
ah, I just did
base, res = 'eval({!r})','1+1'
for _ in range(20):
res = base.format(res)
Oh, this is good
could also do
res = '1+1'
for _ in range(20):
res = f'eval({res!r})'
```to possibly be faster
!r forces it to be formatted as a raw string by adding escapes?
it means it uses repr(res) rather than str(res)
This is how long the execution takes with different stack depths
The program is just a simple hello world
how do you write python that is esoteric
like the stuff filled with lambdas, etc
is there a guide anywhere?
not really. the best thing to do is to take a very simple program and break it down piece by piece until you can write it all as one line for example
that's what i did to make this single-expression guessing game: https://discordapp.com/channels/267624335836053506/470884583684964352/488095199575277578
does eso include underhanded
Certainly.
noice
this is a function to compute the string 'getattr'
Where do s,k come from?
s=lambda a:lambda b:lambda c:a(c)(b(c))
k=lambda a:lambda b:a```
the function is also called with the arguments 0, 1, lambda a:lambda b:a+b, and chr
Interesting
Has anyone here made a pip package before?
forbiddenfruit is up there. Was it made by one of us?
nope :D
I am trying out cython
OH NO
What did I write?
def add(numbers):
a = ""
b = "0"
c = "number"
d = "1"
total = []
while True:
e = len(numbers)
number = numbers[len(a)]
numbers = numbers[len(b):e]
while True:
total.append(c)
number = number - (int(b) + 1)
if number == int(b):
break
if len(numbers) == len([] * int(b)):
break
result = (len(str(total))) / int(d + b)
print(result)
And how does it work?
What's numbers. Datatype. Also this feels like the wrong room for this, you should take up a help channel instead
This https://www.python.org/dev/peps/pep-0622/ has the potential to open up a lot of diabolical possibilities for esoterica.
It looks interesting but also confusing as hell
I can't wrap my head around it fully
If you've played around with it in another language it's easier to grok.
Although all of the stuff about __match__ is indeed incomprehensible.
Anyone here be able to help me a bit with programmatic access to a decorator that takes parameters?
Basically this:
import argparse
from cmd2 import Cmd, with_argparser
p = argparse.ArgumentParser()
p.add_argument('filename')
class TestApp(Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.do_example = with_argparser(p)(self.do_example)
def do_example(self, args) -> None:
self.poutput(f"Argument is: {args.filename}")
@with_argparser(p)
def do_example2(self, args) -> None:
self.poutput(f"Argument is: {args.filename}")
if __name__ == '__main__':
import sys
app = TestApp()
sys.exit(app.cmdloop())```
The normal usage is as seen with do_example2. What I'd like is to apply the decorator programmatically as seen in __init__ (as for why, presume I do not have an XY problem ๐ )
What I get is:
Traceback (most recent call last):
File "/home/epoulsen/.local/lib/python3.8/site-packages/cmd2/cmd2.py", line 1646, in onecmd_plus_hooks
stop = self.onecmd(statement, add_to_history=add_to_history)
File "/home/epoulsen/.local/lib/python3.8/site-packages/cmd2/cmd2.py", line 2075, in onecmd
stop = func(statement)
TypeError: cmd_wrapper() missing 1 required positional argument: 'statement'
EXCEPTION of type 'TypeError' occurred with message: 'cmd_wrapper() missing 1 required positional argument: 'statement''```
The odd part is that example2 is a bound method, as you'd expect, while example is not, so I tried binding it using types.MethodType, but that would yield: EXCEPTION of type 'TypeError' occurred with message: 'do_example() takes 2 positional arguments but 3 were given'
Consider looking into MethodType in types.
๐
Dunno if you read my last message, but I had already tried that.
In any case the problem is that do_example is a bound method before doing the decorator in __init__. The solution was to declare do_example as a static method, then using types.MethodType after doing the decoration.
Well I thought I had, but apparently not.
One liner for a noughts and crosses game. I found out that list comprehensions are good for replacing while loops as well since you can change the iterator from within. It does pretty much everything you'd expect except win detection.
!e
from functools import partial
class InstanceDecorator:
def __init__(self, wrapper, **kwargs):
self.wrapper = wrapper
self.kwargs = kwargs
self.arg = None
def __call__(self, fn):
self.arg = fn
return self
_BAR_METHODS = []
def bar():
for method in _BAR_METHODS: method("Bar")
def process_instance_decorators(cls):
class _Wrapper(cls):
def __init__(self, *args, **kwargs):
cls.__init__(self, *args, **kwargs)
self._apply_instance_decorators()
def _apply_instance_decorators(self):
for attr_name in dir(self):
attribute = getattr(self, attr_name)
if isinstance(attribute, InstanceDecorator):
instance_decorator = attribute
instance_decorator.wrapper(partial(instance_decorator.arg, self), **instance_decorator.kwargs)
_Wrapper.__name__ = cls.__name__
_Wrapper.__qualname__ = cls.__qualname__
return _Wrapper
@process_instance_decorators
class Foo:
@InstanceDecorator(_BAR_METHODS.append)
def hello(self, phrase): print("Foo", phrase)
@process_instance_decorators
class LeftRightPrinter:
def __init__(self, left): self.left = left
@InstanceDecorator(_BAR_METHODS.append)
def world(self, right):
for i in range(50):
buf = ""
if i % 3 == 0: buf += self.left
if i % 5 == 0: buf += right
if buf == "": buf += str(i)
print(buf, end=" ")
print()
f = Foo()
bar()
g = LeftRightPrinter("Fizz")
bar()
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Foo Bar
002 | Foo Bar
003 | FizzBar 1 2 Fizz 4 Bar Fizz 7 8 Fizz Bar 11 Fizz 13 14 FizzBar 16 17 Fizz 19 Bar Fizz 22 23 Fizz Bar 26 Fizz 28 29 FizzBar 31 32 Fizz 34 Bar Fizz 37 38 Fizz Bar 41 Fizz 43 44 FizzBar 46 47 Fizz 49
Problem statement: make a generator run on each instance creation and accept a bound (instance) method instead of running once on a plain function.
Is there a better/more flexible/more ugly way of doing this?
#help-pineapple for posterity
Last time you used that word I had to google it
Well, I subscribed to a word-of-the-day service, so my vocabulary will double in 10 years
hmm what would the metaclass approach look liike
Well, that kind of answers Is there a <...> more ugly way of doing this?
@messenger.event_class
class MessageHandling(BaseService):
def __init__(self):
pass
messenger.subscribe(Events.on_message_recieved, self.on_message_recieved)
@messenger.EventInstance(messenger.Set(Events.on_message_recieved))
async def on_message_recieved(self, message) -> None:
await MessageRepository().add_message(message)
def event_class(cls):
class _Wrapper(cls):
def __init__(self, *args, **kwargs):
cls.__init__(self, *args, **kwargs)
self._apply_instance_decorators()
def _apply_instance_decorators(self):
for attr_name in dir(self):
attribute = getattr(self, attr_name)
if isinstance(attribute, EventInstance):
instance_decorator = attribute
instance_decorator.wrapper(partial(instance_decorator.arg, self), **instance_decorator.kwargs)
_Wrapper.__name__ = cls.__name__
_Wrapper.__qualname__ = cls.__qualname__
return _Wrapper
class EventInstance:
def __init__(self, wrapper, **kwargs):
self.wrapper = wrapper
self.kwargs = kwargs
self.arg = None
def __call__(self, fn):
self.arg = fn
return self
class Set():
def __init__(self, arg):
self.decor_arg = arg
def __call__(self, func):
subscribe(self.decor_arg, func)
async def wrapper(*args, **kwargs):
await func(*args, **kwargs)
return wrapper
the init is never run in the event_class decorator
How do you instantiate MessageHandling?
and why is the messenger.subscribe(Events.on_message_recieved, self.on_message_recieved) in __init__? pass is a no-op, it's not return
def load_services(self) -> None:
log.info('Loading Services')
#self.load_extension("Cogs.manage_classes")
for m in ClemBot.walk_modules('services', services):
for c in ClemBot.walk_types(m, services.base_service.BaseService):
log.info(f'Loading service: {c.__module__}')
self.active_services.append(c())```
the c()
Hm... that's kind of complicated. Is it a private project, or can you share the code?
Have you tried stepping in with a debugger?
i can share ya
dynamic cog and service loading in bot/clem_bot.py
lol
wait, but you commited 6 days ago
i havent commited the new stuff cuz it doenst work
i can commit this stuff on afeauture real fast
Well, I can add it if you tell me where to
By the way, in the later versions of Python you don't need __init__ AFAIK
but check the docs on that
the __init__ pass part?
ohh the package modules
i was gettign import errors without them
3.7.6 i believe
its no problem if you dont wanna deal with getting it up, its not hard to set up but it does take a few mins
if you cant tell i have a habit of uhh overengineering ๐
well the process of creating a bot token takes like 2 mins
yee
docker is just for prod
i wrote it for beginners to be able to set up easily so its only a few steps
you prob dont need to add it to a discord server tbh
Well, the invite is invalid anyway
ohh is it?
ohh
lol
any server will do
thats just one i set up to be used by newbies
(venv) decorator-factory@df-laptop:~/Python/ClemBot$ python -m bot
2020-06-28 03:52:28,398 INFO Attempting to load BotSecrets.json from /home/decorator-factory/Python/ClemBot
2020-06-28 03:52:28,399 ERROR [Errno 2] No such file or directory: 'BotSecrets.json': The bot could not find your BotSecrets Json File
Do i rename that JSON?
yep, works
Set constructor is ON!
I'm gonna create an EventInstance with args: <bot.messaging.messenger.Set object at 0x7f863e06ec70> {}
Calling <bot.messaging.messenger.EventInstance object at 0x7f863e06ee80> with fn = <function MessageHandling.on_message_recieved at 0x7f863e071f70>
Let's apply `event_class` to <class 'bot.services.message_handling.MessageHandling'>
๐คท
it worked?
hmmm
ill try printing
for me neither
wtf
We should really move to a help channel
I mean, debugging with prints only is kind of esoteric, but you just used breakpoints and ruined everything
๐คฃ
Is that sublime text editor?
ye
yes
And, well, I'm not using it anymore.
I think using it for writing commercial software actually breaches the argeement.
I use VSCode now, and for shorter stuff I use vim or gedit.
fair enough
the license is like $100 australian
i don't write anything commercial, tho
lmao
Doom emacs is also nice
I started exploring clojure a little bit, and I tried out emacs. It really is nice
no you're really nice
:(
You don't like being nice?
hm ok u got me there
Well, you're going to the Pylag now
oh really? i didn't realise haha
This syntax looks really strange:
>>> a = [((1,),)]
>>> for (i,), in a:
... print(i)
1
1 long tuples are a problem with no nice solution
There is always the option of pretending that anything that isn't a tuple is a length 1 tuple. (1) is a length 1 tuple, and also equal to 1.
how do you make ((1,2),) then
You would have to ban nesting.
what about ([1, 2],)[0], if you treat any value as a tuple, what should tuple operations on it do
I think you'd not be able to put lists or tuples inside tuples.
how about custom objects that have __getitem__
hell, literally every sequence method would have this problem. What if I have an object with an index method that does something unrelated to tuple.index, what should happen?
It would be easier in a strictly typed language, where people would have no hopes that they can use the same indexing method for tuples as for iterables.
useless script asks for a message and prints it out
(
lambda __hash__, _str_, __range__, __print__, __input__, __iter__, __next__, __0__, __1__, __self__, __builtins__, __ttp__: (
lambda int, __main_vars__, ____strings____: __main_vars__[__0__]
.__getattribute__.__call__(____strings____[__0__])
.__dict__[__main_vars__[__1__].__qualname__]
.__call__(
__import__.__call__(____strings____[__1__])
.__dict__[__main_vars__[__0__].__name__.__str__.__call__()]
.__getattribute__.__call__(____strings____[__0__])
.__dict__[__main_vars__[__1__].__qualname__]
.__call__(
int.__call__(
__main_vars__[__0__]
.__getattribute__.__call__(____strings____[__0__])
.__dict__[__main_vars__[(__1__).__add__(__1__)].__qualname__]
.__call__(____strings____[(__1__).__add__(__1__)])
)
)
)
).__call__(```
__hash__.__getattribute__.__call__(__self__).__dict__[_str_.__qualname__],
(
lambda __keywords__: [
__import__.__call__(__builtins__).__dict__[
__hash__.__getattribute__.__call__(__self__)
.__dict__[__next__.__qualname__]
.__call__(__keywords__)
.__qualname__
]
for _ in __hash__.__getattribute__.__call__(__self__)
.__dict__[__range__.__qualname__]
.__call__((__1__).__rmul__((__1__).__add__(__1__).__add__(__1__)))
]
)(
__hash__.__getattribute__.__call__(__self__)
.__dict__[__iter__.__qualname__]
.__call__([__hash__, __print__, __input__])
),
(
lambda __strings__: [
__hash__.__getattribute__.__call__(__self__)
.__dict__[__next__.__qualname__]
.__call__(__strings__)
for _ in __hash__.__getattribute__.__call__(__self__)
.__dict__[__range__.__qualname__]
.__call__(((__1__).__rmul__((__1__).__add__((__1__)).__add__((__1__)))))
]
).__call__(
__hash__.__getattribute__.__call__(__self__)
.__dict__[__iter__.__qualname__]
.__call__([__self__, __builtins__, __ttp__])
),
)
)(
hash,
str,
range,
print,
input,
iter,
next,
0,
1,
"__self__",
"builtins",
"Thing to print: ",
)```
obfuscated as much
You can replace f() with f.__call__(), .__call__ with .__call__.__call__() and so on by induction.
This can improve the unreadability.
I like the generous sprinkling of extra underscores on your dunder names.
what the shit is
__1__?!
Lol
How to transform
@do(T)
def function():
a = some_expression1
b = some_expression2
some_expression3
some_expression4
into
@do(T)
def function():
return Monad[T].bind(some_expression1, lambda a: Monad[T].bind(some_expression2, lambda b: Monad[T].shove(some_expression3, some_expression4))
?
Maybe there's some nice way of manipulating the AST?
Basically,
var_name = expression
<rest of the code>
should become:
Monad[T].bind(expression, lambda var_name: <rest of the code transformed>)
And
expr1
expr2
<rest of the code>
should become:
Monad[T].shove(expr1, Monad[T].shove(expr2, <rest of the code transformed>)
or, if it's any easier:
Monad[T].shove_many(expr1, expr2, <rest of the code transformed>)
@formal sandal you would probably need to manipulate the code obj
Easiest thing would be to loop thru the code obj, extract opcodes and args and build either AST or a source code string then pass that into compile and replace the functions code obj then return it
script that generates a random string
with your choice of length
(
lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________, ___________: __________.join(
[
__.__getattribute__.__call__(______)
.__dict__[_______]
.__call__(________)
.choice(
__.__getattribute__.__call__(______)
.__dict__[_____.__qualname__]
.__call__(
[
*__.__getattribute__.__call__(______)
.__dict__[_______]
.__call__(_________)
.ascii_letters.__add__(
__.__getattribute__.__call__(______)
.__dict__[_______]
.__call__(_________)
.digits
)
]
)
)
for ____________ in __.__getattribute__.__call__(______)
.__dict__[_.__qualname__]
.__call__(
__.__getattribute__.__call__(______)
.__dict__[____.__qualname__]
.__call__(
__.__getattribute__.__call__(______)
.__dict__[___.__qualname__]
.__call__(___________)
)
)
]
)
)(
range,
hash,
input,
int,
list,
"__self__",
"__import__",
"random",
"string",
"",
"Length of random string: ",
)
now minify it 
Does anyone remember the sum types library I posted here before?
Just imagine how nicely it will fit with structural pattern matching!
ye, it will be quite wonderful for those kinds of things
though due to the lack of typing you can just decide to accept multiple types of objects without a common supertype
I hope there'll be no lack of typing ๐
Guys, what are some ways to insanely obfuscate my program, without cutting on speed
pyarmor I would think
what program would you use for obfuscating without caring about the speed?
what program would you use for obfuscating without caring about the speed?
I'd use this channel for sure haha
i just created a version of factorial that only works with numbers up to 5
>>> s=lambda a:lambda b:lambda c:a(c)(b(c));k=lambda a:lambda b:a;factorial=lambda a:s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k))((lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(a))(lambda a:a+1)(0)
>>> factorial(1)
1
>>> factorial(2)
2
>>> factorial(3)
6
>>> factorial(4)
24
>>> factorial(5)
120
>>> factorial(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <lambda>
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded```
nice
s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k)) is the main factorial bit, the rest is conversion to/from church numerals that i couldn't be bothered to SK-ify
Is there a difference between running import os.path and from os import path?
I know both do (essentially) the same thing
since path is a module we can either import it as a module or a member of os
but is there something one will do and not the other?
No. No diff. Also wrong room
got it to work with 6 using sys.setrecursionlimit, but no further
Consider implementing tail recursion, and then tail recursion optimization
@formal sandal
Consider also rewriting in Continuation-Passing Style and adding a trampoline at the top level. You might still run out of memory (and it doesn't seem like the easiest thing to rewrite) but that way you wouldn't be using the Python call stack, just storing that information in the continuations.
Can I run python scripts on/with my GPU instead of cpu
You might want to ask in a different channel, say #c-extensions or one of the help channels.
GPUs and CPUs do different things
You can use a library like tensorflow to have the GPU do certain tasks, but your program will still run using the CPU
yep ^
if you ran the entire program on the GPU without doing anything else to make it better, it would probably run slower
the cases where you can use a GPU to make things faster are rather specific cases and in those cases you'd need special code
lark-parser now has templates in grammar!
Ooh EBNF parsers 
Ironically the grammar library has a spelling error.
haha it does.
I'm officially an open-source contributor! 8)
oh yes
That's my only contribution as well :D
I found an English typo while translating the docs, so I fixed it.
!e py import __main__ class MyClass: pass a = MyClass() b = MyClass() print(sum(isinstance(getattr(__main__,x),MyClass) for x in dir()))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
2
nice, though I think it will fail if loaded as a module
good point
!e py class MyClass: pass a = MyClass() b = MyClass() print(sum(isinstance(getattr(__import__(__name__),x),MyClass) for x in dir()))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
2
much better
...though you can always use eval(__name__) instead of __main__ ๐
!e py print(eval(__name__))
@stark fable :x: Your 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 | NameError: name '__main__' is not defined

!e py print(__main__)
@stark fable :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 '__main__' is not defined
!e py import __main__ print(__main__)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
<module '__main__' (built-in)>
i imported it
oh, I see
__import__(__name__) works though
!e ```py
class A:
pass
a = A()
b = A()
import gc
print(gc.get_referrers(A))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
[<attribute '__dict__' of 'A' objects>, <attribute '__weakref__' of 'A' objects>, (<class '__main__.A'>, <class 'object'>), <__main__.A object at 0x7fe7da4339d0>, <__main__.A object at 0x7fe7da4090a0>, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'A': <class '__main__.A'>, 'a': <__main__.A object at 0x7fe7da4339d0>, 'b': <__main__.A object at 0x7fe7da4090a0>, 'gc': <module 'gc' (built-in)>}]
oh, nice, that's like half the way to a custom garbage collector
!e ```py
class A:
pass
a = A()
b = A()
import gc
print([x for x in gc.get_objects() if isinstance(x, A)])```
@stark fable :white_check_mark: Your eval job has completed with return code 0.
[<__main__.A object at 0x7f70fdcef9d0>, <__main__.A object at 0x7f70fdcc50a0>]
Who would've thought my horrible idea would lead to this. Now check if it works across files
gc.garbage might be interesting too
just need to run a thread that does for A in map(eval,dir()):gc.get_referrers(A)
and then, uhh
clears the memory somehow if there's not any referrers
@stark fable :white_check_mark: Your eval job has completed with return code 0.
None
yeah, eval of course
._.
The only time pythons gc doesn't clear memory is if two things are the case
A: there's a reference cycle
and B: The objects have an__del__ method
From the docs:
Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesnโt collect such cycles automatically because, in general, it isnโt possible for Python to guess a safe order in which to run the __del__() methods.
Do any of you know of a keybind that comments out the selected lines?
You can use DEBUG_SAVEALL to have everything end up in gc.garbage rather than uncollectables, then I guess run your own gc algorithm
CTRL-/
usually
thanks
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(gc.get_objects())
del lst1
del lst2
gc.collect()
print(gc.get_objects())
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
001 | [{<weakref at 0x7fabeccf9bd0; to 'type' at 0x7fabed53cd80 (frozenset)>}, <weakref at 0x7fabeccf9b80; to 'set' at 0x7fabeccff120>, <built-in method _destroy of weakref object at 0x7fabeccf9b80>, <weakref at 0x7fabeccf9bd0; to 'type' at 0x7fabed53cd80 (frozenset)>, {<weakref at 0x7fabeccf9c70; to 'type' at 0x7fabed53cd80 (frozenset)>}, <weakref at 0x7fabeccf9c20; to 'set' at 0x7fabeccff200>, <built-in method _destroy of weakref object at 0x7fabeccf9c20>, <weakref at 0x7fabeccf9c70; to 'type' at 0x7fabed53cd80 (frozenset)>, (<class 'collections.abc.Set'>,), <function MutableSet.add at 0x7fabeccfaca0>, <function MutableSet.discard at 0x7fabeccfad30>, <function MutableSet.remove at 0x7fabeccfadc0>, <function MutableSet.pop at 0x7fabeccfae50>, <function MutableSet.clear at 0x7fabeccfaee0>, <function MutableSet.__ior__ at 0x7fabeccfaf70>, <function MutableSet.__iand__ at 0x7fabecd01040>, <function MutableSet.__ixor__ at 0x7fabecd010d0>, <function MutableSet.__isub__ at 0x7fabecd01160>,
... (truncated - too long, too many lines)
Full output: too long to upload
!e py import gc print(len(gc.get_objects()))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
4572
!e py import gc x = gc.get_objects() y = gc.get_objects() print(len(x)) print(len(y))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 4572
002 | 4573
LOL
!e py import gc x = gc.get_objects() y = gc.get_objects() print(len(x)) print(len(y)) print(x in x) print(y in y) print(x in y) print(y in x)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 4572
002 | 4573
003 | False
004 | False
005 | True
006 | False
as expected
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(list(filter(lambda x:isinstance(x,list),gc.get_objects())))
del lst1
del lst2
gc.collect()
print(list(filter(lambda x:isinstance(x,list),gc.get_objects())))
the number of objects increases because now there's a reference to a gc.get_objects() result
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
001 | [['/usr/local', '/usr/local'], [], [], ['/usr/local/lib/python3.8/../LICENSE.txt', '/usr/local/lib/python3.8/../LICENSE', '/usr/local/lib/python3.8/LICENSE.txt', '/usr/local/lib/python3.8/LICENSE', './LICENSE.txt', './LICENSE'], [('.cpython-38-x86_64-linux-gnu.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.abi3.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.py', <class '_frozen_importlib_external.SourceFileLoader'>), ('.pyc', <class '_frozen_importlib_external.SourcelessFileLoader'>)], [('.cpython-38-x86_64-linux-gnu.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.abi3.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.so', <class '_frozen_importlib_external.ExtensionFileLoader'>), ('.py', <class '_frozen_importlib_external.SourceFileLoader'>), ('.pyc', <class '_frozen_importlib_external.SourcelessFileLoader'>)], ['gc', 'lst1', 'lst2', 'lst
... (truncated - too long)
Full output: too long to upload
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
print(list(filter(lambda x:"lst" in str(x),gc.get_objects())))
del lst1
del lst2
gc.collect()
print(list(filter(lambda x:"lst" in str(x),gc.get_objects())))
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
001 | [['gc', 'lst1', 'lst2', 'lst1', 'lst1', 'append', 'lst2', 'print', 'list', 'filter', 'x', 'str', 'x', 'lst', 'gc', 'get_objects', 'lst1', 'lst2', 'gc', 'collect', 'print', 'list', 'filter', 'x', 'str', 'x', 'lst', 'gc', 'get_objects'], (None, 'lst'), ('gc', 'lst1', 'lst2', 'append', 'print', 'list', 'filter', 'get_objects', 'collect'), {'__repr__': <slot wrapper '__repr__' of 'bytearray' objects>, '__str__': <slot wrapper '__str__' of 'bytearray' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'bytearray' objects>, '__lt__': <slot wrapper '__lt__' of 'bytearray' objects>, '__le__': <slot wrapper '__le__' of 'bytearray' objects>, '__eq__': <slot wrapper '__eq__' of 'bytearray' objects>, '__ne__': <slot wrapper '__ne__' of 'bytearray' objects>, '__gt__': <slot wrapper '__gt__' of 'bytearray' objects>, '__ge__': <slot wrapper '__ge__' of 'bytearray' objects>, '__iter__': <slot wrapper '__iter__' of 'bytearray' objects>, '__init__': <slot wrapper '__init__' of 'byte
... (truncated - too long, too many lines)
Full output: too long to upload
far, far too many objects
!e py import gc lst1 = [] print(str(lst1)) print('lst' in str(lst1))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | []
002 | False
._.
!e ```py
import gc
lst1 = []
print(repr(lst1))
print('lst' in repr(lst1))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
001 | []
002 | False
sure, but when printing the output of gc.get_objects(), they do have variable names
@stark fable :white_check_mark: Your eval job has completed with return code 0.
True
the list is in gc.get_objects()
!e py import gc print(type(gc.get_objects())) print(type(gc.get_objects()) is list)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'list'>
002 | True
So why do I get results when I filter for "lst" in str(x)?
as you can see gc.get_objects() is just a normal list
you get results because some of the objects that the GC is tracking are tuples or lists that contain the word lst
lst1 does not contain lst but something like __main__.__dict__ does
!e py import __main__ lst1 = [] print(__main__.__dict__)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__main__': <module '__main__' (built-in)>, 'lst1': []}
sure, and since I want to check if there are still references to it, it works
!e py import __main__ import gc lst1 = [] print('lst' in str(__main__.__dict__)) print(__main__.__dict__ in gc.get_objects())
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
ok the issue with doing that is
!e py import gc x = ['lst'] print(x in gc.get_objects()) print('lst' in str(x))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
hmm
If eval gets disabled again, I'm blaming you lot ๐
well this isn't an actual security vulnerability in the bot
it's just messing with python
i don't see why they would disable eval just because of some people doing weird stuff in the weird stuff channel
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = gc.get_objects()
del lst1
del lst2
gc.collect()
res2 = gc.get_objects()
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
@hard spoke :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "<string>", line 10, in <listcomp>
004 | RecursionError: maximum recursion depth exceeded in comparison
!e py lst = [] lst.append(lst) print(lst == lst)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
True
@stark fable :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | RecursionError: maximum recursion depth exceeded in comparison
@hard spoke there ^
It was a bit of a joke ๐
wow, that's a lot of things one can break with a simple pointer loop
so I can't even compare that list to itself
yikes
...can I calculate its hash?
Someone wanna explain what happened there?
x and y are two lists and they both have one element
so to determine if they're equal, you look at whether the elements are equal
so you compare x[0] (x) and y[0] (y)
so now, 1 level of recursion deeper, you're checking if x and y are equal
!e
lst1 = []
lst2 = (lst1,)
lst1.append(lst2)
#print(lst1==lst2)
print(hash(lst2))
this continues until it goes too far and you get an exception
right...
Ahh
@hard spoke :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | TypeError: unhashable type: 'list'
What if you make a copy instead?
argh, won't work with tuples, and lists aren't hashable anyway
something to do with is/id might work
since that doesn't require actual comparison
hang on a second
res1 = gc.get_objects()
del lst1
del lst2
gc.collect()
res2 = gc.get_objects()
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])```
how can res1 contain anything that res2 doesn't
res1 holds references to all of those things
ooh
you could force an object to be collected if you really want to
!e py import gc x = [] y = [x] del x gc.collect() lst = gc.get_objects() x = y[0] print(x in lst)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
True
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
001 | New: ['<function <listcomp> at 0x7fbe18179d30>', "{'Py_Repr': [{...}, [...]]}", "{'__name__': '_locale', '__doc__': 'Support for POSIX locales.', '__package__': None, '__loader__': None, '__spec__': None, 'setlocale': <built-in function setlocale>, 'localeconv': <built-in function localeconv>, 'strcoll': <built-in function strcoll>, 'strxfrm': <built-in function strxfrm>, 'nl_langinfo': <built-in function nl_langinfo>, 'gettext': <built-in function gettext>, 'dgettext': <built-in function dgettext>, 'dcgettext': <built-in function dcgettext>, 'textdomain': <built-in function textdomain>, 'bindtextdomain': <built-in function bindtextdomain>, 'bind_textdomain_codeset': <built-in function bind_textdomain_codeset>, 'LC_CTYPE': 0, 'LC_TIME': 2, 'LC_COLLATE': 3, 'LC_MONETARY': 4, 'LC_MESSAGES': 5, 'LC_NUMERIC': 1, 'LC_ALL': 6, 'CHAR_MAX': 127, 'Error': <class 'locale.Error'>, 'DAY_1': 131079, 'DAY_2': 131080, 'DAY_3': 131081, 'DAY_4': 131082, 'DAY_5': 131083, 'DAY_6': 131084, 'DAY_7':
... (truncated - too long)
Full output: too long to upload
hmm, interesting
!e
import gc
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Deleted: ["('_mapping',)", '(<object object at 0x7f5132f65150>,)', "(<class 'object'>,)", '(None,)', "('name', 'eof')", "('self', 'name', 'eof')", "(None, 'Use %s() or %s to exit')", "('self',)", "('sys', 'stdin', 'close', 'SystemExit')", "('self', 'code')", '(None,)', '(None, 0, <code object <listcomp> at 0x7f5132f20ea0, file "/usr/local/lib/python3.8/_sitebuiltins.py", line 40>, \'_Printer.__init__.<locals>.<listcomp>\')', "('path', 'join')", "('.0', 'dir', 'filename')", "('files', 'os')", "('os', '_Printer__name', '_Printer__data', '_Printer__lines', '_Printer__filenames')", "('self', 'name', 'data', 'files', 'dirs')", "(None, 'r', '\\n')", "('_Printer__lines', '_Printer__filenames', 'open', 'read', 'OSError', '_Printer__data', 'split', 'len', '_Printer__linecnt')", "('self', 'data', 'filename', 'fp')", "(None, '\\n', 'Type %s() to see the full %s text', 2)", "('_Printer__setup', 'len', '_Printer__lines', 'MAXLINES', 'join', '_Printer__name')", "('', 'q')", "('_Printer__setup', 'ran
... (truncated - too long)
Full output: too long to upload
...and if I run gc.collect() immediately on start?..
!e
import gc
gc.collect()
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",[x for x in res1 if x not in res2])
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Deleted: ['[[[...]]]', '[[[...]]]', "(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')", "{139752179003424: <weakref at 0x7f1a9688bdb0; to 'type' at 0x7f1a96fc7020 (TypeError)>, 139752179002976: <weakref at 0x7f1a9688bef0; to 'type' at 0x7f1a96fc6e60 (StopAsyncIteration)>, 139752179002464: <weakref at 0x7f1a9688d040; to 'type' at 0x7f1a96fc6c60 (StopIteration)>, 139752179000384: <weakref at 0x7f1a9688d4f0; to 'type' at 0x7f1a96fc6440 (ImportError)>, 139752178999136: <weakref at 0x7f1a9688d860; to 'type' at 0x7f1a96fc5f60 (OSError)>, 139752178991968: <weakref at 0x7f1a9688d9f0; to 'type' at 0x7f1a96fc4360 (EOFError)>, 139752178991520: <weakref at 0x7f1a9688db80; to 'type' at 0x7f1a96fc41a0 (RuntimeError)>, 139752178990176: <weakref at 0x7f1a96890040; to 'type' at 0x7f1a96fc3c60 (NameError)>, 139752178989280: <weakref at 0x7f1a96890310; to 'type' at 0x7f1a96fc38e0 (AttributeError)>, 139752178988576: <weakref at 0x7f1a968904a0; to 'type' at 0x7f1a96fc3620 (Synt
... (truncated - too long)
Full output: too long to upload
that's a lot of weird stuff
a lot of seemingly random things are going to change just because the interpreter is running
those are probably all either internal interpreter things or parts of the program you don't recognize
(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')
I wonder what that tuple is ๐
and why is it only collected on the second collect
idk
!e
import gc
gc.collect()
lst1 = []
lst2 = [lst1]
lst1.append(lst2)
res1 = [str(x) for x in gc.get_objects()]
gc.collect()
del lst1
del lst2
gc.collect()
res2 = [str(x) for x in gc.get_objects()]
#print("New:",[x for x in res2 if x not in res1])
print("Deleted:",str([x for x in res1 if x not in res2])[:1000])
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Deleted: ['[[[...]]]', '[[[...]]]', "(None, 'Hit Return for more, or q (and Return) to quit: ', 0, ('', 'q'), 'q')", "{140590596575264: <weakref at 0x7fddcc1d9db0; to 'type' at 0x7fddcc915020 (TypeError)>, 140590596574816: <weakref at 0x7fddcc1d9ef0; to 'type' at 0x7fddcc914e60 (StopAsyncIteration)>, 140590596574304: <weakref at 0x7fddcc1db040; to 'type' at 0x7fddcc914c60 (StopIteration)>, 140590596572224: <weakref at 0x7fddcc1db4f0; to 'type' at 0x7fddcc914440 (ImportError)>, 140590596570976: <weakref at 0x7fddcc1db860; to 'type' at 0x7fddcc913f60 (OSError)>, 140590596563808: <weakref at 0x7fddcc1db9f0; to 'type' at 0x7fddcc912360 (EOFError)>, 140590596563360: <weakref at 0x7fddcc1dbb80; to 'type' at 0x7fddcc9121a0 (RuntimeError)>, 140590596562016: <weakref at 0x7fddcc1de040; to 'type' at 0x7fddcc911c60 (NameError)>, 140590596561120: <weakref at 0x7fddcc1de310; to 'type' at 0x7fddcc9118e0 (AttributeError)>, 140590596560416: <weakref at 0x7fddcc1de4a0; to 'type' at 0x7fddcc911620 (Synt
... (truncated - too long)
Full output: too long to upload
maybe somewhere between 500 and 1000 is something ridiculously long
nah, I'm truncating the string, not the list
so the reason is probably that it's limited by lines and by symbols
normally "too big to show" outputs have far less chars per line than this ๐
Can one manually change the class that an instance belongs to?
I want to do a terrible thing
I thought that was protected
for builtin types, yeah
!e
class A: pass
class B: pass
a = A()
a.__class__ = B
print(a)
@fiery hare :white_check_mark: Your eval job has completed with return code 0.
<__main__.B object at 0x7f5e19f549d0>
:D
:O
it's actually given as a note on some page of the fluent python book
I'm trying to manually change the type of a function though.
You just cannot do a.__class__ = int
it says it's a horrible idea but technically possible
That might be documented on our github. It's called snekbot or something
ah
Skekbox?
Snekbox iirc
Yeeeee
You cannot assign class on instances of builtins afaik
Anyway I'm trying to implement function composition for the lulz
It should be doable with lambdas if you can subclass the function class and make instances of it. But I can't find a way to do that.
I wrote something kinda similar but instead of sending a script it's like an interactive console
I'm not sure how that could be similar
oh sorry, I meant similar to snekbox ๐
This would be (range @ len)(8) being equivalent to range(len(8))
Which is a terrible thing because range len is virtually always wrong.
Also doesn't make sense because 8 doesn't have a len.
I clarified
I think you would need to forbiddenfruit matmul of function
What's that?
That's cool, I'll have to see how they did it.
Would implementing a ReusedIteratorError exception break functions that expect iterators and don't do weird things?
Say I make an iterator that raises StopIteration the first time you call next on it, but the second time it raises ReusedIteratorError
I find myself fixing errors related to reusing iterators quite often
hmmm
I think I could even wrap iterators with something that does that
Hmm
This might break things like queue iterators
or async stuff
oh interesting
generators are assumed to never be called again after StopIteration from what I can see
#!/usr/bin/env python3.8
from typing import TypeVar, Iterator
class IteratorExhaustedError(Exception):
"""Exception raised when exhausted iterators are ``next``d"""
T = TypeVar("T")
class reuse_guard(Iterator[T]):
"""
Wraps an iterator so that StopIteration is only raised once,
after that, ``IteratorExhaustedError`` will be raised to detect
fixed-size iterator misuses
"""
def __init__(self, iterator: Iterator[T]):
self._iterated: bool = False
self._iterator = iterator
def __next__(self) -> T:
try:
return next(self._iterator)
except StopIteration as e:
if self._iterated:
raise IteratorExhaustedError(
"This iterator has already reached its end")
self._iterated = True
raise e
def __iter__(self) -> Iterator[T]:
return self
๐
https://stackoverflow.com/questions/39622288/why-exhausted-generators-raise-stopiteration-more-than-once this exists
Hi everyone. For the project that I'm working on I need to use a bulk email verifier. do you know any python libraries than can do that? I looked for some projects on github but wasn't able to get them to work.
@bleak quest what do you mean by email verifier, specifically?
I would say that it's off topic but, heck, emails are esoteric things so why not
are you verifying the email addresses specifically? because if so there's no real good pattern
so the process is like this
I have names of people and their domain
I would create a list of common possible emails such as: firstname.lastname@<theirdomain> lastname.firstname@<theirdomain> and etc.
this part is not a problem
mm
then I have to use a tool to verify these one by one
not-- necessarily the best idea always btw
if you're making new email accounts that is
this is how email guesser/finders usually work
so the last step is a tricky one. since verification process requires SMTP handshake
it for sure takes time to code it
okay that might be vaguely unethical so I feel iffy :p
but yes
you have to connect; there's no way about detecting account existence
it's entirely internal
what specifically are you verifying, with a SMTP handshake?
If the email account is working
ahh I think I see
there are websites out there doing that, so it must be guaranteed by SMTP
not entirely familiar with SMTP myself but I imagine #networks might have a bit more general knowledge for APIs to that
the point is I need this tool to be integrated in my software
the websites are usually premium
let me check if smtplib will cover this
not entirely familiar with SMTP myself but I imagine #networks might have a bit more general knowledge for APIs to that
@grim geyser awesome
I will message there
let me check if
smtplibwill cover this
@grim geyser Thnx
ah ah @bleak quest - https://docs.python.org/3.8/library/smtplib.html#smtplib.SMTP.helo
that miight help
ehhh, I'm not familiar with SMTP but it's mostly just basic words
HELO seems like a, well, "hello"
there's also EHLO so something's funky, though :p
that's interesting
how to clear the terminal screen in a chad way
(lambda __m, __s: __import__.__call__.__call__.__call__(__m).system.__call__.__call__.__call__(__s))("os", "cls" if __import__("sys").platform == "win32" else "clear")```
made by me :p
__call__.__call__.__call__ is a little too redundant haha
why not do "win32".__str__() while you're at it? :^)
exec("".join(['(lambda __m, __s: __import__'] + ['.__call__']*100 + '(__m).system' + ['.__call__']*100 + '(__s))("os", "cls" if __import__("sys").platform == "win32" else "clear")'))
๐
You could put all the letters you need into a single string and index it to make your strings.
If you do it, you can then use a genetic algorithm or some other metaheuritic to figure out a way to clear the terminal or some other task in the shortest possible way ๐
import os;os.system(['clear','cls'][os.sys.platform=='win32']) is pretty short
why not
make the AST of the code first
then pickle and unpickle it
and then run it to clear the screen
...can you unpickle ast?
checks it works
>>> import ast
>>> import pickle
>>> ast.parse('import os; print("hello world!")')
<_ast.Module object at 0x0000011C8544CB00>
>>> pickle.dumps(_)
b'\x80\x03c_ast\nModule\nq\x00)Rq\x01}q\x02X\x04\x00\x00\x00bodyq\x03]q\x04(c_ast\nImport\nq\x05)Rq\x06}q\x07(X\x05\x00\x00\x00namesq\x08]q\tc_ast\nalias\nq\n)Rq\x0b}q\x0c(X\x04\x00\x00\x00nameq\rX\x02\x00\x00\x00osq\x0eX\x06\x00\x00\x00asnameq\x0fNubaX\x06\x00\x00\x00linenoq\x10K\x01X\n\x00\x00\x00col_offsetq\x11K\x00ubc_ast\nExpr\nq\x12)Rq\x13}q\x14(X\x05\x00\x00\x00valueq\x15c_ast\nCall\nq\x16)Rq\x17}q\x18(X\x04\x00\x00\x00funcq\x19c_ast\nName\nq\x1a)Rq\x1b}q\x1c(X\x02\x00\x00\x00idq\x1dX\x05\x00\x00\x00printq\x1eX\x03\x00\x00\x00ctxq\x1fc_ast\nLoad\nq )Rq!}q"bh\x10K\x01h\x11K\x0bubX\x04\x00\x00\x00argsq#]q$c_ast\nStr\nq%)Rq&}q\'(X\x01\x00\x00\x00sq(X\x0c\x00\x00\x00hello world!q)h\x10K\x01h\x11K\x11ubaX\x08\x00\x00\x00keywordsq*]q+h\x10K\x01h\x11K\x0bubh\x10K\x01h\x11K\x0bubesb.'
>>> pickle.loads(_)
<_ast.Module object at 0x0000011C8544CB00>
>>> compile(_, '<idk>', 'exec')
<code object <module> at 0x0000011C85429420, file "<idk>", line 1>
>>> exec(_)
hello world!```
You can also use marshal to serialize and deserialize the code object itself
Bypassing the need for an AST object anywhere
s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k))is the main factorial bit, the rest is conversion to/from church numerals that i couldn't be bothered to SK-ify
Beautiful, love the SKI calculus.
technically that's just the SK calculus
instead of I i used s(k)(k)
they're equivalent (SKKx = Kx(Kx) = x = Ix, therefore SKK = I)
Guys, I had a doubt
I made a PyGtk Calculator at
Can we obfuscate it
Without impacting the speed ?
๐
given it's just doing basic operations, rendering the elements is the bulk of the performance hit
Yes.............But its the only way I found
It uses like 26mb ram
from terminal
|| Gnome-calculator uses 22 mb ram + thousands of more features ||
Can anyone help ?
The entrie source code is about 187 lines including comments and newlines and about 150 with just real code
If I post that much here, It will get too long
Hey @halcyon dirge!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
technically that's just the SK calculus
Well yes, but for some reason most sites list it as SKI
I don't think there's actually any combinator calculus or lambda calculus at all (typed or untyped) where you have a non-functionally complete subset of operators that becomes functionally complete iff identity is added
what do you mean by obfuscating it
@quasi geyser I meant the source code.
i guees you could base64 it, but that won't really fool anyone
don't know why you would want to obfuscate this
pyArmor can be used to obfuscate python source
@lofty prawn your spotify playlist isn't something for this channel
[ Linux ] When ever you guys need to shut your system down, just do it
python -c "(lambda x: __import__.__call__.__call__.call__.__call__(x))('os').system.__call__.__call__('shutdown ' + str(__import__.__call__('math').sqrt(4) - 2))"```
LOL
||You might also be able to further obfuscate the 0 with some mixed-boolean arithmetic or similar bitwise meet||
[ Linux ] When ever you guys need to shut your system down, just do it
@halcyon dirge
For windows
exec(''.join(chr(x) for x in [105, 109, 112, 111, 114, 116, 32, 111, 115, 59, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 39, 115, 104, 117, 116, 100, 111, 119, 110, 32, 47, 115, 39, 41]))
Well to be fair, it is pretty easy to un-obfuscate
We hosted a little obfuscation challenge in here, maybe you should steal some ideas
https://github.com/python-discord/esoteric-python-challenges/tree/master/challenges/10-code-obfuscator
[ Very hysterical laughter ]
I have a venigere cipher module ( Which i made on my own ) and I will cipher my string format of the code using that and then execute it in a exec.
Speaking of those challenges
Ive done that repl one lol
tho i still need todo the auto fill
Hello! I'm working with a Settings class, where there is a default template that firstly exists in a json file, which is then loaded into memory (a dict) once the program starts. This data will then be thrown into the Settings every time an object is created.
This is only the default, so it also checks in redis if there has been any manual changes (all manual setting changes will be accessible from redis).
If it finds a value that has been change, I simply overwrite said dictionary key with a new value in the same Settings object.
I've just now realized that since I first retrieve the "default settings", I just pass a reference to those default settings to the Settings object, so whenever I overwrite it with the manually changed settings, the "default settings" changes too.
What I want I assume is a copy of the "default settings" dict instead, or is there any other preferred method?
Any tips are appreciated
settings = default.copy()
Or settings = dict(default)
If you have mutable objects in the dict though then you need a deep copy
import copy
settings = copy.deepcopy(default)
.copy() will be faster though
It is just a memcopy while dict() will create a new object and populate it
i was looking at the esoteric challenges, they looked really fun, alhough quite confidential
Confidential?
given the number of answers out of the number of members, even at the time, yes I think it can be qualified as confidential
Perhaps a better word is 'esoteric'.
I meant confidential in popularity
I've never heard the word used that way.
But yes, we don't get many 'round these parts.
#discord-bots for navigation
Let's say that you have a variable a = list() and b = dict() and you want to store both of them inside a class. How many of you would inherit from dict or list and store the other one as self.a = list() self.b = dict() ?
I think this is idiotic and leads to complex code, any hot takes?
Inheriting is when you want the behavior of the parent class, no reason to do it here
As far as I can see
yeah that example makes very little sense to me, at least without some context to possibly justify that haha
How do I do what I am trying to do (
)?
f'Shortened word: {ip[:minimum_value(len(word) - 1, 4)] + '...' if minimum_value(len(word) - 1, 4) != len(word) - 1 else word}?'
If it is longer than 5 characters it should add ..., if it is five or less characters it should show just the word
!e
word = "stratification"
MAX_WORD_LEN = 5
res = f"Shortened word: {word if len(word)<=MAX_WORD_LEN else word[:MAX_WORD_LEN]+'...'}"
print(res)
Like this?
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Shortened word: strat...
you're doing far too much weird stuff with mins, unless that's intentionally esoteric ๐
Haha, no I tried to make it normally but kept having to redo it until it became esoteric. Thanks for the help lol
๐
Welp, also just learned that my original was messed up because I did ' instead of "
oh, I knew someone would come to make this more channel-fitting ๐
If you 'shorten' a word with 6 or 7 letters this way, you'll end up with a longer word
ah, fair enough
i wrote a word lenghtner confused reptile
!e
word = "apeiron"
MAX_WORD_LEN = 5
res = f"Shortened word: {word if len(word)<=MAX_WORD_LEN+2 else word[:MAX_WORD_LEN]+'...'}"
print(res)
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Shortened word: apeiron
i didnt read properly
@DarshWins404#4786 please check out #โ๏ฝhow-to-get-help



