« first day (3230 days earlier)      last day (1709 days later) » 
02:00 - 19:0019:00 - 00:00

2:46 AM
cbg
 
 
2 hours later…
4:53 AM
Guys, please help me understand why we should use django-leaflet instead of just leaflet.js if we want to integrate maps into a django project. What benefits does django-leaflet give me that plain old javascript code won't???
 
5:24 AM
@AbdurRehmanKhan I haven't used it, I use plain old JS in Flask but it looks like it helps with callbacks so you can process interaction with maps
My guess is that it's meant to be integrated with geodjango but I haven't used that either so that really is a guess
 
cbg
 
5:40 AM
@roganjosh I see, you may be right. If you use plain JS with Flask, I think I'll try doing that with Django. I don't need geodjango either, just very simple maps with may be a couple of markers/polygons. Thanks!
 
There's nothing stopping you completely avoiding it :)
 
Yeah! If I get stuck, may be I'll learn the hard way why django-leaflet exists :D
 
Seems hype
 
I doubt you'll get "stuck". Above is it embedded into my Flask app. It's just going to be a wrapper with some convenience functions
 
5:50 AM
That looks great. That's pretty much close enough to what I'll be doing too haha.
 
6:17 AM
cbg
 
cbg
 
cbg
 
What is cbg? O_O
 
check the chats rules
 
6:25 AM
@AbdurRehmanKhan it's salad
 
aka go to the chats websites url, you'll learn the salad language
 
<note to self, remember to turn on the keyboard when doing the copy part before trying to paste the link> Today will be a long day I fear.
 
I feel that
Chat room question: Does anyone have a fun way to name variables?
 
Melon for informing me. Very cabbage indeed.
 
6:41 AM
...... "thank you for informing me. Very Hello indeed"
You'll get the hang of it
 
I thought cabbage could be used a placeholder for random words too, like the room's description: The productive programming cabbage (where cabbage=language). In my case, I meant cool lmao.
 
cbg
 
cbg
 
@AndrasDeak haha
 
7:15 AM
@AnttiHaapala Deleted
 
thanks
 
7:34 AM
cbg!
 
cbg!
 
8:04 AM
@JonClements Further to your kind interest in my job hunt, I had an interesting talk with a potential employer this morning - waiting for a contract to review the offer. Part-time, 100% remote, running an existing small Python/devops team likely to grow.
 
I'm pleased to hear. Everyone benefits in that one I think.
 
8:48 AM
It seems they will hire this channel
^_^
 
9:12 AM
Hi everyone
 
@StephanS how about you don't chide people when they are doing everything right?
@AbdurRehmanKhan yes, that's fine. Welcome
 
Hi Andras
I need some help
lat1 long1 lat2 long2 Approx. time
17°25'38.9"N 78°19'32.4"E 17°25'38.4"N 78°19'54.5"E 10:58 AM
 
So go get it
 
I am unable to format the above thing, anyways I am inputting those values into Google Maps
 
doesn't sound like a python issue
 
9:22 AM
So first I am inputting lat1, long1 for the first stop, followed by lat2/long2 for the 2nd one and then the time inside departs at section
@AndrasDeak Yeah I need ideas, I want to automate it, is it possible? If so can you direct me on what topic I should take a look at?
 
Nope, I can't.
 
Ok
One more thing I forgot to add is I am inputting it from an excel sheet
Thats the main thing actually, that is why I asked this question
 
@RaphX And we need you to stop acting like a help vampire.
 
Sorry@PM2Ring
I will see if I can figure out something
 
9:30 AM
You have been given many warnings about your vague unformed questions. Please stop doing that. If you want to ask questions here, present them in a clear coherent fashion. Your usual approach leads to long rambling conversations that rarely lead to a fruitful conclusion. They are of little benefit to you or the other participants, or the other people reading this chat.
We are a little more relaxed & flexible than the main site, but many of the same principles apply. We are happy to help people, but we aren't going to do your work for you.
Imagine that you won a competition, and the prize is a free session with a Python think-tank who normally charge $1000 per hour. Don't waste that prize!
19
 
And most of us are working cheap at that rate! ;-)
 
Got it , sorry again@PM2Ring , I will not ask vague questions like this next time
 
@holdenweb true dat :P
 
10:51 AM
cabbage
 
Hey guys. Stupid questions. I have a script with an import statement that doesn't work. If I do it manually from the console, it says no module with that name exists.
The python interpreters are the same, and they're at the same directory. Any clue what could be happening?
 
@MitchellvanZuylen One common reason is that the name of your python file clashes with an installed module. Like trying to import foo from your file named foo.py. Otherwise we'd need some more information, more or less an MCVE
 
Maybe I'm misunderstanding how import works. Would changing directory like os.chdir('random/location') work if I want to import something from that location? That shoudn't work right?
 
that will work. But caveat: You generally don't want to use it that way*
 
Hmm. Okay, then I'm very confused.

My import statement is
from mediaShare import create_app
 
11:01 AM
We are also confused. Hence my request for an MCVE.
 
If I run this line from a file.py it says mediaShare does not exist as a module. If I run it from the terminal, it works.
 
Are you running it from the same directory? And is mediaShare an installed module or a local .py file?
 
And what is mediaShare? Is it a folder name/.py file?
 
Running from the same directory. mediaShare is a folder which contains a init.py which contains the function create_app
 
you can edit/delete messages for 2 minutes in chat
 
11:05 AM
formatting screws my underscores, but you understand what I mean
 
you'll find this interesting.
But yes, your "mediaShare" is being "found" as a module only because of your current working directory when you're running things in terminal.
 
Thank you for your help. That link is interesting indeed
I got to go catch my flight now, bye. Thanks!
 
bye
 
11:20 AM
Hi there! Maybe it's a stupid question...
Is it possible to minimize a flask application in angular??
for example ... if I create my hello world app, and then I serve in angular, the 'hello world' that I had written in python, can I see it on the browser?
 
Do you mean that you want to see the source code of the actual file itself?
 
no, I mean this:
@app.route('/')
def hello_world():
return 'Hello World'
 
Sure, why not. I don't see what Angular has to do with this though. That's essentially a response from server side
 
11:46 AM
ok, thanks!
 
12:10 PM
Can two planets of equal size move along the same circular orbit on opposite sides of the sun, so that one is never visible from the other? en.wikipedia.org/wiki/Counter-Earth lists a number of reasons why this can't be the case for Earth, but they're contingent on some combination of 1) the solar system having other planets 2) the planets' paths being elliptical 3) the planets having different masses, and other such details that might not apply to other solar systems.
 
My knee jerk instinct is to say that the factors that would need to go right for such a thing already make it sound impossible. But that's all i can contribute on this matter, i have no idea if it's theoretically impossible or not
 
I'm guessing that it's very unlikely for counter-planet pairs to form out of the protoplanetary disc, but I'm less interested in the chances of it happening and more interested in whether the system can remain stable afterwards
 
That's a Lagrange point.
hence probably stable.
 
The wiki article does a good job explaining why Earth's L3 Lagrange Point can't keep an object with a small mass in a stable position, but I don't know whether that would matter for an object that's as heavy as Earth
 
12:21 PM
@Kevin I don't see a reason why two identical planets on a circular orbit around their star would not be stationary. Of course circumstances should be ideal, and I wouldn't be surprised if it were unstable, i.e. move something a bit and it will collapse eventually
 
Mm hmm, I was just thinking that if the system were perfectly symmetrical down to the atom, then there's no way it could ever become asymmetrical. But this doesn't tell us what happens if planet A has one more atom than planet B.
... Not that "forever symmetrical" necessarily implies long-term stability. The planet pairs could plunge into the sun while maintaining symmetry, for instance.
 
something something conservation of angular momentum
you also can't really have a spherically symmetric star in practice
perhaps a neutron star
 
It can be football shaped or pill shaped or a cube or what have you. We only really need 180 degree rotational symmetry.
 
what I mean is that plasma tends to have all sorts of turbulent behaviour, so if you have an active star it will probably always have various kinds of random fluctuations that break symmetry
gentle reminder of crazy many-body orbits
 
We only need to model the interaction of three bodies... How hard could it possibly be? ;-)
I'm inclined to say that the L3 stability problem applies even to planet-sized masses. If anything, it's worse, because if Planet A starts to "roll down the hill" in the widdershins direction towards Planet B, then Planet B will roll down turnwise towards planet A.
Or, hmm, let me look at this graph again
Oops, I read it wrong. L3 is stable in the turnwise/widdershins directions, and unstable in the towards the sun and away from the sun directions.
So if planet A rolls towards the sun, then planet B will roll away from the sun. I think this makes sense, since it conserves energy or some such.
Maybe the final fate is that planet A plunges into the sun, and planet B assumes a more distant orbit with twice as much kinetic energy
 
12:40 PM
You have a sim running?
 
Nope, I'm just looking at colored arrows in Wikipedia diagrams
 
@ReblochonMasque Always, in his mind.
 
There cannot be a planet on L3, because this is where my evil space station is located!
 
Wait, so in the scenario described here (two planets in perfect counter-rotation on opposite sides of the sun) the planets still pull on each other? I would have thought that the star gravity mitigated any interaction between the planets... maybe if it was a massive star
 
"mitigated" I think is the wrong word... More like "dominates". You can't drown out one source of gravity with a larger one, they just add or subtract
 
12:51 PM
stackoverflow.com/questions/57562548/how-to-set-an-icon-in-kivy ("why isn't this code working?") must include the desired behavior..
 
The planets do still pull on each other. We know this happens in our solar system because there's a bunch of asteroids in Jupiter's trojan points
 
@Dodge gravity can't be shielded
Even as we speak I'm pulling you with gravitational force.
 
Also, the reason Neptune was originally suspected to exist was because something was exerting a gravitational pull on Uranus that couldn't be accounted for by the planets we already knew about
 
Ok, @Kevin and when you said that the planets need be perfectly symmetrical down to the atom to remain perfectly opposite, that was more a reference to the fact that a slight difference in mass will cause the perfectly opposite rotation to cease and not that the effect of the planets on one another is changing.
 
Also planet (I)X
 
12:54 PM
@AndrasDeak That is a crazy thought actually lol
 
cbg...long day ahead!
 
@Dodge Yeah.
 
I guess space exploration in our neck of the woods has been extensive enough to prove that there is not an opposite earth on the other side of our sun ;)
 
1:17 PM
The Counter-Earth wiki page says as much. We have satellites at L4 and L5 that have a clear view of the other side of the sun, and even if we didn't we'd be able to detect the gravitational influence that Counter-Earth would have on other planets' orbits, and even if we couldn't we might be able to get a peek at CounterEarth as the sun wiggles around its barycenter and/or when Counter-Earth accelerates WRT Earth since we're both on elliptical orbits
 
Are most here physics majors/related work?
 
o/ computational linguist here
 
I feel like I'm in a minority XD
 
1:40 PM
@biggi_ nope
 
'morning cbg
 
@AndrasDeak nope to which part? mostly physics or sparkies being the minority?
 
it was a directed reply; no to mostly physics
 
gotcha, didn't see that
 
sparkies are probably one of many minorities :)
 
1:57 PM
What are sparkies?
 
electrical engineers haha
 
o-kay, thanks! :D
 
2:18 PM
Is possible with python kill any process which produces in my script PermissionError?
 
2:29 PM
@EnderLook I don't understand your question
 
I don't think Python has a native understanding of what a "process" is, so I guess it depends on what library and/or system calls you're using to monitor and communicate with processes
 
cbg
 
Unless you're specifically talking about processes created with the multiprocessing module
 
I have a script which uses subprocess and multiprocessing. One process does I/O in a file. I noticed that when my script stops due to an exception, and I try to execute it again, it always raises PermissionError (when trying to delete the old file because it's open by a rogue process, I guess...), and so I must manually kill the old instances of python using the Task Manager
 
Do you know which rogue process has the file open? Is it a python process created by multiprocessing, or some other program's process opened by subprocess?
 
2:35 PM
@EnderLook probably worth reading this to get a handle on the subprocess stuff, anyway. Not sure why you'd want both subprocess and multiprocessing, though - aren't they both essentially means to the same end?
 
@Kevin In task manager they are called python, so I guess they are multiprocessing, but jus they consume 0% CPU and 10-40 Mbs, instead of the normal 20-30% and 1200-3500 Mbs, so I think they are in a kind of idle state...
 
Ok.
 
I use multiprocessing when I want it to look like threading.
 
cbg, folks!
 
cbg gadget
 
2:37 PM
@holdenweb My script does some stuff with python libraries, but when it can't, it calls a subprocesses to do that. (With python I unzip some zips files, and with subprocess I unrar some rar files...)
 
@EnderLook It sound like you might be calling subprocess with shell=True, in which case you will kill the shell running the subprocess rather than the subprocess itself. That appears to account for your reported issue.
@EnderLook you know your use case better than I do
 
@holdenweb My subprocess has subprocess.CREATE_NO_WINDOW
 
My initial expectation is that, when a multiprocessing subprocess raises an uncaught exception, that subprocess ought to print its error information and promptly terminate itself completely. It's surprising to me that it's still hanging around in the task manager.
 
Hello folks. I have a question about OAuth2. I don't really get how to do if I just have a client and a server.
 
@Kevin Maybe the process with the exception die, but its siblings don't (and so I must kill them)?
 
2:40 PM
Sounds about right. I would expect an exception in one subprocess to only terminate that process, and all sibling processes and the parent process would continue to run.
 
@EnderLook But that doesn't necessarily imply shell=False. It "just" means there's no stout or stderr channel, I understood.
 
@holdenweb Ohh
Didn't know that
 
Better check, then, it's a while since I touched that stuff.
 
I'm glad holdenweb is tackling the subprocess half of this question, because I have no idea how to kill rogue subprocess subprocesses
 
@biggi_ I'm a construction worker turned crop scientist who is addicted to programming, so probably the most minor of room six minorities.
 
2:44 PM
If they are Popen ob jects, use Popen.kill().
Just noticed the default vakue for shell is False, so maybe strike my idea unless it'as actually being passed as True :-(
 
@holdenweb I'll take a while, my script accidentally remove 179 files of my pc and I have no idea what they where XD, I will have to do some checks...
 
Ouch!
 
Cabbage.
 
cbg @toonarmycaptain
 
cbg captain!
 
2:51 PM
@holdenweb My script was already in False it didn't do any effect, actually I don't use Popen, but run. But I am starting to suspect that the error is in the process rather than in the subprocess. Isn't there a way to just kill all process on error? I though adding daemon=True would do the trick but....
 
here is an MCVE that demonstrates that a multiprocessing subprocess that raises an exception does not automatically kill its siblings or parent.
 
@holdenweb Actually, from the 179 it only removed 6 of them, all of them inside Git, so it was easier than I expected, lucky!
@Kevin Oh, I'll have to do research so!
 
I... Don't actually know how to make the pool die completely if one of its workers fails.
 
No worry, you proved where is the error, so that will make much easier for me to fix it. Anyway, I just got called and I must go, so I will fix it later
Thanks all of you!
 
So...maybe I'm missing something or my search terms are garbage, but any ideas on how to specify a type "iterable except dictionary"?
@Dodge How goes?
 
2:58 PM
does anyone know of a way to create an "expression object"? I know that when I create a lambda, I get a function object that I can manipulate. I'm trying to find a simple way to create an "expression object" so that I can insert it as the body of a lambda that I will later create. I'm trying very hard to avoid goind the route of ast
Something along the lines of:

expr = a+b>0
f = lambda a,b,c,d: eval(expr)
 
Nvm TIL Sequence type :)
 
@inspectorG4dget I don't think python has macros in the standard library at least
 
@toonarmycaptain it will probably exclude sets though
 
any idea how I can get it (even from outside stdlib)? I really wanna avoid using strings/ast
 
@inspectorG4dget can't you do that with another lambda?
expr = lambda a,b: a + b > 0
funs.append(lambda a,b,c,d: expr(a,b))
 
3:03 PM
@EnderLook here is a quick proof of concept of a multiprocessing killer. By specifying error_callback, you can make the main process terminate all its children right after any one of them raises an exception.
 
@AndrasDeak not exactly perfect for what I'm looking for, but it's a damn sight prettier than what I currently have. Thank you
 
no problem
 
This is a pretty abrupt termination so you can expect that the sibling processes will not have a chance to politely release whatever resources they have allocated, even if you're using a with block
 
I wrote pandas code yesterday and it was ugly. :(
 
Open question: what happens if the pool calls apply_async more times than you have worker processes? Will terminate kill all children, including the ones that haven't been allocated to a worker yet?
My guess is "yes" but I'm not 100% confident
 
3:09 PM
@Kevin Looks like today might be another day of searching through the source code
 
@AndrasDeak Thanks. That's actually fine :) I'm doing one of those palindrome-related excercises and knew I could accept a int or list/tuple and then see if the input equals it's reverse slice (stringifying the int) - a set with more than one element wouldn't be symmetrical because of the orientation of the brackets and the spaces between the elements anyway - too much work to handle for this case ;)
 
pastebin.com/PvxHk1XK never executes processes 5 through 13, so I'm inclined to say that terminate will terminate children that haven't started working yet
 
@Kevin Unless it's a counterexample, it's not really a proof now, is it?
 
@toonarmycaptain I'm good, busy as ever
 
I can't positively prove the behavior of any Python program, not even print(2+2)
The best you're going to get from me is "worked on my machine, at least once"
 
3:22 PM
we are getting close to the 1,234,567 python questions
 
wow..
 
<rant> Gitlab's pipeline view is extremely frustrating when you try to provide nice naming and the job containers don't expand in width at least a bit to accommodate seeing a name without hovering over it.</rant>
 
What's special with that number @piRSquared?
ok, I see it, never mind! :D
 
(-:
 
@Dodge Me too, I wish I were busier with different things though.
 
3:38 PM
@toonarmycaptain also there's at most one item in a palindrome that appears only once and not more
 
@AndrasDeak Good point.
 
@inspectorG4dget Had you considered not using a lambda at all, and just calling exec on the expression with a dict as the local namespace?
 
3:59 PM
Ah finally got my 2 body simulator to draw an orbit that doesn't look like a straight line
 
@holdenweb that's almost exactly what I want to do. Unfortunately, exec would require me to have the expression as a string, which I really don't want to do. If there were a way to create an expression object that I could exec, that would be ideal
 
Turns out acceleration in terms of meters per second squared is different than in meters per day squared
and they're both different from meters per second per day
 
@Kevin yeah, I'd say they're off by a factor of almost 100k
 
@Kevin Too bad python doesn't have a suitable typing system for this :P
 
So basically you want to defer execution of an (arbitrary?) expression?
 
4:03 PM
@holdenweb yes (arbitrary), and yes
 
The only way I can think of deferring code execution is ... to write a function or a lambda! Sorry.
 
@Dair actually, the quantities library tries to bridge that gap
 
astropy.units sounds similar
 
ok ok. Now that I think about it, you could easily override the binary operators to add a bunch of exception for units...
 
@holdenweb all good. Thanks for trying. I think I'm going to try some hacks to get Andras' idea to work
 
4:05 PM
@inspectorG4dget I suppose you could define a variable class so that the result from evaluation of the expression IS some sort of structured object.
Much like sqlalchemy defines Fields and allows you to build queries with them.
Lotta work, though.
 
Why the restriction against strings though? That's the part that confuses me most.
oh, also recbg
 
Syntax checking at compile time?
cbg :)
 
ok, so this is the part that I didn't mention previously (not mentioning which, pretty much turns this into an X/Y problem)
 
don't worry, it's sounded like XY from the start :P
 
I'm trying to write a Design-by-Contract (DbC) library for python
 
4:07 PM
rubs hands together aah the juicy details!
 
there are two libraries that already do this... or try to but don't have the required feature completeness
the one I chose (a long time ago) hasn't been in active development since 2007 (so it's OLD)
so now, I'm trying to implement DbC with decorators
<necessary aside to explain what DbC is>
DbC is a paradigm that allows for the semantic checking of functions at runtime. This goes way beyond type-checking
so, you could specify a contract for a function that param1 must not only be an int, but must also be within [0,7], etc.
this makes debugging a LOT easier when data flows become very complex and the stack size increases
</ necessary aside to explain what DbC is>
so, I'm writing this DbC library that is made up of basically two functions/decorators: preConditions and postConditions
DbC also has the ability to compare the current (post-function-run) value of a parameter to its pre-function-run value. It also allows you to perform semantic checks on the function's return value
 
sounds related to the hypothesis testing framework.
 
as a result, I've created three new variables: __old__, __id__, and __return__
@Dair thanks, I'll check it out
 
okay, first off. this sounds wicked cool, never knew about DbC.
 
__old__ is a Namespace that contains that pre-run variable values
 
4:15 PM
However, practically speaking, from what im understanding, you just need to validate inputs and outputs yeah?
 
in order to assert that the objects haven't changed, __id__ contains their object IDs (id(myvar))
@ParitoshSingh yes
 
Perhaps if you ditch thinking of it from a DbC perspective, and think of it simply as additional checks before and after running your function, i'd imagine this becomes a much simpler problem to tackle
 
so, right now, I have the whole thing set up as a bunch of lambdas
@ParitoshSingh that's why I've done it with decorators. So I just have to decorate each function with a bunch of lambdas, each of which tests for one of the validations
 
ok cool, so far so good
How does one write the actual conditions?
 
the problem is that when I do it this way, I have to make the design decision to force each lambda to have the same signature as the function being validated, even if that lambda tests only ONE of the function params
 
4:18 PM
Also, seems related to dependently typed languages (see Coq, Idris, Agda, Lean, ATS ) except they make guarantees about the methods at compile time.
 
@Dair very related to dependently typed languages
@preConditions(lambda a,b,c: a<5)
def func(a,b,c):
# do stuff
see, in that example, func takes three params, but the first (and in this case, only) precondition checks only ONE of them. But it still needs the full param spec from func
currently, preConditions looks similar to this:
def preConditions(*funcs):
    def decorator(fn):
        def wrapper(*args):
            if "__testmode__" not in globals():
                raise NameError("__testmode__ not set")

            if globals()['__testmode__']:
                fails = []
                for i,func in enumerate(funcs):
                    if not func(*args): fails.append(i)
                if fails: raise PreConditionError(f"PreCondition functions failed:\n", '\t', *map(str, fails))
            return fn(*args)
        return wrapper
what I would like to do, is make it such that preConditions executes each lambda in some magical environment, such that the lambda itself does not need to specify the irrelevant arguments in the signature of the function that it wraps
does this make ANY sense at all?
 
yep, i get the big picture so to speak. I am not sure the lambdas are your saving grace here, not in the current format.
 
and that's where I'm banging my head against the wall. There's gotta be a cleaner way to do this. That's why I thought about evaling expressions within a context, but I can't think of a way to do that. Also, since this is used in actual run-time testing, I don't want to use strings, because it'll force <endUser> to write valid python code as python strings (which therefore have no syntax highlighting).
So, I'm trying to figure out if there's a way to capture an expression and delaying its evaluation
 
My knee jerk reaction is to think of some kind of argument introspection on the function perhaps, and a no-argument lambda.
But i might be sending you off on a wild goose chase, this is all pure speculation on my part for the moment.
 
no-arg lambda is a nice idea. I was thinking inspect.signature.bind + inspect.getcallargs with a dict-comp filter
 
the problem is that once I bind the signature, I might not have a way to call. So I'm trying to see if I can do something like (lambda a,b : a+b)(**{'a':1, 'b':2})
 
wim
> ... the percentage of new Bitbucket users choosing Mercurial has fallen to less than 1%
 
I may do some digging on this, im intrigued. Disclaimer though, I'll probably come up empty handed.
 
@wim quoting SO dev survey
perhaps mercurial users don't use SO
 
wim
the 1% is their own stats, nothing to do with SO
 
4:37 PM
yeah, I was responding to your first message
the 1% does seem to be their own
 
wim
kind of sad to see Python fail so badly here
 
Python?
 
is mercurial built on python or something?
 
wim
hg is poor compared to git
but with a bit of love in the important areas (e.g. interpreter startup time) it could have been great
Yeah, mercurial is implemented in Python.
 
Ah, that explains it.
Not really the language's fault at the end of the day, though i can understand your sentiment.
git's pretty good though. (git good??)
 
4:39 PM
I wonder how much is about speed and how much is centralized vs decentralized or whatever
 
wim
well they are both decentralized
hg CLI is better
 
yeah, that's just what I'm reading, I must have misread the original post
 
wim
though it's unthinkable to have a worse CLI than git
 
^ kevin'd
 
it's probably called git for a reason
 
4:41 PM
ah fair, i never got into the CLI, so far all my "git" experience is not really git, it's just softwares built on git
 
wim
and mercurial is still 2.7 too, which is a joke
they have only beta support for Python 3 since v5.0 (released mid 2019!)
 
wim
5:15 PM
@Kevin can't believe nobody made a gravitational pull on uranus joke.. y'all too mature for me
 
5:41 PM
I was thinking about it real hard.
 
groan
 
I still love that Mercurial's shortened name is Hg.
 
^^ ha! That's actually pretty neat.
 
Hmm, I thought I got my gravity simulator working, since I was able to get Earth to go around the Sun without slingshotting off into space. But then I added a 100 kg satellite on the other side of the sun. I expected it to stay 180 degrees from earth, and move gradually towards or away from the sun. Instead, it stays at the same distance from the sun, and catches up with Earth in its orbit and overtakes it in about 25 years.
Even if my prediction about L3's behavior was wrong, I'd at least expect the satellite to get stuck inside L5 or L4
 
5:59 PM
Question: how can i actually add things to my local scope from a dict? (understanding full well that this is a bad idea etc etc)
def local_scope_messed_up(**kwargs):
    #these don't work
    for k, v in kwargs.items():
        exec("{}={}".format(k, v))
        locals()[k] = v
        print("{}={}".format(k, v))
    print(var)

local_scope_messed_up(var=5)
the exec one actually caught me off guard, i didn't think that would fail as well.
 
That exec statement does succeed... Kind of. Simpler example:
def f():
    exec("foo=1")
    print(locals()) #result: {'foo': 1}
    print(foo)      #result: NameError
f()
So the name foo is indeed bound to the value 1 in f's local scope. But it still can't find foo when we try to print it.
This is because name resolution is determined at compile time. If the body of f does not contain an assignment statement that binds foo, then Python assumes that the locals dict can't possibly contain a variable named "foo", and doesn't even bother to look.
 
silly little interpreter
 
Yes, but the system works... Unless you're doing dynamic variable shenanigans.
 
Is it possible to append a no-op assignment to the function's bytecode, or something similarly dumb?
or does one have to hack a specific part of the bytecode
 
Hmm. this throws a wrench in things
So, the only workaround so far that i saw was a guy polluting the globals, and then deleting stuff after. But I am sure that would overwrite something important for someone eventually
 
6:05 PM
I was going to say "you just need to put an assignment in an impossible branch, like this:"
def f():
    if False:
        foo = 999
    exec("foo=1")
    print(locals())
    print(foo)
f()
But now that I actually run this, I am surprised to find that locals() no longer contains any values.
 
okay, it doesn't even work without exec
>>> def foo():
...     x = 3
...     locals()['y'] = 4
...     print(y)
...     return x
...     y = ...
...

>>> foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-392-c19b6d9633cf> in <module>
----> 1 foo()

<ipython-input-391-5fad231dc3a7> in foo()
      2     x = 3
      3     locals()['y'] = 4
----> 4     print(y)
      5     return x
      6     y = ...

UnboundLocalError: local variable 'y' referenced before assignment
 
yep, i suppose i should have separated the examples
 
... But I suppose even if the impossible branch technique did work, it wouldn't help Paritosh, because he'd have to manually specify each variable name by hand. Which defeats the purpose of dynamic variables.
 
def fire_pre_conditions(func, **kwargs):
    #fill namespace with kwargs here.
    return func()
 
@Kevin indeed, that's why I was wondering about appending to the bytecode, which sounds easier than editing a specific part of the bytecode
 
6:08 PM
Essentially, this was my last hurdle i was trying to solve
 
@ParitoshSingh shouldn't you just pass **kwargs to func()...?
 
The no-arg lambda for func and making it work.
The func itself was/would be written by someone else.
 
so?
 
If the intention is to populate variables in fire_pre_conditions so that func can access those variables when you call it, that won't work even if you use non-dynamic variables.
 
Or do you want it to be zero-arg? Sounds a bit fishy when the body is an expression involving names.
@Kevin right, that too
 
6:10 PM
yep, context: this is my exploration on the DbC thingy
 
Example:
def fire(func):
    x = 23
    return func()

print(fire(lambda: x+10))
This will not print 33.
 
I know. But I'd prefer def expr(a,b): a + b to def expr(): a + b # what are a and b even???
 
functions look at the enclosing scope of their definitions to find nonlocal variables, not at the enclosing scopes of wherever they were called.
 
@Kevin something something javascript
 
@AndrasDeak I think this one i can probably solve at this stage without issues. But i just wanted to figure out whether i could very specifically make the no-arg variant work.
 
6:11 PM
I see
 
Call it an exploration in madness so to speak
 
I wonder if it's possible to modify the closures of the function object... That is Deep Magic, though.
 
i was very hopeful with types.SimpleNamespace initially, but i misunderstood/misassumed how it would work.
 
@Kevin it could give Paritosh a sense of closure
 
ba dum tss
 
6:14 PM
let him suffer, I say :P
 
If we're not allowed to modify the function signature, I'd say that modifying the globals dict is the approach that's most likely to work... Perhaps you could defend against the "what if I overwrite something important?" problem by saving the old global values and restoring them later.
 
Hm, that could be an option, but honestly i really would never want to use a library that's (even temporarily) wreaking havoc in my globals.
(Good thing i'd never really realise if i library was actually doing such a thing now would i) :p
 
x = 23

def print_x():
    print(x)

desired_globals = {"x": 42}

#setup desired globals, saving the older values
previous_values = {}
for k, v in desired_globals.items():
    if k in globals():
        previous_values[k] = globals()[k]
        globals()[k] = v

print_x() #42

#restore older globals
for k,v in previous_values.items():
    globals()[k] = v

print(x) #23
Something like this
@ParitoshSingh Well, each file gets its own globals (uh, I think), so the library should only mess up its own namespace, and not the user's.
 
oh, that's a headscratch/eureka moment rolled into one
 
C:\Users\Kevin\Desktop>type thelibrary.py
def print_x():
    print(x)

def call_with_globals(func, d):
    for k, v in d.items():
        globals()[k] = v
    func()

C:\Users\Kevin\Desktop>type main.py
import thelibrary

x = 42
thelibrary.call_with_globals(thelibrary.print_x, {"x": 23})
print(x)

C:\Users\Kevin\Desktop>python main.py
23
42
Here we see that main's global x retains its value of 42, since thelibrary's globals()[k] = v statement updates thelibrary's global x and not main's global x
 
6:26 PM
You're insane! And in a very good way :)
 
This also means that call_with_globals only really works if its func argument is a function defined inside thelibrary. Otherwise the changes you make to globals() won't be visible inside func.
 
You can change the __globals__ on the function to mutate the scope with no mess.
def call_with_globals(fn, **kwargs):
    fn.__globals__.update(kwargs)
    return fn()

>>> call_with_globals(lambda: a + b, a=1, b=2)
3
Unless __globals__ mutates more than itself
 
wim
Anyone know how to make PyYAML emit comments?
the inverse of this:
>>> import yaml
>>> yaml.load("""\
...    k1: v1
...    k2: v2  # the second val
...    k3: v3
... """)
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
 
Okay, so one issue i do see is that we need to "clean up" after ourselves because it does leave the globals polluted
Even the call with fn.__globals__.update(kwargs)
But this works like a charm
 
I think func.__globals__ resolves to the same dict reference as globals(), so mutating one is as polluty as mutating the other
@ParitoshSingh The upshot of having unique globals per file is that you don't necessarily need to clean up after yourself, if you're sure that the globals you're mutating aren't used anywhere else in that file.
 
6:33 PM
Yeah it probably gets the same reference as globals(), I noticed it does change the scope after posting. At that point a small context manager/try+finally can revert it, which I think you said earlier.
 
If the global SPINDLES_PER_WIDGET is only ever accessed within def reticulate(widget): and you only ever call reticulate from call_with_globals, then there isn't much harm in leaving globals as it is, since you're going to overwrite it the next time you call call_with_globals anyway
 
The issue with leaving it messed up is that the user writing the function could make a mistake and it would silently accept it.
For example, if they pass multiple functions for validation, and then make a mistake further down the line like following:
new_namespace.fire_pre_conditions(lambda: n>7,a=3)
This would work if n exists
 
Ok, that's a valid concern.
 
6:54 PM
Hm, there's a gap in my understanding somewhere. I can't seem to make a function run in the other module's namespace even if i send it over? That sounds wrong to me, but i have no idea anymore why the approach discussed above is failing
#new_namespace.py

def fire_pre_conditions(func, **kwargs):
    #fill namespace with kwargs here.
    for k, v in kwargs.items():
        globals()[k] = v
        print("k,v is ",k,v)
#    globals()["_run_this"] = func
    result = func()
#    for k in kwargs:
#        del globals()[k]
    return result


#main.py

import new_namespace
new_namespace.fire_pre_conditions(lambda: n<3, n=3)
#NameError: name 'n' is not defined
 
Like I said, fire_pre_conditions won't work unless the function you pass it is also defined in new_namespace.py. Your lambda is defined in main.py
 
oh. I see.
That's a no bueno then
I can imagine Andras smiling to himself right about now. :p I suppose back to the drawing board then
 
I expect updating func.__globals__ would allow you to modify the function's globals, no matter where it was defined... But then you'd be modifying the globals of main.py
 
@ParitoshSingh I'm sad for you
 
02:00 - 19:0019:00 - 00:00

« first day (3230 days earlier)      last day (1709 days later) »