« first day (4357 days earlier)      last day (816 days later) » 

03:33
that kinda looks like a monad?
 
5 hours later…
08:09
Been trying to bypass this "safe eval", but no luck so far. Turns out it's pretty difficult to be evil when you can't use any names at all
I can do it if I have access to globals, but I doubt anyone would be dumb enough to give me that
Actually never mind, that lets me access the builtins module, but I still can't use any functions from there
08:45
Cbg
08:59
Exciting news: I updated the "What tutorial should I read?" page on the sopython wiki to change "Fluent Python 1st edition and 2nd is in pre-release" to "Fluent Python 2nd edition"
09:31
@RobGrant not approved yet i guess
Does anyone how to make an internal call to an endpoint in django, apart from using requests packages, is there any internal django method that makes a call to it?
ie making call to internal exposed urls internally? url method are wriiten in function way not in class way
10:19
@Aran-Fey you can't even use print...guess you can't import modules either right?
Well, import doesn't work because that's a statement, and __import__ isn't accessible, so... unless you can get a hold of __import__ or importlib.import_module, no
so you basically can't do anything? o-o
Isn't that pretty much the idea behind a safe eval?
11:03
I mean, you could argue that the only true way to make eval "safe" would be to just prevent anything from running inside, but that's not really making it much of an "eval" anymore
incorrectly tagged unclear; PowerShell? stackoverflow.com/questions/73785245/…
been a while I saw you here trippleee, and indeed this is powershell
11:48
That's a neat ostensibly-safe-eval
yeah, and by feeding it blacklisting/whitelisting list, you could have a nice basis for a per context safe eval
So far I've managed to bypass it with getattr and with globals. Both very much meta-programming functions that only a drunk, half-asleep newbie would give you access to
@Aran-Fey but isn't that done outside of the input passed to safe_eval_norecurse? because from what I tried and saw, anything you pass to execute as a string to the function doesn't work, unless you do something outside of that function
Yeah, you need allowed_names={'globals': globals}
Or my good ol' friend allowed_names={'getattr': Tools.scripts.find_recursionlimit.RecursiveBlowup5.__getattr__}
12:46
Cbg people
13:32
@Aran-Fey I'm pretty sure allowed_names is not intended to be a sequence, and that the sandbox is only looking for the use of the names, not replacing their lookup
It's used as the locals namespace, so it has to be a dict: return eval(code, {"builtins": builtins_dict}, allowed_names)
Caught me off guard as well haha. I passed in a list and everything went kaboom
It's certainly not a well written piece of code, that's for sure
but attribute accesses also generate co_names.
oh, it looks like considerable thought was put in, considering the micro-optimizations
I think that's a product of cargo-culting, not thought xD
13:37
nedbatchelder.com/blog/201206/eval_really_is_dangerous.html impressively, Ned is apparently still updating this, as he's checked the constructor for the code type in 3.11
Anonymous
Is there any way to create a decorator that is used to like, register a method to be used in another method?
Anonymous
@register
def function(self):
    pass

def another_function():
    Use all methods that are registrered here.
One possible weakness of this approach is that an entry in allowed_names will allow the key to be used anywhere in the code, even if it does not resolve to the value given. For example, for allowed_names = {"abs": abs}, you would be able to do [1,2,3].abs(). In the majority of cases, this is harmless. None of the objects you can create have a dangerous method whose name matches a seemingly safe global.
@Warcaith Sure, just append the decorated functions to a list or whatever
Anonymous
Could you give me an example? I'm still pretty new to decorators.
13:42
registered = []

def register(func):
    registered.append(func)
    return func
Perhaps you could trick a clueless administrator into providing a large allowed_names dict that maps dangerous method names to harmless stubs. The admin may think this gives you no additional power, when in fact it gives you the keys to the kingdom
@PeterT our codebase is all Python right now, and we're looking to shift suitable portions of our code that bottleneck us into C++ (we have big sequential data processing in loops in some areas).
@Kevin actually that's not a bad idea I can just save standard C-code as a .cpp file and a .c file and see which ones I can get working faster
(Lemme just go to Ned Batchelder's article so I can rummage through his big box of kingdom keys)
It's certainly interesting to see how much different keys can unlock. For example, __class__ + __subclasses__ is essentially a master key
...or is it? Might also need getattr
14:03
As soon as I figure out why ().__class__.__base__ gives a different result than ().__class__.__getattribute__("__base__"), the kingdom will be mine
Simple answer: tuple.__base__ is a class attribute, but tuple.__getattribute__('__base__') looks for an instance attribute
...and you didn't provide an instance
Scary answer: Metaclass and descriptor shenanigans. tuple.__base__ is equivalent to vars(type)['__base__'].__get__(tuple)
#Ok, so if I go up one layer...
>>> ().__class__.__class__.__getattribute__(().__class__, "__base__")
<class 'object'>
There we go. I think?
Yeah, that also works
Hacking is educational
... But since the purpose of my real code is to access things using only the attribute __getattribute__, it's not useful to have a solution that requires two usages of thing.__class__
I've been wondering if there are any neat ways to get a hold of type and/or object
I don't think there's much you can do with just .__getattribute__, unless you somehow get to object.__getattribute__, then you're golden
14:18
().__class__.__class__ gets you type, but it's not useful for my attack vector
@PM2Ring Nice! I'm impressed she's playing what appears to be a variant of a lap steel guitar standing up!
Susan Tedeschi's voice is unrivaled.
I decided to rummage through the kingdom key bin for an easier key. I found one. (lambda: 1).__builtins__. Easy enough to get that using only one particular attribute name. Here's an example that imports os inside the ostensibly safe sandbox and prints the contents of your current working directory. pastebin.com/raw/se3RLMXe
Of course, we're still assuming that the person in charge of allowed_names is cluelessly putting dangerous things in it. But the minimum required cluelessness is lower now than it was before, when we were hoping they'd add {"__import__": __import__} or what have you.
Oh, that's clever. Creating a function and grabbing the builtins from there didn't occur to me!
Turns out that little bug in the implementation is useful after all!
(The correct code would be eval(code, {"__builtins__": builtins_dict}, allowed_names))
14:36
Possibly one of Ned's kingdom keys would let you get to __builtins__ even then, but I'm not inclined to comb through them to find one that isn't prone to the descriptor weirdness I encountered in my previous approach.
If allowed_names is an empty dict, breaking out becomes much harder. I'm not prepared to declare it completely impossible, because there's quite a bit of internal code you can invoke just with literals and syntactical elements that might trigger dunder methods.
maybe f(**my_specially_constructed_dict) will call __getattribute__ for us in some convenient way, I don't know
Anonymous
14:50
Anyway to force a decorator to be used inside a specific class?
Anonymous
15:01
Or is there any way to enforce the method that uses the decorator to have specific arguments?
I mean, if you call the method and it doesn't have those arguments, then it'll crash, right? Isn't that enough enforcement?
Anonymous
Yes, it is, sorry. Is there anyway to make it so PyCharm can autocomplete these arguments?
Anonymous
Just want to help our developers to understand the decorators a bit more :)
Wait, does your decorator change the signature (parameters) of the decorated function?
@Warcaith You can use typing's ParamSpec to define how the decorator and method/function arguments relate.
Not sure if PyCharm already understands those...
Anonymous
15:05
@decorator_that_passes_arguments_into_a_method
def a_method():
    pass

^ Crash

@decorator_that_passes_arguments_(a_b)_into_a_method
def a_method(a, b):
    pass

^ No crash
Anonymous
I'll look into that Miyagi! :)
If you're looking at specific arguments known ahead of time, then Callable or Protocol are enough.
import inspect
def foo(func):
    if len(inspect.getfullargspec(func).args) != 2:
        raise ValueError("Can only decorate functions with exactly two arguments")
    #todo: decide what to do with keyword args and varargs, etc etc
    return func

@foo
def bar(a,b):
    return a + b
#works

@foo
def qux():
    return "idk"
#crashes, as desired
re: "enforce the method that uses the decorator to have specific arguments"
15:41
https://stackoverflow.com/questions/73789193

I'm confused by OP's confusion. It appears as though the question is: "if I write `while not x:`, why doesn't the value of `x` change?" Or else it's something *so* confused that it can't even be properly expressed in English.
@KarlKnechtel I think they are confused by missing that while exists when its target is false.
So while not exists when its target is true, but the "double negation" trips them.
*"exists" => "exits"
16:00
stackoverflow.com/questions/30151234 just got a new answer, is a blatant homework question with no actual question from the user
@MisterMiyagi ah, so this is just K-12 education failing to teach elementary logic again.
(I also have no idea what the tomato "turningscraft" is)
Possibly turingscraft.com, but no need to fret too much over the mystery
I do have sympathy for any student having to deal with a temperamental automatic grading system. 'Your answer was: "4". That is incorrect. The correct answer is: "4"'
Since buggy graders are inscrutable, and doubly so if we don't even know the name of the grading software, I thusforth cast my vote of "can't be reproduced"
Anonymous
16:37
@Aran-Fey This won't work:

registered = []

def register(func):
    registered.append(func)
    return func
Anonymous
I need to run the method before it gets registered.
Anonymous
I need a way to run all methods with a specific decorator
Anonymous
Thanks for the help anyway!
"I need to run the method before it gets registered." Why?
If you need to do something with a function after you define it but before some event X, then you should not be using a decorator to cause event X
May as well go to a car factory and tell them "I need to drive the car before it gets put together"
Anonymous
So what if I need a way for a developer to mark a method "A" to be executed when the method "B" is executed?
Anonymous
16:45
class AClass:
    def run():
         # Run all methods marked with "@something"

     @something
     def a_method():
          pass

     @something
     def b_method():
          pass
Anonymous
I get what you mean and it seems odd using a decorator.
Anonymous
But I need a functionality like this :p
If method a must always be executed immediately after method b finishes executing, simply call a() while you're inside b. If a needs to be called eventually, but not necessarily immediately, then you've got options
async and Promises, etc, seem to be trendy these days for not-quite-linear modes of execution
or you could just cache the state of each method (eg: executed or not, etc) in order, inside a dict/list, and check that
Anonymous
No, I just want to register all methods marked with "@something" and run them inside "run()" method.

class AClass:
    def run():
         # Run all methods marked with "@something"

class BClass(AClass):
     @something
     def a_method():
          pass

     @something
     def b_method():
          pass
16:49
On the less fancy side you could keep a variable call_these_eventually = [], and once "eventually" arrives, you iterate through it and call each element
@Warcaith Ok, a reasonable goal. Aran-Fey's suggestion would probably work there.
Anonymous
Really?

registered = []

def register(func):
    registered.append(func)
    return func
Anonymous
This does only execute when the functions are executed, or am I wrong?
register will call once for each time you do @register. Nothing will happen with register or registered when the functions are executed.
Anonymous
Ooh, that's a special kind of decorator.
If you want something to happen with registered, you'll need to do it yourself. For example, maybe inside AClass.run, you'd like to do for func in registered: func()
Anonymous
16:54
I'm used to have a wrapper inside and everything
Anonymous
I'll try that
Anonymous
2
Q: Python Register Class Methods with a Decorator and Inheritance

user5038859How do I register class methods with a decorator and use inheritance at the same time. I've found a lot of semi-helpful posts/tutorials online, however, I haven't been able to find exactly what I'm looking for. In the process, I think I've confused myself (class decorators vs metaclasses). Here...

Anonymous
This is what I needed.
Anonymous
:p
"special kind of decorator" is... Debatable. Your typical bread-n-butter decorator usually has one def inside another def, and Aran-Fey's doesn't. So, yeah, it's special in that way. But from Python's perspective, it doesn't notice anything unusual. One def or two, all it cares about is whether it's callable.
It can be helpful to know how "magical" a language feature is, in the sense of how much special logic the engine needs to handle it. zero-argument super() is a nine on the scale. Descriptors are six. Decorators are one. They're about as magical as the "+" operator.
In almost all cases, @foobar <newline> def zort(): whatever is identical to def zort(): whatever <newline> zort = foobar(zort)
Anonymous
17:05
Aaah, I see.
Anonymous
Thanks for the explaination, it makes decorators a bit more understandable.
Anonymous
Could you perhaps show an example how this would work in practice?
Anonymous
registered = []

def register(func):
    registered.append(func)
    return func
Anonymous
I'm still misunderstanding something
Anonymous
:|
17:06
If inheritance is involved, it's probably easier to "tag" the decorated methods instead of appending them to a list
As payment for listening to my boring lecture, I will make a small example
Anonymous
@Aran-Fey Inheritance is involved. How do you mean?
def register(func):
    func.__registered = True
    return func

def run_registered_functions_in_class(cls):
    for func in vars(cls).values():
        if getattr(func, '__registered', False):
            func()
Anonymous
@Kevin Haha, awesome, I really appreciate all of your help!
You can also extend that to loop over every cls in cls.__mro__ or whatever you want
Anonymous
@Aran-Fey This looks really cool. I'll try this right now. Isn't there any rule breaking to the python coding convention using double underscore btw?
Doesn't Flask do something like this?
Anonymous
@0x263A I think so, as I've seen it somewhere else :p
Anonymous
@Kevin Thank you, I'll try this too!
17:11
There's no name mangling here though, since the code isn't in a class
@Warcaith You shouldn't use __dunder__ names, but __private names are fair game
See also docs.python.org/3/reference/… for a listing of "special" variable names. There aren't many.
Anonymous
@Aran-Fey This doesn't work inside class, with "self" instead of "cls", or am I wrong?
Now, as for whether a particular name is stylistically valid, that's a whole other can of worms
@Warcaith Well, then you need to figure out which class you want to operate on. type(self)? __class__?
Anonymous
Aaah, true!
Anonymous
17:14
Wooooo
Probably cleaner to use a WeakSet btw
registered = weakref.WeakSet()

def register(func):
    registered.add(func)
    return func
Anonymous
It works now. That's kind of cool!
If you're trying to register instance methods, that's an extra complication. What should call_all_registered_functions do if I have a class Fred with a registered method, and I have created ten Fred instances? Should it call all ten of them? Call just the first Fred's method? What if I have zero Freds?
Anonymous
Weakref, hmm.. need to read something about that I think! :p
Anonymous
:55256001 True, but this does however work:

for func in vars(type(self)).values():
    if getattr(func, "__registered", False):
        print("Works")
Anonymous
17:17
@Aran-Fey Sooo, to the final question.. any chance I could have the "registered" variable belong inside the class that the @register decorators are used? ;)
I don't really know what you're trying to do, but if you know, then all is well
Anonymous
Like..

class AClass:
registered = weakref. WeakSet()
Anonymous
I'm building a TestSuite and every "register" method is actually called "@testcase". I don't want to do as other test frameworks where you are required to for example use "test_" before each method to make it act as a test.
trying to access a registered object that belongs to the same class as the method whose decorator is halfway done executing... Tricky. Name resolution inside classes is at least a four on the magic scale.
Anonymous
Haha!
17:20
@Warcaith Nope
Anonymous
@Aran-Fey This does however make it so no other subclasses can see the "registered" methods.
Anonymous
Ops
Anonymous
I mean this
Anonymous
def register(func):
    func.__registered = True
    return func

def run_registered_functions_in_class(cls):
    for func in vars(cls).values():
        if getattr(func, '__registered', False):
            func()
Anonymous
Doesn't all subclasses use the same set when using:

registered = weakref.WeakSet()

def register(func):
    registered.add(func)
    return func
17:22
Yeah, they all use the same set. Is that a problem?
Anonymous
Oh, not really actually. It would be a problem if the set was using the actual name of the methods, but I guess it adds the pointer to the method?
class A:
    b = 10
    #works:
    c = b + 5
    #works:
    d = [x+6 for x in range(b)]
    #fails:
    e = [b+x for x in range(15)]
It adds the actual method to the set. What's a pointer? ;P
Love that name resolution magic
Anonymous
@Aran-Fey I'm C++ damaged, sorry.
Anonymous
17:25
Does the weakset make it so the references to the methods are removed as soon the class is destroyed?
To restate things in pointer-free terms, a set can contain two functions that have the same name, without considering them duplicates.
And a WeakSet follows that same rule as well, natch
Well. Strictly speaking, the method is removed from the set when the last reference to the method is dropped. But yeah, that almost always means that the class was destroyed
Anonymous
Alright, but this is great and exactly what I need. WeakRef is really cool, very much like shared_ptr in C++, which I like.. ;)
I speculate that WeakRefs can't make your program more powerful, they can only make it more memory efficient
Anonymous
Yeah, true, but that is actually pretty important as the test can tend to get a bit heavy.
17:34
Valid
Anonymous
17:48
@Aran-Fey I got one problem, which is that I need to know which functions belongs to which class now.
Anonymous
registered = weakref.WeakSet() is a combination of all classes now
You get a function as input and need to find out which class that belongs to?
Anonymous
Your other solution (func.__registered) does work, but not as nice and clean as the other one.
Anonymous
Yes. I know I could use .__class__
Or you get a class as input and need to find out which functions belong there?
Anonymous
17:50
Should I store it as a tuple perhaps?
Anonymous
(Class, Function)
Anonymous
1 sec
Anonymous
registered = weakref.WeakSet()

def register(func):
    registered.add(func)
    return func

class A:
    @register
    def a():
         pass

class B:
    @register
    def b():
         pass
Anonymous
The set has references to both a() and b() here.
Anonymous
But I need to be able to separate them out, so I don't try to run a method from another class :p
17:52
That's what the run_registered_functions_in_class function is for
def run_registered_functions_in_class(cls):
    for func in vars(cls).values():
        if func in registered:
            func()
Anonymous
Oh, right, I didn't add that when you showed me the other solutions with weakrefs :P
Anonymous
Am I wrong, or doesn't this also delete the memory whenever the class with all registered methods are destroyed?


def register(func):
    func.__registered = True
    return func

def run_registered_functions_in_class(cls):
    for func in vars(cls).values():
        if getattr(func, '__registered', False):
            func()
Anonymous
I like it a bit more, as I don't need to have a global "registered" variable.
Anonymous
But there are maybe downsides to this approach.
Eh, it doesn't really matter
Anonymous
18:01
But heeey, I'm interested in why you preferred the second one! ;D
Adding new attributes to objects always feels a bit dodgy because you never know what other madmen exist out there who do the same thing, and there's a chance that the attribute name you picked isn't unique
Anonymous
That's completely true. You kind of secure yourself from that by using the other approach.
Anonymous
The func.__registered does not work inside class, with vars(type(self)).
Anonymous
I need to look into it a bit more
Anonymous
Interested in seeing how it would work
Anonymous
18:14
Oooh
Anonymous
.values()!
Anonymous
:p
18:51
@Aran-Fey Namespaces are a honking great idea - let's do more of those!
I'm honestly not sure which one of the two solutions that's supposed to support :P
I'd love to use namespaces, as soon as e = [b+x for x in range(15)] is syntactically valid in a class body
<nitpick>It is syntactically valid!</nitpick>
Nitpick accepted
Much to my surprise, the silly lambda calculus math I played around with all month, turns out to have a practical application. Namely, rewriting lambda expressions so they don't use lambdas, which may resolve some namespace curiosities
class A:
    b = 10
    #fails
    c = lambda x: x+b
    #works
    d = b.__add__

print(A.c(1)) #NameError: name 'b' is not defined
print(A.d(1)) #11
An unimpressive example, but it illustrates what I mean. You can also eliminate lambdas from much more complicated expressions.
 
1 hour later…
20:15
@PM2Ring ty for the pings... because listening to a lot like of music.youtube.com/watch?v=5s-k8Q_40cA lately
20:28
I know it's pretty vague but... I started using Pycharm, my code works fine when I run on Windows command line and it is also running fine on Pycharm after configuring the run configurations. However, Pycharm is accusing plenty import errors "Unresolved reference...". Has anyone ever dealt with this? Weird that it accuses errors though it still works just fine
Have you modified your PYTHONPATH? That might be it
user19876853
Hello everybody. I am new, can I ask a question about Natural Language Generation (NLG)? I just need an answer with "yes" or "no".
Yes or no.
Proving once again that natural language is hard
user19876853
A Template-based or Rule-Based NLG can also be called an NLG system if:

owns all the various stages of NLG work (including grammar and Morphological Realization), but does not have Syntactic Realization because there are templates (dynamic or fixed) and of course you all know how templates work?

That way, will I still have an NLG system (albeit a very poor and simple one) or will it just be sophisticated if/else software?
20:36
I could be wrong, but I don't think we have any natural language processing people in this room
user19876853
I wanted to give it a try, considering NLG is used a lot with Python. Do you know where I can ask?
No idea, sorry
user19876853
Thanks :)
Just saw your suggestion now @Aran-Fey, that wasn't it. I figured it out, apparently you have to set every directory you import from as "Sources root". That made the "errors" go away and code still works
21:01
howdy folks! It's been a while. How's everyone doing?
absolutely hyped \o
what's hype-worthy? (... hype-notic?)
the colleagues, at the moment
21:44
Sep 2, 2021 at 21:55, by PM 2Ring
Susan Tedeschi has a fairly gravelly voice, but she can still manage to produce some powerful clear notes. Here's a recent performance of a song she wrote over 20 years ago, Just Won't Burn. She isn't quite as fast on the guitar as some players, but I love the emotion she puts into her playing.
Another one of my favourites from Susan is Whiskey Legs
Aug 15, 2015 at 14:30, by PM 2Ring
Hi, @JRichardSnape. I don't know if I've posted this one before, but I think you'll like it. The Susan Tedeschi band playing John Prine's Angel From Montgomery (with a little bit of Sugaree), featuring some very tasty violin work by Jason Crosby.
@0x263A The stand-up laptop (or whatever it's called) is pretty unusual. She's only had that one for a couple of months. Here she's playing her old one, covering Peter Gabriel's Sledgehammer. Megan also has a Dobro, which you can see in old Lovell Sisters videos.
22:45
The Planned service interruption will impact all Stack Overflow & Stack Exchange sites, Stack Overflow for Teams (free/basic/business tiers), and Chat. — AMtwo 26 mins ago
23:04
@JonClements That's beautiful, but it's just a bit too sad for me right now.
@PM2Ring yeah... how are you?
Bit of a more upbeat... music.youtube.com/…
23:20
@JonClements My house mate for the past 5 years died of cancer a couple of weeks ago. He was my closest friend: we met in 1980. He was in a lot of pain for the last few months, but he died peacefully in his sleep, at home, in the arms of the woman he loved.
So I'm a bit melancholy at the moment, and don't have a lot of motivation.
I'm sorry I didn't know. I'm scared to ask how everyone is.
for what it matters hugs.
He had a lot of friends. He was a great musician, and loved to jam with people. His family is Jewish, and the Jewish traditions around death are very supportive.
I'm not aware of a Jewish funeral... I do my best to try to be aware of all but forgotten that one
Thanks. I appreciate it.
I'm not of any belief
23:27
After the funeral, they have Shiva, where family & friends gather at the house every night for a week.
so it becomes a a house passing as well?
@PM2Ring My condolences.
@JonClements Yep. Each evening starts with prayers, and then people reminisce. It can be sad, but it's also a celebration of the person's life.
His dad's a pretty amazing guy. He's in his early 90s. He was born in Poland, and worked as a child slave for the Nazis in the notorious concentration camp, Auschwitz.
@PM2Ring while the're no religious attachment - I do wonder if it's the same reason we kept the front door open for a few days
and you could chit chat
and the family members had her in the room at the funeral place
so they they could visit her being dead but dressed up nicely
I spent nearly 40 minutes just chatting away
23:43
@Max_98 You might try ai.stackexchange.com, if I understand the problem correctly.
anyway - getting emotional... see you sooner rather than later @PM2Ring
@Kevin This is only a problem if you are hoping to find b within the class. Python isn't designed for that kind of "static initialization", yeah.
Here's my friend Manny & his girlfriend Aviva, playing some improvised World Music, recorded in our loungeroom. youtu.be/PPtnQ39CHeA
@PM2Ring sorry - feels wrong for me
my favourite today is youtube.com/watch?v=6xN3hbJG2tc

« first day (4357 days earlier)      last day (816 days later) »