« first day (3314 days earlier)      last day (1633 days later) » 

12:06 AM
@AndrasDeak I could also see something like this cropping up if the code was being tweaked often, for a varying prefix. Checking for "__" became "_", so [:2] became [:1]
 
hmm, could be, and that would explain why the filter was there to begin with
 
Of course, that's no excuse to ignore startswith, IMO.
 
wim
12:19 AM
how they filter _ names is not important (just slightly different ways of doing same thing), what was more curious was why implement it with the same as the default behaviour for * import anyway. but I found the answer, it prevents pydoc from using dumb heuristics. nothing to do with * imports.
 
12:36 AM
how do you deal with help vampires at work when your too nice to say no?
 
find a nice way to say "no", there are plenty
 
i think today i was successful, I said I was behind on my work and please ask someone else
 
@erotavlas Socratically. What have you tried? What did you expect? What did the documentation tell you about this kind of error?
 
I tried the above and it worked for today, I might try it again in the future. The documentation revealed nothing about help vampires within the context of office environment, only online chat rooms. Furthermore online documentation was unhelpful and mostly pertains to 'energy vampires', a similar but distinct phenomenon. :)
 
wim
try being a bit more mean
they love you too nice and helpful types!
 
12:51 AM
thats me :) before today I did everything they asked, I guess I'm a people pleaser
 
wim
feign incompetence?
 
thats pretty hard to fake for a senior level dev.
i think for my next approach I'll try garlic
 
2:00 AM
That's why chat is such a nice interface, simply stop typing and the problem is solved. IRL people can be far more bothersome
 
2:59 AM
@erotavlas Perhaps you misunderstood. I meant you should ask those questions of your vampires.
Also, I seem to recall seeing this kind of question over on Workplace.SE
 
@JoelHarmon oh haha sorry :)
 
3:43 AM
if you floor anegative number, should it increase in value or decrease in value
philosophically speaking
 
wim
decrease. nothing philosophical about it.
 
floor always decreases
 
Hey, what's the deal with running a python script from a different working directory? Do I need to do anything special in the script for it to handle this case, or should the user navigate to the same directory and then run the script?
 
wim
you can run it from any directory
if it fails with import errors it means your script is bugged, for example not installing library modules properly or using relative paths to try and resolve resources
 
what if my script tries to read a file from a relative directory? I guess its absolute path should be used instead?
os.path.join(os.path(file), 'some_file.txt')
 
something like this?
 
wim
^ go to page 66-67
 
ok thanks, are these your slides?
 
wim
no, but it shows how to read a resource in a package. if some_file.txt is not a resource of the code, for example it is a file provided by user (configuration or command-line argument), then it doesn't really matter if you use an absolute path or path relative, both should be working OK
 
wim
4:01 AM
you are from melbourne? I used to live in Fitzroy
 
nice
another question: if my script is run like this; foo/bar/my_script.py ../some_relative_directory
where some_relative_directory is relative to where the script is run, how would I get the absolute location of that directory?
i.e. in this case it is one level higher than foo/
 
wim
os.path.abspath(...)
 
cool thanks, I think that'll work
 
4:18 AM
is it common to store a module's root directory? e.g. can I put PWD = os.path.file( __ file __) in my top level init.py?
 
wim
yes it's common
here = os.path.dirname(__file__) or here = Path(__file__).parent
 
Ok, because now I'm using something like ```OUTPUT_FILE = os.path.join(os.path.dirname(__ file __ ), "../Report/template_output.html")
so it'll become OUTPUT_FILE = os.path.join(PWD, "Report", "template_output.html")
or perhaps BASE_DIR instead of PWD
 
4:42 AM
int.__add__(2,3.0) returns NotImplemented and float.__add__(2,3.0) will give error, as first argument need to be float in this case. So, how the expression 2+3.0 will get evaluated?
 
wim
via float.__radd__(3.0, 2)
 
Ok, so python interpreter decides that?
 
wim
yes, because that's what NotImplemented signals to do
 
Ok thanks
@wim But why using __radd__? Is there any reason not to use float.__add__ after getting the NotImplemented signal?
 
wim
5:13 AM
because binary operations are not necessarily commutative
(consider division, for example)
in the general case, it matters whether you are on the right or the left
 
5:32 AM
@Code-Apprentice Re your question from October on porting drc::drm() from R. I wrote up an answer. Lmk if that helps or not. I still think your first question needs retitling, and probably was superseded by your second reasking.
 
6:13 AM
All: there is no canonical Q&A about introspection, we need something. Can anyone suggest anything?
 
"introspection" is a bit broad, don't you think
 
introspect what? Functions in a module? Classes in a module? Functions in a class? Arguments of a function? The line number where a function was defined?
 
I think a canonical of "why is my pandas dataframe not being updated when I call this function" would be nice
 
 
2 hours later…
7:54 AM
cbg
@Aran-Fey I think what I took away from yesterday's discussion can be summed up into something like this github.com/takluyver/flit/issues/115#issuecomment-332147969
 
sounds about right
 
8:09 AM
@Aran-Fey Suggest as many as you think necessary; I didn't say there needs to only be one, or two, or three. But currently there are zero and obviously that's an oversight. The most common case I personally see (and the one I referenced above) is introspecting arguments of a function.
 
@wim I think there are a few unanswered/badly answered posts on SO that could be solved with this lib, e.g. stackoverflow.com/questions/56452948/…
 
... also here's a similar question for base Python string methods How best to redirect all duplicates of “Why doesn't <Python string method> do anything unless you assign its result”?. Can you suggest some for "why is my pandas dataframe not being updated when I call this function"?
 
it looks useful, but it produces scary stack traces on failure dpaste.com/0KVC58X
 
8:28 AM
Hi All,
I am trying to get the creation time of each frame of a video but couldn't able to get the information.. can anyone please help me out?
my code which I tried so far is :

import cv2
def FrameCapture(path):
vidObj = cv2.VideoCapture(path)
count = 0
success = 1

while success:
success, image = vidObj.read()
#cv2.imwrite("frame%d.jpg" % count, image)
count += 1

vidObj.release()

if __name__ == '__main__':
FrameCapture("SampleVideo.mp4")
 
that looks like you should probably post this as a question on Stack Overflow, with more details about what's wrong with your code and what you have done to troubleshoot
 
cbg guys o/
 
What even is the "creation time" of a video frame?
 
@Aran-Fey each frame will have some timestamp value of its own
for more info, pls refer this link
https://hhsprings.bitbucket.io/docs/programming/examples/ffmpeg/video_data_visualization/showinfo.html
a frame will show following properties:
[FRAME]
media_type=video
stream_index=0
key_frame=1
pkt_pts=0
pkt_pts_time=0.000000
pkt_dts=0
pkt_dts_time=0.000000
best_effort_timestamp=0
best_effort_timestamp_time=0.000000
pkt_duration=N/A
pkt_duration_time=N/A
pkt_pos=48
pkt_size=345600
width=640
height=360
pix_fmt=yuv420p
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
 
@Rish Please use gist.github.com to share long code.
or some pastie site
 
8:37 AM
Searching for "creation" on that site gives 0 results but ok
 
so out of these properties, if I want to fetch "pkt_dts_time" of each frame, how should I do it ?
 
That's rare, why would you need creation time of a video frame and not the whole video?
 
@TheLittleNaruto, ok I will do it from next time
 
I've been forced to work with databases, and sqlachemy as the orm. I'm now starting to write tests, is there a good tutorial with some best practices on how to do it?
some questions I have:
- is alchemy-mock any good?
- should I test repository-functions that just execute a specific query?
- should I mock the db for functional tests as well?
 
Does anyone can help ...how to ingest data into splunk using python scripts?
 
8:53 AM
@Arne Not diving too deep, but if your DBMS supports nested transactions / savepoints, that'll come in handy. Organize your tests so that they begin a "master" transaction, handle fixtures if any, run the test, and rollback all effects.
 
What you write suggests that I have an actual instance of the db running during tests, right?
 
Yeah, when it makes sense (functional maybe, integration most definitely). In unit tests it might be more beneficial to mock the whole DB away (maybe some thin database access layer / repository). Disclaimer: just my 2c.
And resist using SQLite in tests, unless your production also uses SQLite :)
 
@IljaEverilä hahaha, why would I even do that? *hides sqlite snippets*
ok, that helps a lot structuring the whole thing already. thanks!
 
9:19 AM
@wim Hmm, hadn't seen that one before, it's decent. But we had many other near-duplicates revolving around whether objects can/should be tested for equality using is, id(obj), aliasing, caveats about interned strings, unbound method objects (in 2.x), pitfalls, etc. Those answers need some cleanup and bringing up-to-date for 3.x.
 
9:35 AM
@inspectorG4dget Congratulations
 
Long time no cabbage!
Hopefully we will soon be able to address you as "herrDoktorInspectorG4dget"
In fact starting now. Nice pic!
 
10:22 AM
cbg
 
10:54 AM
Hi,
stng = "report has bee generated for the {batch} with count {count} but blash blah {4}{2}".format(batch=123,count=12)
I want supply values only to the keyword variable, not for positional values({4}{2})
How I can do that
?
 
there isn't really a way to do that
 
If I do above I'm getting tuple index out of range error
any suggestion?
 
Any reason you can't just remove the positional ones from the format string?
 
actually, I have a query in stng variable where I'm using regular exp to get some value from column
So I can not remove from that string
 
when you say query - do you mean SQL query?
 
10:59 AM
yes, SQL Query
 
any reason to not have a string specifically for the sql query and another string for printing the results?
also - you're not using string formatting to build a sql query are you?
 
This is the actual string
query = "select REGEXP_CONTAINS( tmst, r"([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})[-+]([0-9]{2}):([0-9]{2})$" ) as tmst from {table}".format(table='acptns')
where I'm passing table name from some other process
 
Oof
 
then do either r"{{4}}{table}".format(table='acptns') or r"{4}%(table)s" % {'table': 'acptns'}
 
Or split the string into two
 
11:07 AM
okay
 
actually, the code you posted is a syntax error, so I'm still not entirely sure what the problem really is
 
Can't you parametrize queries to do this right?
 
I think prepared statements don't allow you to insert table names
 
@Aran-Fey even I'm reading this query from a file as a string and formatting
 
@Aran-Fey :(
 
11:10 AM
@Aran-Fey yes, I just shared for the reference ...
 
0.1 serious suggestion: generate a tuple ('{0}', '{1}', '{2}', '{3}', ...)
 
we almost found a use case for str.format_map (it throws an error when it sees numbered placeholders)
 
@AndrasDeak Yes, I don't think a better solution than this
 
I'd try though
"reading this query from a file" -> write something else to the file?
 
reading query from a file
 
11:19 AM
@Aran-Fey heh... could also always just write a custom Formatter :p
 
oh yeah, that's a thing that exists
 
@Vijay I can't help but feel there's some miscommunication here
 
Did I miss anything here?
 
Yes, I'm reading the query from a file, then formatting that string by passing the table name and then running the query
 
11:31 AM
Okay. What I'm saying is to write a different query to the file
For instance one that has double braces around non-template parts, like {{4}}
 
cbg
 
@SeanFrancisN.Ballais hi again from a Jon that isn't Skeet :p
 
@JonClements Hi again, Jon that isn't Skeet. Hahaha
 
all the Jons
 
11:49 AM
Hello
 
hello
 
fish fingers and custard?
 
anyhow .. I'm generating a tuple ('{0}', '{1}', '{2}', '{3}','{4}') and it worked...
Thank you all for the help and suggestions .....
 
I'm not very knowledgeable with Python syntax and was hoping I could get some help reading programmingpraxis.com/2010/03/19/…
 
11:56 AM
@Vijay it'd seriously be easier to just escape the formatting... eg {{4}} instead of {4}...
 
Specifically the line while p <= B1: q, p = pow(q, p**ilog(B1, p), n), pg.next()
Specifically what is ilog() ?
 
@JonClements okay
 
Haven't read the link yet but ilog() seems like a function from math.
 
@northerner ilog is not a builtin, so look for an import. Maybe from something import * which is bad practice
plus that line like that is terrible
I can't find any reference to ilog anywhere beyond that blog post
 
Maybe it's a typo then
 
12:01 PM
Maybe? I'd tread carefully with code like that.
 
There's a lot of crap code on that site
 
also it was written for python 2, so watch out for instance for divisions which would mean integer division
def primegen():
    """
    Generates primes lazily via the sieve of Eratosthenes.
    Code shamelessly stolen from someone else's work.  No idea where I got it.
    Input: none
    Output:
        Sequence of integers
    """
    yield 2; yield 3; yield 5; yield 7; yield 11; yield 13
    ps = primegen() # yay recursion
    p = ps.next() and ps.next()
    ...
from what I can tell p is guaranteed to be 3...
so yeah, don't take that code more seriously than pseudocode
(also gen.next() is obsolete)
Oh, this is in a comment on a blog. Why are you even reading it? :D
 
Because I can't find a better reference :P
I think ilog is taken from here programmingpraxis.com/contents/standard-prelude/#comment-1213 which I guess is part of the scheme language
 
What language are you looking it write something in? There's plenty of examples of efficiently calculating primes in Python on the 'net
 
My actual goal is to understand how the stage 2 version of Pollard p-1 works. math.stackexchange.com/questions/3418562/…
 
12:08 PM
Are @staticmethod and @classmethod decorators necessary for defining respected functions?
 
I don't get it. It's clear that some people know how it works but it's like they give the most cryptic explanation.
 
@Zeta.Investigator depends on how you want to call the functions
 
@AndrasDeak I don't know...what is the standard? I guess any function defined inside a class which does not take self is static?
 
For instance if you want to be able to say Foo.from_thing(thing) with Foo being the class then you need a classmethod.
@Zeta.Investigator it can be I think, yes
 
@Zeta.Investigator if it doesn't need self, why should it be in the class though?
 
12:10 PM
@AndrasDeak So these decorators are superflous?
In Java we didn't do that
 
Python is not java, and they are not superfluous. Just often not needed.
 
@Arne General tidiness and relevancy of functions in a scope
 
note that in python you don't have to define a class for everything
 
classmethod decorator does something very specific, it explicitly passes the class object in first argument
 
@Zeta.Investigator python is not java
 
12:11 PM
staticmethod i don't remember offhand
 
Sometimes it makes sense, but you often don't have to. This is something that java users sometimes struggle with.
@ParitoshSingh it doesn't use cls nor instance as first arg
just the "rest" of the signature
 
Aha, ty ty
 
@ParitoshSingh No we have to add cls even if we add @classmethod
 
@Zeta.Investigator if you don't want that use a @staticmethod, that's what it's for
 
@Zeta.Investigator that's what Paritosh said
 
12:12 PM
@Zeta.Investigator yes, that's what i mean by explicit, you get a reference to the class in the first argument. but note that cls is not a keyword, you can rename it to anything you like.
Just like self is not special for that matter.
 
class Javaclass:
    @staticmethod
    def add_numbers(first, second):
        return first + second
if the method doesn't use any class or instance info (so it could just be moved outside the class) you have a static method
if you just want to group functions (and no state is needed), consider using a separate module of their own instead
Then you can have helper_module.add_numbers just as tidily as HelperClass.add_numbers (and it will be idiomatic python)
 
There is one thing that the mentality of defining static method inside classes is discouraged in python (unlike Java)...but my question is in fact about the necessity of "decorators"
 
I don't understand your question, we've even discussed that they affect the signature
 
@Zeta.Investigator there is no auto-detection of the kind of functions based on their signature, if that is what you mean
the respective parameters "self" and "cls" are conventional as well
 
or perhaps this is what you're missing: instance.method(arg) will roughly call type(instance).method(instance, arg) for an instance method, type(instance).method(type(instance), arg) and for a class method
by which I'm just trying to explain how the actual signature of the function being called is affected
 
12:17 PM
@AndrasDeak suppose I want to declare a static method...since I don't use either selfBlah and clsBlash as first argument, python should automatically consider it a staticmethod...am I wrong?
 
@Zeta.Investigator Yes, you are. cls and self are just conventions as Miyagi said, there's no magic in the name.
the only magic is that the instance or class get passed on call to instance or class methods
Python can't tell if in def foo(arg1, arg2): the first parameter could be an instance of an instance method. "self" is not special in any way.
 
aha
that was confusing
So these decorators are necessary in python
 
it has very different logic than Java I'm afraid :)
@Zeta.Investigator yes
 
Wait, but how was these concepts written before decorators were introduced in python?
 
(hmm maybe not, if you want to call them as static)
@Zeta.Investigator decorators are just syntactical sugar for def method(...): ...; method = staticmethod(method). But I wasn't here back then, so I don't have historical evidence
I think python classes only came after a while, and they weren't very good for a long while. So perhaps they didn't work very well back then
others here know much more about these aspects, I'l llet them answer
 
12:23 PM
It's always been functional... it's err... just... until the type system got unified - it was err... "interesting" :p
 
A rather n00b question: for declaring instance variables inside the class constructor, do we have to choose the same name for instance variable and construction input? Can we do this? def __init__(self, nameParameter): self.namehaha = nameParameter?
 
i was gonna say, but then you edited it :P
 
yes, there's no magic involved there either
 
yes, that's perfectly fine. no magic anywhere
 
12:28 PM
Another weird thing, here nameParameter could be anything! like list or tuple or single string object...How are we supposed to cope with this "dynamic type" thing?
 
however, you probably don't want to worry about this right now, but __init__ isn't the "constructor" per se (as other languages call it) - it's the "initialiser" :)
 
If you need to restrict it, you need to add logics accordingly. Whether you talk about classes or outside, that doesn't change.
But i suppose it's nicer to work with people who are able to read docstrings, and then actually pass the correct datatypes and so on. But if someone really wants to break your code, they'll usually find a way :P
 
I don't get it. Should I signal type of variables in their names? like name_list instead of just name?
 
@Zeta.Investigator For signals to the end user, i'd recommend docstrings.
 
or type annotations
 
12:30 PM
@ParitoshSingh """ this is docstring?
 
@Zeta.Investigator Er, yes and no. your statement, on face value, is very vague. that itself is just a tripled quoted string literal. However yes, you'll see those used for writing docstrings too. Note that again, you can use '''hello''' anywhere in your code, and it's not magically a docstring. You will most commonly see those triple quoted literals in source code though
 
@Zeta you are familiar with the term Duck Typing ?
 
But if you write a string immediately after the def line, python "ties it" to the function as a docstring.
 
@JonClements apparently no
 
Off topic, but has anyone here figured out a way to permanently set an environment variable on linux? According to getent passwd $LOGNAME | cut -d: -f7 my login shell is bash, according to this answer the personal customization file for bash is ~/.bash_profile which contains [[ -f ~/.bashrc ]] && . ~/.bashrc and my bashrc contains export MYVAR=foo.
If I open a terminal, I can see the envvar just fine. But if I launch a program outside of a terminal, it can't see it.
 
12:41 PM
@Aran-Fey something something login shells
.bash_profile, .bashrc and .profile each get executed under different conditions
Hmm, though perhaps this is something else...not sure about the mechanics of "program launched outside of a terminal"
perhaps it would work after a restart, if your gnome or whatever has the envvar set
 
I did restart, this setup doesn't work
 
nevermind, you linked one of the answers from there, sorry
Just to be clear, we're talking about running a program with double-clicking an icon or something, right?
 
well, launching it from my application menu. Basically the same thing (I think, anyway)
maybe I'll just put it in /etc/environment...
(and pray it won't cause any problems for the root user)
 
have you found things like superuser.com/questions/19044/…?
 
cbg
 
12:47 PM
cbg
 
@Aran I think you can execute stuff (depending how you're doing so)... like: MYVAR=foo python do_something.py...
 
they say you might need .gnomerc or something in .kde depending on your window manager
@JonClements yeah, that has to work
(but a bit pedestrian)
 
@AndrasDeak Hmm, I hadn't considered that. Let me see if that helps
@JonClements Right, but I don't wanna have to launch the program from a terminal every time
 
@Aran-Fey (you could probably edit the launcher with the envvar)
but an rc is probably much better
 
Does that work? I tried to use a shell command in a launcher just yesterday and it didn't work
 
12:50 PM
or do what some frameworks do... you make a .env file and it loads its environment from that
 
Anyway, I want it to be global (for my user). It's not just one specific program that needs access to it
 
@Aran-Fey I'd expect it to. I can try to repro
as soon as I figure out how to add one, I guess :D
hmm, I guess a dash launcher should be just as good
 
you can install alacarte for a graphical utility
 
I have that, apparently. Thanks
 
I've discovered the Python API to automate iTerm2 - pane splitting, screen grabbing, keystroke sending, and general terminal poking. Very handy for working with our 3-node cluster product. (One script to split to 3 panes and SSH to each node, another script to send a text string to all panes - the POWER!)
 
12:53 PM
eh, I can't reboot right now because I'm copying files in the background. Further experiments will have to be postponed until that's done *twiddles thumbs*
 
ah, alacarte won't allow me to prepend an envvar setting
 
actually, one of my programs can see the variable...
IntelliJ, what did you do wrong this time
ah, never mind, the other program launches a shell, which is probably why I can see the variable in there
 
hmm, yeah, I can't edit the launcher command so that it's syntactically correct and has the envvar
 
What is a similar command for this print('A %-12.3f number'%4.3) using f-string. print(f'A {4.3:-12.3f} number') doesn't seem to work
 
>>> print(f'A {4.3:-12.3f} number')
A        4.300 number
Wrong python version? Need 3.6 or newer.
 
1:03 PM
No -12 should give spaces after the number
Not before
 
>>> print(f'A {4.3:<12.3f} number')
A 4.300        number
good catch, I didn't know they behaved differently (and I never use percent formatting)
 
@AndrasDeak thanks that worked
 
no problem
 
Percent formatting is very useful... For determining whether the asker of a question is using a tutorial from 1995 ;-)
 
user10984358
If I have a dictionary of dictionary of dictionary and so on to some arbitrary level, is there some way I can do str.strip() for all of the values in the dict?
 
1:07 PM
@TheNamesAlc yes :)
 
@TheNamesAlc not without some recursive function of your own, no
 
@Andras well - don't need recursion
 
user10984358
@AndrasDeak I was hoping it had to come to this
 
user10984358
how do you do so without recursion?
 
with a stack
 
1:08 PM
@JonClements sure, it can be any kind of graph traversal. But my impression is that "arbitrarily nested" usually lends itself better to recursive solutions. And I have dysrecursia, so this is something.
 
user10984358
explicit stack or recursion are not the same?
 
hmm, yeah, I wanted to better understand that stack-based DFS mentioned here earlier
@TheNamesAlc not at all. One will break in python after ~1000 levels, the other won't
 
Hi All,

is their a way you could read html css using python BeautifulSoup for spmething specific.
for eg: check whether text is left aligned or right aligned
or font size ??
 
@MunishGupta I don't know, but I'd google for a "css parser"
 
user10984358
ah, RecursionDepth Exceeded something
 
1:09 PM
Font size seems difficult, because that's mostly decided by the user's settings
"Good" CSS should not override what the user considers a readable size
 
@TheNamesAlc yeah, because C stacks are more expensive than tuples
 
@MunishGupta not really - unless the site source expressly has it inlined that you can parse out, you'd have to somehow work out based on classes and hierarchy what the browser decided was the ultimate styling
 
@Kevin: you are checking whether xyz site has a font size of 10 px or 12px.
 
@AndrasDeak Also, keeping your own stack avoids all those performance-killing function calls, so will be much snappier.
 
is "dysrecursia" a thing @Andras?
 
1:14 PM
@JonClements it is now
 
It is well worth learning the idioms for recursion-less graph traversal in Python (DFS and BFS). I only crossed this bridge myself in the past year, but really worth it.
 
I'm pretty sure I've hacked together at least one of those for Advent of Code...
 
@AndrasDeak just did some research on CSS parser and this is it. But I could not find any good tutorial or article on how to implement it. Can you share something.
 
@MunishGupta sorry, when I said "I don't know" I meant it. I don't have anything to do with the web.
 
@AndrasDeak np. Thanks for the direction.
 
1:19 PM
@TheNamesAlc If you want to navigate through nested stuff and don't mind using another package, Boltons has as remap method that might do what you want.
 
d = {1: {2: {3: " foo "}, 4: " bar "}, 5: {"qux  ":6}}
stack = [(d, list(d.keys()))]
while stack:
    if not stack[-1][1]:
        stack.pop()
        continue
    current_dict, keys = stack[-1]
    print(current_dict, keys)
    key = keys.pop()
    child = current_dict[key]
    if isinstance(child, dict):
        stack.append((child, list(child.keys())))
    elif isinstance(child, str):
        current_dict[key] = child.strip()

print(d)
#result:
#{1: {2: {3: 'foo'}, 4: 'bar'}, 5: {'qux  ': 6}}
 
user10984358
that seems like something I could use till I come up with my own function to do this, appreciate that @IvoMerchiers
 
Hacky little stack-based approach for @TheNamesAlc
 
def depth_first(node):
    lifo = [node]
    while lifo:
        node = lifo.pop(-1)
        print(node, end='')
        lifo.extend(reversed(node.children))

def breadth_first(node):
    # use FIFO queue to keep track of nodes to visit
    fifo = [node]
    while fifo:
        node = fifo.pop(0)
        print(node, end='')
        fifo.extend(node.children)
 
user10984358
is it years of dev exp. or you guys just paid more attention in Algorithm / Data Structure class?
 
1:22 PM
I just really like trees.
 
SEO: nice stack based iterative not recursive BFS DFS ^
 
Oh, this will only work on a tree-like dict, by the way. If there are any cycles it loops forever.
For example d = {}; d[1] = d
 
user10984358
do some dicts have that ?
 
only if you hate yourself
 
It's pretty rare for a dict to have a cycle "in the wild"
You usually have to construct one intentionally
 
1:23 PM
@TheNamesAlc Did a refresher while prepping for Amazon interview
 
For instance, if you're loading your data from json, it definitely won't have a cycle
 
user10984358
ahh, the same reason as to why sys.exit() can be used and is not used
 
hmm?
 
user10984358
@PaulMcG a friend of mine interviewed for Amazon at Seattle last week and they asked him minesweeper BFS/DFS related question
 
user10984358
@AndrasDeak I mean you could use sys.exit() in a code but is there an actual use for that?
 
1:27 PM
Usually if I want my program to terminate early, I'll throw an exception or return from the main function. Mostly I use sys.exit while I'm parsing the command line arguments
 
@TheNamesAlc Well, yeah, that comes up rarely. But having a non-tree-like (i.e. not cycle-free) graph is not that far-fetched. You should keep that case more in mind.
 
turns out it was an XY problem all along. Replaced my .idea folder with one from another project and suddenly IntelliJ decided to stop ignoring my PYTHONPATH
 
@TheNamesAlc I had to use os._exit() recently to exit out from an interactive python -i mini-REPL.
 
user10984358
well TIL then :), I will come up with some recursive approach just to see how "good" my code stacks against Kevin's
 
If your object has a maximum depth that's smaller than 999, then you probably won't hit the max recursion depth
 
user10984358
1:29 PM
its 20 at most, apparently arbitrary means a lot to you guys than it does to me:D
 
the essence of arbitrary is that there's no upper bound
 
Some pyparsing parsers need to bump the recursion limit to 2000. There's nothing sacred about 1000, more important is that there be some limit.
 
I got Kevin'd by @PaulMcG but, since I typed it out anyway (and it should work), an example;
d = {
    'a': {
        'b': {
            'c': 'test1',
            'd': 'test2',
            'e': 'test3',
            'f': {
                'g': 'test4'
            }
        },
        'c': {
            'h': 'test5'
        },
    },
    'b': 'cabbage rules'
}



todo = [d]
while todo:
    nxt = todo.pop()
    for k, v in nxt.items():
        if isinstance(v, dict):
            todo.append(v)
        else:
            nxt[k] = v.replace('test', 'cabbage')
 
If the data is coming from an untrusted source, it might be worthwhile to use the overflow-proof iterative approach even if you think "normal" input won't break. Maybe the first thing an evil user will try is submitting {1:{2:{3:{...999 more layers here... :{1000: "haha"}...}}}}
 
if you need to, you can also put "guards" in place... so either type or length checks, eg: if len(todo) > N then raise a custom exception
 
1:39 PM
Tried it in boltons as well since I wanted to test it myself:
 
@IvoMerchiers please see our code formatting guide for chat and practice in the sandbox if necessary
 
from boltons.iterutils import remap

def visit(path, key, value):
    if isinstance(value, str):
        return key, value.strip()
    else:
        return key, value

d = {1: {2: {3: " foo "}, 4: " bar "}, 5: {"qux  ": 6}}
remap(d, visit)
 
Does the boltons approach work on a very deep dict? For example d = " haha " followed by for i in range(2000): d = {i: d}
 
perfect
 
@PaulMcG I'd imagine with pyparsing it'd be quite interesting to find a practical TEO there
 
1:44 PM
Not familiar with that TLA
 
Thief executive officer?
 
@Kevin Just tested that and it seems to work
 
@PaulMcG not familiar with TLA either?
 
Three Letter Acronym
 
head butts desk - of course
"tail end optimisation"
meh... I mean TCO - sighs
 
1:50 PM
That's okay - not having that in native Python, I rarely think of it, and I would have thought you meant something pointy-haired-boss-speaky like "Total Cost of Ownership"
 
just me forgetting the terminology... sorry
to clarify - what I meant (if not using the right 3 letters) was en.wikipedia.org/wiki/Tail_call
 
user10984358
@Kevin if isinstance(child, dict): so if my nested dicts are defaultdicts with a lambda function i need to change this accordingly right?
 
Hmm, if I reengineered pyparsing to keep my own stack, that could maybe be within reach, plus a big performance boost avoiding all those function calls. (more than a weekend project though)
@TheNamesAlc Why not experiment and see if a defaultdict will isinstance as a dict?
 
@TheNamesAlc isinstance(child, dict) evaluates to True if the child is a defaultdict, so you shouldn't need to change that
 
user10984358
it still goes inside the loop, i am confused, i just tried with defaultdict and dict
 
1:57 PM
isinstance checks for subclasses
>>> isinstance(defaultdict(list), dict)
True
 
user10984358
tried the other way and it gave False, handy
 
"the other way"?
 
user10984358
>>> isinstance(dict, defaultdict)
False
 
when comparing types you'd need issubclass anyway...
 
Oh, I was worried for a minute there that you were doing if type(child) is dict:, which is unrecommended
 

« first day (3314 days earlier)      last day (1633 days later) »