« first day (3798 days earlier)      last day (1375 days later) » 
06:00 - 20:0020:00 - 23:00

20:00
Simplifications I glossed over because they confuse me: locals are magically stored in both a dict and an array, and I don't know which one is the "real" one. I don't know when frames are actually created, when they're zombified and later revived, and which of its attributes are still valid after this process. I don't know where closures go when you're not looking at them.
I can't find what's correct in the PEP8 doc:
answer = f(a=1,
           b=2,
           )
or
answer = f(a = 1,
           b = 2,
           )
the difference is the spaces around the =. Anyone have any thoughts?
@inspectorG4dget absolutely not
@AndrasDeak the former is preferred?
Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter:

# Correct:
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# Wrong:
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)
@inspectorG4dget yeah but that indentation looks suspect to me. But it might be correct because the indentation rules are forgiving
@inspectorG4dget PEP8 says no space around assignment inside a function call
20:11
but the example is in a single-line call. I sometimes have multi-line calls - these benefit from teh added spaces by way of readability
@inspectorG4dget The examples at python.org/dev/peps/pep-0008/#indentation keep the closing parenthesis on the last kwarg line. Either that or they use a hanging indent where the first kwarg is on a new line. Not sure about what's allowed, though.
@inspectorG4dget they don't benefit :P
# Correct:
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )
from pep8. i think that's fairly clear on this.
@ParitoshSingh ah, thanks, I didn't find that one
yikes
My personal preference for multiline bracket closing is "or it may be lined up under the first character of the line that starts the multiline construct"
20:12
looks pretty bad, yeah
@ParitoshSingh many thanks
#i.e.
answer = f(
    a=1,
    b=2,
)
same, ive kind of started favouring stuff like this lately -
oh...kevind
@Kevin yeah, that's the hanging indent I think? That's what I've been using too for a while
i think i saw that first in black, so it's been a very recent thing for me
20:13
Ahem! "Although practicality beats purity."
My brain grasps aligns-with-first-character more readily, so I award it the practicality prize
(Prize valid only within my personal reality)
Suppose I want to iterate through something a certain number of times, think islice, but I want to repeat the last thing if I run out of things. Is there already a better wheel out there? Or does anyone have a better wheel than this:
from itertools import islice

def repeat_last(things):
    for thing in things:
        yield thing
    while True:
        yield thing

[*islice(repeat_last([1, 2, 3]), 5)]
# [1, 2, 3, 3, 3]
I vaguely feel as if iter can do something useful here
i like how clean that looks.
fwiw, I've been using "closing bracket aligns with opening bracket +1 char -> (i.e. the same column it would have been on if the list were empty", and "no spaces around = in function args unless in a multiline call (in which case spaces are required)"
20:17
yeah thats how my editor auto-indents the closing brace for me
so it should be decently common-place too i assume.
I'm quite liberal with spaces around = because it did not occur to me that there would be different rules for the assignment statement and named arguments
equals is equals
@piRSquared I'd go with using yield from itertools.cycle((thing,)) to replace that while loop, but that's about it
yield from itertools.repeat if you go that route*perhaps
@ParitoshSingh YES! THIS!
i personally would probably just use the while loop though, to be honest :P
and yeah Kevin same, when i learnt about spacing around = i didn't realise that "wasnt" the norm for args
i picked it up pretty quick though, because it was some kind of linter that turned my entire code file yellow. every. single. line.
20:27
def repeat_last(x):
    return iter(lambda g = iter(x): next(g, x[-1]), object())

x = [1,2,3]
i = 0
for item in repeat_last(x):
    print(item)
    i += 1
    if i > 10: break
Been a while since I wrote a proper coding horror :-)
@Kevin that assumes that x is a sequence
True
otherwise you could just chain(iter(x), repeat(x[-1]))
first arg could probably just be x
But I don't see how that achieves my goal of creating an abomination...?
20:34
True
out of curiosity, what are you working on that you are trying to use a hold-forward for?
I'd like not to assume it is a sequence. BTW completely theoretical right now. I don't need this for any reason other than to satisfy curiosity.
Now we can bikeshed the whitespace in Kevin's lambda
I had a brilliant idea for a repeat_last that works with finite non-indexable iterables, but the core devs have foiled me by not implementing nonlocal walrus assignment inside lambdas
Maybe if I use a generator expression...
20:49
Included the limit but I still don't feel like it's golfed enough.
def repeat_last(things, times=None):
    count = 0
    for thing in things:
        if times is None or count < times:
            yield thing
            count += 1
    while times is None or count < times:
        yield thing
        count += 1

[*repeat_last([1, 2, 3], 9)]
I'm confused. The first time I run the lines below in a jupyter notebook, nothing is written to the file. The second time I run it, the content gets written:

out = open('file.txt', 'w')
out.write('oh')
why is that the case?
I think you need to close the handle
why would it be closed the second evaluation and not the first?
The reopening of it, closed the first one
interesting!
20:51
import itertools

def repeat_last(x):
    return (g:= iter(x)) and (r:=None) or (r:=next(g, r) for _ in iter(lambda: 0, 1))

x = itertools.islice(itertools.count(), 0, 5) #sample iterable with finite length but no indices
i = 0
for item in repeat_last(x):
    print(item, end=" ")
    i += 1
    if i > 10: break

#result: 0 1 2 3 4 4 4 4 4 4 4
checks out, thank ye!
Use with anyway
with open('file.txt', 'w') as out:
    out.write('oh yeah')
yes I know but I was talking with others and the behavior above happened and I wasn't sure why
thank you!
20:53
But... your question highlights exactly why with is best practice
I wanted to cram everything in the genexp but SyntaxError: assignment expression cannot be used in a comprehension iterable expression. Lame.
no doubt
cbg patch
@Kevin My head hurts
ive hit this interesting snag with my desire to learn how to mock tests properly, how do you do this when you are performing some kind of function that doesnt return anything.
Easiest example is I have is:
20:59
(g:= iter(x)) and (r:=None) create two local variables, g and r, without us having to use an assignment statement. for _ in iter(lambda: 0, 1) iterates over an infinite number of zeros until it reaches a one, and binds the value to a variable we never use. next(g, r) calls next on the actual iterator of x, returning either the next value, or the most recent value of r if x's iterator is out of values. r:= binds that returned value so we can use it in the next loop.
def to_file(df,name : Path)
   if name.suffix == ".csv"
     df.to_csv(name)
  elif name.suffix == ".xlsx"
    df.to_excel(name)
Dang, it's been so long since I've last seen 2-argument next that I thought it was equivalent to g.__send__(r)
typed that mvce out so give me a sec to see if i can confirm its formatted perfectly
I haven't ruled out the possibility of doing it without a walrus, but I don't have a clear idea on it. It would be easier if iter(x).__next__ accepted a sentinel argument like next() does.
for drop in g.__iter__(ade): # slurp,yum
21:03
but yea, I wanted to mock df functions to return some output I could run a test against, but since im dont even returning any values in the function i can't pull my mock stuff back out
If I use __next__(), I can preserve mutable state for a useful period of time. If I use next(), I can escape from StopIterations without a try-except. I need both of those but I can only have one.
and if i use mocking to change how this function works then I've just defeated the purpose of testing this function
@Kevin I don't follow, what can __next__ do that next can't?
df1.to_csv = MagicMock(return_value="write to csv")
wont give me back the testable output from that to_file function
@Skyler You can check if the mock was called though, right?
df1.to_csv.assert_called() or whatever
21:07
@Aran-Fey ohhh, can you
from the example I read it seemed like a function like that:
from unittest.mock import MagicMock
thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
thing.method.assert_called_with(3, 4, 5, key='value')
i thought that means it checks to assert by calling that function with the input you gave
but it actually cehcks to see that you called that function before
yeah
@Aran-Fey My intermediate goal is to acquire a callable that returns a successive value of x every time it is called. callable = iter(x).__next__ works, (until it crashes with StopIteration), but it's not so easy to create an equivalent callable with just next. If you do something with iter-within-lambda, for example callable = lambda: next(iter(x)), then it just returns the first element of x forever.
If I had full freedom to use statements, I could ofc do g = iter(x); callable = lambda: next(g). But my abomination is expressions only. And I don't want to use walrus operators because I already did that and got bored.
that makes things much much wieldy, though i still have a question
actually 1 sec, first let me see if this works
callable = lambda g=iter(x): next(g) may or may not work depending on its surrounding context and how long you need g to stay alive. My first try, it had to go in a comprehension, so it kept getting collected too soon.
If none of this makes sense, I assure you that you aren't the only one that thinks so
Ah, I didn't realize you were trying to get rid of the walruses
21:18
Perhaps I would still have scoping problems even with a __next__ that supports sentinels. Oh well.
ok yea, im getting the hang of this, thanks aran
1 question though
i noticed when i did to_file(testfile[0],filename[0]) the mock test passed
for each 1 by 1
but if i tried to do map(to_file,testfile,filename) then my mock call assert failed
is that just because I made a generator but never actually iterated through it?
Yeah, map doesn't do anything until you iterate it
My most disliked feature when 3.X first came out! I used map in the REPL a lot and it bothered me that I could no longer see a nice clean list output
btw is list(map(...)) the pythonic way to do said iterating, in my case I dont actually want a list and you cant use the starred expression at the start of a map
to just iterate through it
The pythonic way of doing list(map(func, seq)) is a list comp: [func(x) for x in seq]
Or a for loop if it aids readability/flow
@Skyler for val in map(...):, that's the whole point
21:27
Oh, if you don't actually want the list, then definitely use a for loop
so basically just a for loop with a pass in it
I find it odd that you call to_file multiple times before checking if the mock was called
@Skyler why do you want to iterate and discard the result?
@AndrasDeak because this function doesnt create any output
if you're looking for a side-effect it's better to use an explicit loop
21:28
and i had multiple inputs
for file in files:
    to_file(file)
making comprehensions and map have side-effects is bad
I don't fully understand the goal here, so I'll just say you can usually refactor for whatever in whatever: pass into something more meaningful, and leave it at that
(though it might not be obvious unless you're Dutch)
Think to_file as a serialiser that prints to disk. They just want to call such a function multiple times.
That's not what map is for.
Why call the function multiple times inside one test case, though?
and actually I can just do my assert_called_with
@Aran-Fey i mean this function performs such basic logic subtests seem fine
like if the assert fails you will still see what caused the bug
21:32
idk what subtests are, so no comment
You might already know this, but a regular loop can iterate over multiple input iterables at the same time if you use zip.
here though I'm not really using unittests assert methods though so its just the idea carrying over
Just in case you were using map because you thought that was the only way to provide multiple iterables
@Kevin yea, i know, i just was thinking there was something kind of clean about reading:
21:34
But how can you create subtests if you never iterate over your map(...)? Something isn't adding up here
for test in map(to_file,testfiles,testnames):
    pass
or the like
I'm actually rather fond of map myself but it's quite out of favor in idiomatic Python
@Aran-Fey the whole point we were talking about is whats the right way to iterate over the map if you didnt want to save an output
@Kevin but not in this situation, surely
this is the equivalent of (DON'T DO THIS) [print(k) for k in lst] (REALLY, THIS IS BAD)
I'll endorse Andras' proposal of putting to_file inside the loop, and I'll throw in a zip, giving for a,b in zip(testfile, testname): to_file(a,b)
Oh and consider pluralizing testfile and testname if they are lists
21:37
In fact you can't implement subtests with map at all, since the map will call the function you're trying to test before you have a chance to do a with subTest
(Technically it's "fine" as long as your assertions are inside the with, but ugh)
yea, that's kind of the problem with these loops in the first place, you are doing all the logic then asserting to make sure things were called inside to_file
but there isnt really a clean way to do the assert inside the for loop here
so it kind of implies you really should just do each test in sequence
Wouldn't that also imply there isn't a clean way to do it outside the loop?
@Kevin you'd check each assert_called_with one by one, but for everything up until then you can pretty cleanly bundle them into lists
for file, name in zip(testfiles, testnames):
    with subTest():
        to_file(file, name)
        mock.assert_called()
problem solved
@Aran-Fey i dont think the mock.assert_called_with works here though because I'm basically testing for different mock functions that get called inside to_file
so its like mock.to_csv.assert_called_with for one and mock.to_excel.assert_called_with
and that's pretty ugly to try and setup unless i do something like make a list of function references
21:46
How about
for file, name, mock_name in zip(testfiles, testnames, mock_names):
    with subTest():
        to_file(file, name)
        getattr(df, mock_name).assert_called()
ah, never actually used getattr before but that could work. in your opinion is that better then just defining something right before the for loop like:
mock_names=[testfiles[0].to_csv,tesftiles[1].to_excel]
yes, definitely. Much less code for the same effect
basically mock_names=["to_csv","to_excel"] is the equivalent input using your suggestion right
this works, and is pretty clean to read, thanks
it also makes declaration of the mocks tests easier since they can actually be done in the for loop and use getattr the same way I think right?
can you do getattr(df, mock_name) = ...
21:53
You'll need setattr for that
But I would always mock all of the dataframe methods, and assert that only the correct method was called
Maybe to_file does df.to_csv() followed by df.to_excel(), who knows?
true, over the course of rewriting a more complex function that could totally happen
though that's a bit trickier or at least sounds like you now need a second loop for the getattr step
and a way to flip assert_called and assert_not_called
definitely makes the test more complex, yeah
for today i might leave that as good food for thought though
this has already been pretty enlightening
22:23
De-walrused, kevin-inspired
from itertools import count

def repeat_last(x, n=None):
    g = iter(x)
    r = None
    for _ in iter(lambda c=count(): next(c), n):
        r = next(g, r)
        yield r

[*repeat_last(iter(range(5, 8)), 6)]

# [5, 6, 7, 7, 7, 7]
kevinspired
^ now a thing
also applicable when kevin is involved in a conspiracy
no imports
def repeat_last(x, n=None):
    g = iter(x)
    r = None
    i = 0
    while n is None or i < n:
        r = next(g, r)
        yield r
        i += 1

[*repeat_last(iter(range(5, 8)), 6)]

# [5, 6, 7, 7, 7, 7]
rbrb
06:00 - 20:0020:00 - 23:00

« first day (3798 days earlier)      last day (1375 days later) »