« first day (3232 days earlier)      last day (1714 days later) » 
01:00 - 16:0016:00 - 22:00

4:00 PM
The documentation of exec() and locals() makes it perfectly clear that this kind of thing should not be attempted, and demons might fly out of your nose if you try anyway. But I still want to know why it does what it does.
 
wim
@ParitoshSingh The other Kevin showed me this doozy
 
...must ...not ...get ...distracted
 
wim
myvars = {"var": 123}

def func():
    class Bleh:
        locals().update(myvars)
        print(var)

func()
(ab)using the invisible class namespace - actually works!
 
So, I have a .py file say A.py with a class classA and method metA.
In A.py I also import another B.py having its own classB and metB.
Now, I want to run a metA in one of metB, noting that A.py is not imported in B.py
Make sense?
Is it possible?
 
name resolution inside class definitions have some triple-wacky interactions. I think we've got a Riddle predicated on the concept.
 
4:01 PM
@EJay Can you tell us why not to import it?
 
@EJay If you want to use it, you have to import it.
 
you can also import something from C.py that imports B.py and returns a classB :)
 
I agree that if you want to use it by name, you have to import it. But perhaps you could pass the function as an argument to the other function.
 
A.py runs the mainloop of my tkinter window. B.py just has some other methods I prefer to keep seperately
@AndrasDeak
 
you can edit/delete chat messages for 2 minutes
Why does importing B.py mean it's not "kept separately"?
 
wim
4:03 PM
@piRSquared that's funny because the NameError: name 'z' is not defined is triggered exactly by adding the line where the name z is getting defined
 
Yes, that is an option
But is there another way please
 
C:\Users\Kevin\Desktop>type a.py
def metA():
    print("Hello, I'm metA")

C:\Users\Kevin\Desktop>type b.py
def metB(func):
    print("metB is about to call func...")
    func()
    print("metB has called func.")

C:\Users\Kevin\Desktop>type main.py
import a
import b
b.metB(a.metA)

C:\Users\Kevin\Desktop>main.py
metB is about to call func...
Hello, I'm metA
metB has called func.
 
def h():
    myvars = {}
    exec("z=1", myvars)
    exec("print(z)", myvars)
    return
    z = 2

h()  # 1
 
@Kevin because the issue with passing it as an argument is that I want to call the metA at the time metB is also being called
If i do so as an argument I can't tell
 
Well, in my code metA is being called inside metB, so one could argue that they're running at the same time.
 
4:06 PM
@EJay I have a very strong feeling you have an XY problem. Is it possible for you to show (a small) example where importing doesn't work for you?
 
wim
related questions: [Give function defaults arguments from a dictionary in Python](https://stackoverflow.com/q/57592380/674039)
and (mine): [How to convert this Python 2.7 code to Python 3?](https://stackoverflow.com/q/57595351/674039)
 
Getting two functions to run truly simultaneously is a bit hard to do in Python, thanks to the Global Interpreter Lock
 
wim
hmm, why my shortlinks didn't work
 
@wim newline
 
wim
chat markdown you're forever a mystery
 
4:07 PM
Multiline is the worst. Either all code, or all quote, or mostly text with some markdown, mostly auto-links for URLs
 
I, too, am annoyed by the baffling nature of multiline markdown
 
@AndrasDeak it may be difficult
it won't really make sense out of context
 
Or can you perhaps explain how importing breaks for you?
 
Not baffling in the sense of "how does it work?" but in the sense of "why does it work this way?"
 
So, in one file I have:
 
wim
4:10 PM
interesting to see that OP accepted the one low-voted answer which rightly says "no, can't do that in Python" rather than the five answers that show how to do something else entirely
 
I think it's a perfectly valid design to have one module for your GUI stuff, and one module for your non-GUI stuff, and to not let the non-GUI module import the GUI module. But it's unclear to me why you can't have a third module that imports them both, or have the GUI module import the non-GUI module, or do something dispatchy like my sample code does, or some combination of all of these
 
class app_win(object):
def __init__(self):
# Create window instance
. . .

def _status_out(self, *args):
a = datetime.datetime.now().strftime("%H.%M.%S")
for value in args:
# print(str(a) + ': ' + str(value))
self.statusWin.config(fg='sky blue')
self.statusWin.insert(tk.END, str(a) + ': ')
self.statusWin.config(fg='black')
self.statusWin.insert(tk.END, str(value) + '\n')
self.statusWin.see(tk.END)


App_Win = app_win()
App_Win.win.mainloop
called that A.py
 
@wim well, I've had an OP unupvote my answer when I rejected their superflouos edit to my answer :D
 
In B.py I want:
 
App_Win.win.mainloop doesn't do anything, incidentally. You would need App_Win.win.mainloop() to actually execute the mainloop.
If you're thinking "but then my program will pause indefinitely right after I import a in the main program", you're right. The fact that mainloop runs forever is a frequent frustration for tkinter users.
 
4:13 PM
pretty sure that applies to (inexperienced) users of any GUI framework
 
class option_win(object):
def __init__(self):
# Create window instance
...

def _save(self):
cfg.gams['path'] = self.gep_value.get()
_status_out('Print me') # <<<<----------- ie. method from A.py
 
"How do I run other code while my mainloop is running?" is a question that has many solutions, and most of them are a pain in the butt
 
@Aran-Fey and that I am
 
I have multiple issues with that design
 
@Kevin I could do that. Import both and then call on the methods from each
I'd try that
Apologies for the code structure in previous message
 
@Code-Apprentice Yea, my bad!
 
wim
oh man, I just accidentally opened a stack overflow question on another browser without all my scripts and ad-blockers (and not signed in to my account). the site looks like hell!
 
Do you care for some private Q&A? Jobs? Solutions? Enterprise? ...What public questions?
 
wim
4:33 PM
exactly... crap everywhere
kinda bummer the company took investor money and had to go down the "enterprisey" route instead of a wikipedia-like donation based model
 
@wim Nice! It's so bizzare all in all though.
also recbg
Hm, I wonder if i should dare take a look at SO without an adblock
 
Don't, you can't unsee it!
 
Mistakes were made...
Yeah, i really prefer websites without Ads. At this point, it just looks like noise to me.
 
that's also why they don't read close banners and the help center
 
Yep, and that's a problem. Saw that blog post though, attempting to make changes to it.
 
4:44 PM
fingers crossed, breath not held
 
(whether it's misguided or not remains to be seen. I really don't get why they would think it's important to show who closed it to the OP and hide it from others. Sounds like the opposite of what it should be if anything).
The colour palette was much better though, so that should hopefully help.
imo.
 
@ParitoshSingh Indeed. The idea is probably that there's no "public shaming" this way, but the people being hurt by their questions getting closed are typically not the kind of users who realize that others see a different banner.
 
Aye. I wonder if they'd decide against involving the meta for feedback on this one.
Either ways though, On the whole I still see it as an improvement, so at this point i'd take it one way or another.
I do hope we get a feedback thread on it though.
 
wim
seems like rearranging the deck chairs on the titanic to me
 
5:01 PM
rbrb
 
@wim I'm not sure about that. Their core motivator for some pretty bad decisions was noob attrition. If these changes can help moderation not come across as so "harsh" to many users then they might reach their goals without having to do stupid things like meddling with moderation itself.
 
5:13 PM
@JonClements what was going on here (I am talking about the deleted answers.. -_-) just curious..
 
I'd made a "fan"...
 
ha ha okay.. got it
 
763 characters of "fan mail", wow, that person must've really been into it
 
people have so much time to express "fan"-ship .. -_- how "practical"
 
redaction wasn't a thing then... so dev's/CM's had to get involved on what can't be seen on some of those posts... :)
 
5:20 PM
Ahhh...
 
5:30 PM
Sometimes I forget just how terrible people are at asking questions, and then I'm reminded of the sad truth by some dude who tagged his "how do I read a file in python" question with python-2.7 and spyder and nothing else
It's obvious I spent 5 minutes on SO again today, isn't it. Time to hit Ctrl+W.
 
5:45 PM
Nice
I love that literally all you have to do is a) type that question into google, or b) click on any of the links that show up under the title of your question
 
Continuing my investigation of the locals() mystery... Has anyone been able to come up with a code snippet where assigning to locals() actually does update the value?
 
just read the dozens of SO answers suggesting exactly that :>
 
interesting. Locals seems to just be a view
If it's a mutable type you can muck with it
 
Well if I've learned anything from the movie Déjà Vu it's that views can affect what you're looking at.
 
Oh that's interesting
@Kevin Yup!
 
5:50 PM
I'm looking at Objects/frameobject.c:PyFrame_FastToLocalsWithError (line 916) and I'm pretty sure it's responsible for turning the internal locals map into a palatable Python dictionary when you call locals()
 
x = 3
locals()['x'] = 99
print(x)
as long as locals() isn't in a function
or probably in a scope
 
i.e. as long as locals() is globals()
 
yep
just did print(locals() is globals())
 
Ok, that's worth looking into, but that executes a code path other than the one I'm interested in. I don't suppose you've got a snippet that works from within a function...
 
The one that Wim hinted at
def func():
    class Bleh:
        locals()['x'] = 5
        print(x)

func() #5
 
5:57 PM
I know that you can do

def func():
    def func2():
        print(x)
    func2.__globals__['x'] = 5
    func2()

func()  # prints 5
 
Dang, I can't inspect the frame data of a class as easily as I can a function...
 
so, perhaps __locals__ work like that __globals__, and works with classes as well?
 
globals is just globals.
 
"Sometimes a cigar is just a cigar globals is just globals"
 
6:13 PM
I'm pretty flummoxed but I think it has something to do with the fact that frameobject.c's map_to_dict says, "If values[i] is NULL, the variable is deleted from dict" which suggests a possible mechanism for a name to vanish from the dictionary if it wasn't initially put there in an "official" way
 
wim
I wonder why CPython made locals() return a plain old dict instance, instead of a MappingProxyType or something similar that would blow up if you try to write in it, instead of silently failing to do the thing
There was precedent already in os.environ, which returns a not-really-a-dict-but-quacks-like-a-dict thing
wouldn't it be nicer if it returned a dict when you could write to it safely (e.g. when it's globals) and returned an immutable view when you couldn't write to it safely?
 
definitely would
 
Maybe they want to leave the specification open so that some non-CPython implementation can make their local variables reflect changes made to the locals() dict. Specifying "this dict must not be modified" denies other implementations the right to do have modifiable locals(), unlike specifying "modifying this dict will almost certainly not work"
But I guess that doesn't totally explain the decision because even if the docs say "locals() returns a dictionary that probably isn't modifiable in a useful way" then the CPython implementation could still return a subclass of dict that's read-only
Unless it's too flagrant of a violation of liskov's substitution principle to make an immutable dict class that inherits from dict
 
@wim don't forget that vars() is also hanging around in the background... quite often seen that one forgotten
 
6:41 PM
@Kevin It doesn't have to inherit from dict, as long as it conforms to collections.abc.Mapping? But IIRC locals() was always documented as writable, but with no guarantee the changes will affect the local namespace. Which when you think how locals are implemented makes sense.
IN fact, how does one create a local variable dynamically? I was under the impression stack frames were predictable in size once a function was compiled, but that's not solid knowledge.
 
I think you're right about stack frames having a predictable size. include/frameobject.h indicates that member f_localsplus is dynamically sized, but it's only dynamic in the sense that it's allocated during PyFrame_New, after which point it will no longer change. (I am 75% sure of this)
 
Right. This makes sense to me because locals are identified by a number, which I believe represents their offset in a reference vector, and locals are identified by the detection of bindings during static code analysis.
 
Yeah.
I'm still pretty fuzzy about where said reference vector lives. I think it's in f_localsplus, but my C powers are not strong enough to convince myself for sure
 
6:58 PM
@Kevin in 3.7 the dict returned by locals() is a copy of the locals. it is not a view. that would at least make it useful for passing directly into exec and friends, which are supposed to modify their "locals" dict.
 
Partially agree, depending on our definition of "a copy of the locals". PyFrame_FastToLocalsWithError mutates f->f_locals in-place in all but one code branch. So most of the time, I would expect multiple calls to locals() in the same scope to return the same reference to the same dict.
But one might argue that f->f_locals is the copy of the "real" locals, which live somewhere in f_localsplus. The fact that f_locals' position in memory never changes doesn't have any bearing on this fact.
Or, hmm, maybe it's wrong to say that all real locals live in f_localsplus. If that were the case, then modifying f_locals anywhere in the CPython code would be as likely to succeed as the user doing locals()["x"] = 1. So I must be missing parts of this puzzle.
 
7:16 PM
@Kevin why is that? modifying locals() or f_locals affects the dict copy in my tests. But calling locals() has the side-effect of refreshing f_locals.
 
For instance, STORE_NAME stores the value in f_locals rather than f_localsplus
Currently trying to produce a function that uses the STORE_NAME opcode... This is harder than it looks
 
7:35 PM
And what about fastlocals? The LOAD_FAST opcode implementation starts with setting value to GETLOCAL(oparg), which macro expands to fastlocals[oparg]. So it looks like that's the vector, but it may not be visible in Python.
 
My guess is that fast locals live in f_localsplus and slow locals live in f_locals
I haven't yet been able to create a slow local because all my functions compile to store_fast or store_deref or basically anything other than store_name. But in principle I'm pretty sure slow locals exist
 
7:53 PM
Hmm, I notice names bound within a class definition use STORE_NAME. How very coincidental that the only time we've been able to write to locals() is when we were in a class.
 
8:04 PM
fastlocals always gets assigned from f->f_localsplus - so yes, that's where the function locals live
 
How long is the ping time window after someone leaves chat?
I've found obscure answers of "some time". I'm not really curious for some definitive post, just either anecdotal timings or maybe if someone stumbled over a post one day and mentally noted it
 
A week or two.
And if you ever talked there and go back it restarts, I think. And directed replies always work.
 
Sounds about right. I read this job ad and all that flashed in front of me was jgreenwell's name as kryptonite :P His last ping was on the 9th.
 
8:21 PM
If the UI doesn't offer him he's not pingable.
 
Ah well, it was only a bit of a joke anyway
@WayneWerner I reconsidered our conversation last night and I had a wonky line of thought. It's not a job for the ORM layer, I should drop down to core. What I wanted isn't unreasonable from a query, but it doesn't fit the ORM pattern. Thanks for your patience.
^ closed, thanks
 
8:45 PM
@roganjosh Yeah, that's a thing that you've gotta wrap your head around with sqlalchemy
the difference between ORM and core
both are valid, both are useful
just sometimes you don't want ORM
a project I was working on used the core to define the tables, and then built the ORM on top of that
so it was possible to use both approaches, whichever one was more appropriate
 
You're absolutely right. I've recently been transfixed with ORM and it was obvious that I should be able to get what I wanted through some method.
Guess there's a reason that my searches never worked :P
 
9:11 PM
@Kevin Technically wouldn't those STORE_NAMEs be binding in the class namespace? Locals doesn't even exist until a function/method is called.
 
wim
puzzle: shortest string for which re.compile(s) fails
ugh
 
One character
 
wim
spoiler button has a bug and corrupted my input :(
 
Wondered about that.
 
either way, one character is enough
 
wim
9:24 PM
yes, there are multiple solutions though
 
01:00 - 16:0016:00 - 22:00

« first day (3232 days earlier)      last day (1714 days later) »