Is it possible emulate pointer behaviour in python so as to write a "safe" function def assign(var, fn): exec("global {}; {} = {}".format(var, var, repr(fn())))?
Short of doing unholy things using CPython's undocumented behavior, I don't think it's possible to do it exactly as you have described.
I was about to say 'But if we relax the constraints to "is it possible to create a variable in the local scope, given a string representing its name, and a value?", then you can just do locals()[name] = value', but now that I try it out, it doesn't work. I guess this is why they say you should treat locals() as read-only.
>>> def f():
... locals()["bar"] = 42
... print(locals())
... print(bar)
...
>>> f()
{'bar': 42}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in f
NameError: global name 'bar' is not defined
I wish to set arbitrary variable to some default value, then wrap a cpu-costly function in a wrapper which puts the return value into a queue, have a thread in the original process wait for the queue to receive that value and update the original variable with that value
Basically fn() would run in multiprocessing.Process
I suspect it's doing name resolution at compile-to-bytecode time. It doesn't see any name "bar", so it doesn't even bother looking in the local scope at runtime.
Actually, hmm, if that were the case, then I'd expect exec to fail with the same error, but it actually works...
For locals() doc says NOTE: Whether or not updates to this dictionary will affect name lookups in the local scope and vice-versa is *implementation dependent* and not covered by any backwards compatibility guarantees.
@Mirac7 I think you should just use a mutable object.
Pass a list* in to the expensive function, and append the return value to that list at the end of the expensive function. The original thread can then see the new contents of the list
@Mirac7 That documentation does not imply that locals() should work in local scope, no. It's saying that you can't depend on updates to do anything, in any circumstance.
Is it something like "I'm periodically running code in the main thread which partially depends on the return value of the cpu-costly function, but it can also operate without it, albeit less effectively. So the code runs whether or not the cpu-costly function has finished executing, and it uses the variable's default value when the cpu-costly function's return value isn't available yet." (con'td)
"I want the cpu-costly function to seamlessly update the variable without the periodic code having to do anything on its end"?
If you're thinking "no, the periodic code depends completely on the cpu-costly function, and so it shouldn't ever run until the cpu-costly function returns", then you don't need seamless variable assignment at all. You just need to make the periodic code do my_variable = results_queue.get() and it will happily wait for the cpu-costly function to finish
Did a little googling to see if there's an idiomatic solution for this but all I could find was stackoverflow.com/questions/15668591/… which just suggests the approaches we already thought of: use a mutable object such as a list or a custom class with set() capabilities
@Mirac7 I haven't paid close attention to what you're doing, but when you do weird stuff to try and make Python behave like some other language, then you're probably Doing It Wrong.
TFW your set and dict code out-performs the code of the core dev who was a major contributor to setobject.c and dictobject.c (under certain conditions) stackoverflow.com/a/42674001/4014959
@Kevin Sure, I've only done a tiny bit of threading / async stuff in Python, but I know what you mean. I was mostly talking about the attempt to manhandle locals()
All I can remember when I learned it is loves(raymond, X). and there was something called a "cut" and no one understood how it worked but we needed it for our assignment
I took ai and advance ai both using prolog.... I feel like getting into ti was fun and all. Seeing the advance stuff was daunting. Thinking of solution was fun though.
TL;DR Prolog is very good at back tracking to make choices. Sometimes you don't want it to backtrack at certain "fork" of choices. so you choose to tell it to make a choice and commit to it. cut the backtrack off..
@wim Probably. The commonly used target is crap because it has answers showing how to make dynamic variables using globals(). But it's late and I'm on my phone and don't feel like doing a tedious search.
I bought TF2 because it was on sale for $24, have been enjoying it. I also bought BotW special edition and got the second to last one... but I don't own a switch nor do I intend to get one until their next run or second edition
It's interesting to me that most of the power-ups don't have a huge impact in combat, so there's not many places that are like "I better get twelve more heart pieces before I try going into the Valley of Almost-Certain Doom"
@MooingRawr Titanfall 2, I realize that's ambiguous
I've also been dabbling in Tharsis and Steamworld: Heist, both are fun. The earlier being challenging to the point where I think it's a little too rng-dependent
Which isn't to say the difficulty curve is flat amongst different areas. The City of Tears has more difficult enemies than Fog Canyon, for instance. The principal mechanism in getting stronger is identifying the attack patterns of enemies so you can hit them without getting hit back.
In this way, the game is reminiscent of Dark Souls. (Uh, I think. I've never actually played dark souls. I watched a bunch of Let's Plays though)
@MooingRawr It was around the second boss, when I was trying to find a gap in the attacks that would give me an opportunity to heal (an action that leaves you defenseless for several seconds), before I thought "this feels really familiar..."
The scariest thing I've encountered so far is a little batlike thing that hangs out in dark ceilings, and when it sees you, it shrieks at maximum volume and dive bombs you, exploding violently on contact.
First, let's consider this working example using get and set methods for the variable x
class Foo:
def __init__(self):
self._x = 0
def set_x(self, x):
self._x = x
def get_x(self):
return self._x
class Bar:
def __init__(self, set_method):
self._s...
There's a definite whiff of code smell (and misunderstanding of what properties are for) about it, but maybe there's the kernel of something actually useful there? Alternatively, I might just not have had enough coffee yet.
@AndrasDeak You have failed to define your cbg correctly. Not my problem :)
@idjaw Mainly loads of teaching is taking the time. Also occasional research into modelling the effect of embedded renewable electricity generation on a smart grid.
@davidism I dunno, I kinda like the idea of using strategic bounties to hover around 20.5k and thereby gaining a perverse smug sense of moral superiority.
When I hit 40k I thought I might hover there forever by giving away bounties, but then I forgot about that plan and now I'm halfway to 50k so I may as well trudge onwards
If you really want to go crazy jamming logic into a listcomp, def chain_unique(*args): return [v for v, z, _ in map((lambda x, s=set(), o=object(): (x if x not in s else o, o, s.add(x))), chain(*args)) if v is not z] works ... I tend to agree with @wim that this isn't pythonic, and you should at least explain what's going on if you're going to exploit these kinds of tricks. — Zero Piraeus1 min ago
This is in reference to a chat discussion prompted by this meta post.
The backstory here is simple: a high-rep user on Stack Overflow recently decided to start offering bounties on questions with the express intent of increasing specific authors' reputations so that they could use it to modera...
I really don't like that the whitespace one is secret. Whenever I fix whitespace in PRs I have to put the edited link in myself, and even then people miss it and critique code I didn't write.
Although I haven't had to do that in ages, I guess
@kevin also sir since I can't post another question on here for a while, can you email me if you can, or do you have a github? Mine is gethbonow on gmail, please consider help me if you have time! — user76802422 mins ago
Think I'm bout to get cyberstalked because I answered 1/4th of this guy's question in a comment
@kevin ugh sir since you are good with Python, is there way I can hit you up on google hang out? My gmail is temporary account I've created, so your privacy will be safe. So please consider help me if you have time. Since I can't post screen shot or too long code on here, I have to wait 90 minutes to ask a new question. — user768024256 secs ago
Incidentally, seeking a dupe target for the question linked through that comment. I'm sure "How do I fix UnicodeEncodeError?" has been asked appx one million times already
I think I recall this problem from yesterday. Isabel wants to execute a gui's mainloop while simultaneously executing run.py. I already suggested using import run instead of using subprocess on it, but that didn't seem to take
@IsabelCariod I probably shouldn't have suggested threading yesterday. You can get non-blocking behavior in subprocess simply by using Popen instead of call. My bad.
> When you write your application, place the sessionmaker factory at the global level. This factory can then be used by the rest of the application as the source of new Session instances, keeping the configuration for how Session objects are constructed in one place.
but doesn't it mean that the engine is bound at import time? how does that tie in with your test suite, when you want to have the engine bound somewhere else?
pix is a list, but what is the type of pix[i, j-1]? Because that's what you're iterating over.
Incidentally it's probably a bad idea to refer to the variable name you create in the for clause, in your in clause. It's going to use whatever value the name had before the loop started.
And if it didn't have a value at all, you'll get a NameError.
>>> pix = [[0,0],[0,0]]
>>> j = 1
>>> sum(int(i) for i in pix[i, j-1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
Hi guys, a question from a noob programmer. I have a sql query that finds out how many records there are with a name 'test' for example. In my database there are 4 records. When I print out the query it comes out as (4,) how do I get rid of the brackets and comma? sorry is this a stupid question.
Wild guess: Maybe they're worried that the object's __repr__ implementation might itself raise an exception, which would be a double headache to resolve. May as well just print the type, which is much safer
@simons21 you can parse it, you can find out what object type it's returning and maybe edited the __repr__ of it, etc... many ways of doing it but your question is too broad.
@MarcusS blog.wolfram.com/2013/10/08/a-response-to-falling-with-helium if it interest you... Wayne got me hooked on xkcd's what-if, and the author got banned from wolfram alpha, which led to that blog posting on the math side of one of the comic...
@MooingRawr Yeah, we don't have the full information needed to definitively diagnose here. I was just going by prior experience with SQL-y questions, where people were surprised to get a tuple when they expected something else