« first day (2491 days earlier)      last day (2461 days later) » 

6:16 PM
@PM2Ring - If there is anything contractual about a decorator, it would mostly be that whatever it returns should be a callable with a signature that would accept the same args as would have been passed to the original function, and would return data of similar type as the original function.
 
And that's less contractual and more pinky swear. Such is life in pythonland.
 
pythonland, pythonC, python this motheryamming plane
 
@PaulMcG I mentioned the compatible signature, but I forgot to mention the return type. I'll fix that...
 
I'm mildly disappointed that the byte code for decorating a function is not identical to the byte code for manually doing the assignment yourself
 
how do decorators with extra arguments work?
perhaps that's the reason, or something similarly non-vanilla
 
6:22 PM
Using decorator syntax saves you a STORE_FAST and a LOAD_FAST. At a glance I think this is true for both argumentless decorators and argumentful decorators.
 
when the AST of your function has less fluff when using decorators, that's just false advertising
 
When I started work I had just finished New Game (season 1) and I thought my work would be like that. I was super excited... but then I realized my work life would be kinda more like Kobayashi... (minus the mean manageR)
 
@Kevin argumentative decorators?
 
@PaulMcG Done, and I threw in a ref to the Liskov substitution principle for good measure. :)
@AndrasDeak There's no such animal. :) So-called decorators that take args are really decorator factories: they take some args and return a decorator function, and that decorator function does the actual decorating.
 
Decorators with arguments is the #1 concept on my list of "things I understand but cannot begin to explain to another person"
 
6:26 PM
ah, I see, thanks
I never looked into that
well, I have used lru_cache with a maxsize multiple times, but that didn't affect my ignorance on the matter
 
Here's one I used yesterday:
#Simple memoization, with initialised cache
def initialise(cache={}):
    def memoize(f):
        def memf(x):
            if x not in cache:
                cache[x] = f(x)
            return cache[x]
        #memf.func_name = f.func_name
        return memf
    return memoize
 
Before you can understand decorators, you must understand functions as first-class objects, and that can be a veeeery foreign concept depending on what languages you're coming from (if any)
 
And you call it like this:
@initialise({1:(1, 0), 2:(1, 1)})
 
@Kevin I believe I understand that just fine
 
that mutable default argument seems dangerous...
 
6:28 PM
that's what makes it a cache
is it not?
 
it doesn't have to be a default argument though
 
@Rawing Nah. You want it to remember stuff.
 
maybe not, there's 3 levels of nested functions there so I don't claim to understand it deeply
 
@Rawing It doesn't. But it's faster than any other caching technique.
 
def initialise(cache=None):
    if cache is None: cache = {}
Otherwise all your memoizers will share the same cache
If one is not provided
 
6:31 PM
ah, because calls to the memoizers are during decoration
so "data prevails between calls" means "cache prevails between decorations"
 
No, the definition of the default value for cache is defined when the initialise def is parsed/compiled, not when it is called. So all callers of initialise that don't pass in a custom initializer dict will share the same cache dict
 
@initialise()
def f(x):
    return 'f'

@initialise()
def g(x):
    return 'g'

print(f(1) == g(1)) # True
 
@Rawing Here are some speed tests I did a while ago for Python 2: stackoverflow.com/a/34036910/4014959 That code needs some minor changes to run on Python 3.
 
@PaulMcG yeah, I'm aware of how and why mutable default arguments can bite you, I was just trying to wrap my head around the implications
(without having to actually dissect or run the code)
 
I figured, just didn't get your other comment, but I see it was about the cache/decorating/memoizing in general, not the mutable arg default
 
6:34 PM
it was about both :P
I tend to show more-than-ideal amounts of stream-of-consciousness behaviour, so it's generally not a huge loss to not understand what I'm talking about :D
 
To run that old timeit code on Python 3, you'll need to change .func_name to .__name__
 
Hello mates!
 
hello dudealoo
 
Can you give me a hint? Trying to find a solution for my script
 
if it's python, we can try
 
6:38 PM
We can do hints, sure. If you wanted pointers, you'd have to go the C/C++ rooms.
8
 
I know it's an old joke, but I just couldn't resist.
@PM2Ring I'm too lazy to verify that, so I'll just take your word for it
 
@PaulMcG That's certainly, undeniably true. But since only one function in the script is being decorated it doesn't matter. :) I must admit that doing the if cache is None: cache = {} in the decorator factory is a good idea. BUt really, when I want caching & speed, I don't use a decorator, so it's not an issue that I'm using a mutable default arg.
@Rawing Fine. :) But if you want to run that timeit code I linked earlier, I've since fixed it to run properly on both Python 2 & Python 3.
 
Given:
xlsx file with 2 tabs inside: Sheet1 and Sheet2
Sheet 1 has 600 rows of data
Sheet 2 has 3029 rows of data
Aim:
If value of a sheet1 column sp2 == to a value in a sheet2 column sp2
copy the whole row from sp2 and paste it in sheet 3
There has to be 588 matches, just as the amount of rows in sheet1
So far I get to this point. I don't know where to move further
https://pastebin.com/TJuMhWXZ
Would be grateful if you could give me some hints
 
Ok, the next thing you should do is figure out how to copy a row from sheet 1 to sheet 3.
"How do I do that?", you ask. I don't know.
 
6:50 PM
Exactly!
 
Openpyxl is surprisingly bad at copying cells.
 
If you wanted to ask how to copy a row from one sheet to another, you should have asked "how do I copy a row from one sheet to another?" rather than "where do I move further from this point?"
 
Do you just need the cell values or the other stuff (font, color, border, etc) as well?
 
My bad:)
Nope, only values
 
Well, that's a simple loop then.
 
6:52 PM
you also seemed to ask "value of a sheet1 column sp2 == to a value in a sheet2 column sp2" but your test appears to check for equal values in the same row, which is probably what you need, but you should be precise
OK, I realize that the check is manually element-by-element
 
Yes, I think that I am not comparing values in a right way. I need to take the first value from sheet1 row 1 column 10 and compare to all elements in sheet2 row i column 16
 
ah.
 
You should build a set of all values from sheet2
 
if match -> copy to sheet 3 and continue
if not match -> move to the next element
 
that's why precision is key
 
6:56 PM
Once you've collected them all in a set, you just do if value_from_sheet1 in set_of_sheet2_values: copy_row()
 
Hmm, interesting, Never used sets before.
So:
Build a set from sheet2
if value_from_sheet1 in set_of_sheet2_values: cop

But how will I know what row should I copy?
 
I think solving this problem is best done in two independent steps:
1) master the interface of the library so you can load, copy, paste, update, delete, and save rows with ease
2) work out the algorithm for which rows should be compared against which other rows and put into which result row. You may even want to do this initially with dummy data that only makes use of simple built-in types such as lists and dicts, so there's no chance of you getting confused by the more specialized interface from step 1
Because the problem of "how do I match some rows against some other rows and put them in a third place?" is really two problems
 
@RuslanDoronichev I think you're taking my pseudo-code a little too literally. You'll need a loop and a variable to keep track of which row you're on of course - not much different from your current code.
But instead of comparing the values one by one with ==, you just look them up in the set
 
Thank you guys, for the hints. Now I know where to move further:)
 
pffft raw strings and regex.
>>> re.sub(r'~(.)', r'\\1', '~~')
'\\1'
>>> re.sub(r'~(.)', r'\\\1', '~~')
'\\~'
 
7:07 PM
raw strings are the best thing that could happen to regex
 
so I am converting ~ to \ as an escape character...
 
hm?
 
and ... r'\\\1' because \1 for a back reference and `` for the replacement but it needs to be doubled... of course...
so now I just need to write 3 backslashes in the replacement instead of 6 :D
 
that's still an improvement by 2 ;)
 
I wish python would get first class regular expression literals
and i'' strings
could use i'' strings in replacement
 
7:10 PM
Every day that I don't have to write a regex containing slashes is a good day
 
re.sub(r'~(.)', i'\\{1}')
 
what are i strings?
 
OK, I finally understood the problem
we could have a no-op character to put between \ and \1
 
I actually like raw string literals better than the usual regex literals enclosed in slashes. I'd rather escape a single or double quote than slashes
 
7:28 PM
@Rawing sigh.
obviously you haven't used perl
 
that would be correct :)
 
in perl, you can pick any character as the delimiter.
 
henlo hebhobs
 
if you choose [], {}, <>, () - they're paired
so you can do s[~(.)]<\\$1> (that would be substitute ~(.) with \\$1.
 
Jun 9 '16 at 11:39, by PM 2Ring
Note that if we don't use a raw string for the regex we need 8 backslashes in a row: '\\\\\\\\(\d+),(\d+)' That's hard to read and too easy to mess up.
 
7:30 PM
Oh lord. I'm going to stick with my raw string literals, thanks
 
notice how perl allows using $ instead of \ in the replacement
 
I hardly ever find myself escaping a quote (single or double), so it's really not a problem
 
Raw strings are wonderful, but they still have their limitations: you can't end a raw string with an odd number of backslashes.
 
And in the worst case scenario, you can always resort to raw triple-quoted strings: r"""some" regex' with" quotes""" :))
 
nice perl :D
"\N{LATIN SMALL LIGATURE FI}" =~ /fi/i; # Matches
 
7:36 PM
@PM2Ring Luckily that's not a problem if you're using them for regex. Just add another backslash.
 
@Rawing True. And there's another cute thing in Python 3: raw f-strings.
 
Oops, sorry about the double ping.
that was a pretty insignificant edit.
 
-1
Q: "from import" breaking my code

iNeed2LearnToEatI'v set up a class just for global variables. Im using #from b import xlname, xlstart, xlend to grab a variable from a different class (b.py). The modul runs the whole file instead of just grabbing the functions i need (xlname,xlstart,xlend). Because all of file b.py gets ran it is breaking ...

umm?
 
>>> b = r'test \d'; s = fr'\b\s{b}\sc'; print(f'{s!r}')
'\\b\\stest \\d\\sc'
You can put the r & f in either order.
@AnttiHaapala Impressive!
 
Alright, let me decypher this... From what I can tell, f'{s!r}' is equivalent to repr(s). I swear you're just throwing these fs around to confuse me
 
7:43 PM
@AnttiHaapala that answer... after reading it, my feeling is now :
user image
3
 
I need a one year vacation twice a year
 
@AnttiHaapala FWIW that's what perl was designed to be good for
@Rawing the f-bomb
 
finished everything for my project a week early :\ boring
 
@Rawing "f'{s!r}' is equivalent to repr(s)" Indeed. But I think it's a little faster than the function call.
 
7:58 PM
how is that even possible?
 
Because the f-string machinery doesn't have to perform the repr function look-up, or make the repr() call. It can directly dispatch to the object's __repr__ method.
 
oh, I didn't realize that the repr-to-__repr__ trick was "expensive"
I know we're talking about marginal differences, but still
 
It's not that expensive, and I assume it happens at C function call speed, rather than the significantly slower Python function call speed.
But looking up any global object takes a little time, even built-in functions, because Python always looks in the local namespace first. So you can speed things up a little by caching often used globals as locals. Using default args is a nice way to do that, since the caching occurs when the function definition is executed, rather than each time it's called.
 
yup, I've already seen that here, thanks :)
 
@AndrasDeak also, the f-string is parsed at compile time...
 
8:08 PM
sure, but repr(s) isn't parsed at all
 
... so actually f'{...!r}' just executes one opcode
which is FORMAT_VALUE (2)
which does repr on stack top
so it is much faster, because it doesn't need to call a function at all, let alone do the name lookup
 
I'll stick with my working assumption of "it's magic"
 
wim
I don't like f'{x!r}' because the whole point of f-strings is that you can just do f'{repr(x)}' now
 
@wim but it is slooow
 
wim
so what
 
8:12 PM
sloow
 
wim
premature optimization
 
sloow
 
wim
Python is slow. If you need performance and you're not getting it in Python, switch to golang or something. Don't fluff around with f-strings for marginal performance gains.
 
FWIW, we've had '{!r} for ages, the format function & method support it.
 
umm lol
guess what...
 
wim
8:14 PM
yes, and that's the only reason it made it into f-strings
 
In [3]: %timeit f'{a!r}'
Traceback (most recent call last):
  File "<unknown>", line 1
    f''''
 
wim
and the only reason it came into str.format was probably that 'blah %r' % thing supported it
 
idk what's happening there
In [2]: %timeit repr(a)
107 ns ± 5.68 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [4]: %timeit f"{a!r}"
12.3 ns ± 0.428 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
with a = ''
 
wim
yes, function calls are expensive in Python. so what?
 
and we come back to the one true sad fact:
 
wim
8:16 PM
if you don't like that, then write in assembler.
 
due to people liking monkeypatching so much it is impossible to speed up function calls
it is the stuff that no one needs that makes this slow
how many times have you replaced __builtins__.repr
 
so it's less "people liking", more "allowing"
which is good; we like freedom, yes?
 
I like speed
 
I might have to start agreeing with wim now :D
 
wim
I like flexibility / readability
if I want speed, I focus on speed only for the stuff that really needs it
and I'll tune it, or put it in Cython, or something like that. not fluff around with silly micro-optimizations.
 
user3657941
8:20 PM
When people learn to drive, they don't do it on a race track.
When programmers learn to program, they often try to start on a race track.
 
Antti's fairly good with a wheel
 
I wish python would change so that it would be possible to optimize it better.
the readable python
 
perhaps if we added typed names..... :P
 
with es5, it is quite easy to optimize javascript
 
user3657941
Speaking of converting Python to a typed language, a Java programmer added a bunch of comments to one of my answers. Should I just ignore them? Or should I flag them?
 
wim
8:23 PM
but we have other projects for that
e.g. pypy, cython
they are focused on optimizing that stuff. just let python be python
 
the problem is: they're not compatible
 
wim
they are when people work on it. pypy now has python3 support and numpy support!
those projects need interest and funding , that's all...
 
@DavidCullen it's at your discretion if others mess with your code
 
C is the extreme end of optimization
the compiler is allowed to know what the standard library functions do,
and replace function calls with others...
 
user3657941
When I was writing a lot of Matlab, there were things that needed to be done more quickly. Matlab has the ability to interface with C code. We would write the stuff that needed to go fast in C. It looks like you can do the same thing with Python... ;)
 
wim
8:25 PM
you seriously might like pypy, antti
it's interesting their approach
 
too bad I need to write applications not scripts :(
wc -l requirements.txt > 100 always
 
wim
they make assumptions about what can probably be "safe" optimizations (e.g. nobody monkeypatched repr) and they put assertion guards around the optimized code, so that if the assumptions are ever wrong it falls back to the "slow" python code
this is a better way to get python fast than interfering with the beauty and simplicity of the language proper, IMO.
 
@DavidCullen Do you mean they were criticising your Python code for not following normal Java practice? That's definitely not on.
 
wim
so it can be like, if nobody monkeypatched repr, you get a "fast" code, and if somebody happened to do it, your code still works albeit slowly
 
@wim yeah that's how it could be
 
user3657941
8:31 PM
@PM2Ring: That's a good way of putting it: stackoverflow.com/a/45596108/3657941
 
I want sealed modules :D
 
user3657941
Someone who posted another answer doesn't like mine. But it seems that their reasons for disliking it are because it isn't written like Java.
 
well, one thing about your answer:
Errors should never pass silently.
you can pass almost absolutely anything for name...
 
user3657941
Okay. The OP wanted to guarantee type. He didn't ask about validation. If he wants to ask another question about validation, there seem to be plenty of people who want to provide that answer.
 
user3657941
For all I know, the OP had a validation layer before calling the constructor. That would be weird, but not unheard of.
 
8:40 PM
umm...
 
@AnttiHaapala sealed modules?
 
modules that no one can patch from outside
and no assignments to globals()
 
So like a black box ?
 
@AnttiHaapala oh hey I was just coming here to complain about trying to help someone who is doing exactly that with code I wrote and is surprised it won't work! :P
 
9:08 PM
though I mean it's python so meh. nothing is really "private" :|
 
welp it's closing time for me. Nighty night, cya on Monday rbrb \o
 
9:23 PM
git is yamming awesome
I just found git-grep
 
9:39 PM
that must search history too?
:o
 
exactly my use case
well, I was going for "grep in every file on every branch whatsoever", but it can do "grep in every commit of this file whatsoever" etc
it's magic
https://stackoverflow.com/questions/7151311/using-git-how-could-i-search-for-a-string-across-all-branches
https://stackoverflow.com/questions/10215197/git-search-for-string-in-a-single-files-history
 
9:54 PM
Also done for today - might check back in later, might not - rbrb
 
rbrb, Paul
 
wim
10:06 PM
-1 This violates duck-typing. If I pass a MyFloat instance, a subclass of float, you should not silently convert it to a float instance. You should just use my subclass. — wim 23 secs ago
 
@wim it's particularly bad since there's no documentation that it will happen like that either, heh
 
I agree. I think the most pythonic thing is, if the code messes up because someone passed the wrong thing, it's their fault (so long as said limitation was documented)
 
wim
garbage in garbage out
 
Queue: First In First Out
Stack: First In Last Out
Truck: Garbage In (Compressed) Garbage Out
 
I almost would say if you are going to do that sort of strict converting to make the kwarg names something like rating_int or something, though that feels dirty
 
10:11 PM
If you're going to do that kind of strict converting, don't use python!
 
wim
stacks are usually described as last in first out, not first in last out
 
@KevinMGranger this made me laugh as someone who worked in simulation stuff for a while, where that's the mantra "garbage in, garbage out"
amazing how many people think that trash data can somehow produce a meaningful simulation model
 
I think everyone has that mantra
 
wim
FIFO, LIFO, GIGO,...
@DavidCullen it's kind of ironic - you've misunderstood zen of python, and written this code with implicit conversions, and then said it was explicit .. LOL!
it's an explicit mistake, that's the only thing that's explicit. this is exactly the same mistake Python 2 made with converting bytes into text behind the scenes.
 
user3657941
ppd = PassPredictData(int(rating), str(name), float(lat), float(long), float(elev))
 
user3657941
10:26 PM
That was the OP's original idea, and admittedly explicit, but cumbersome if the constructor has to be called in more than one place.
 
You shouldn't convert your data anywhere near the constructor, you should convert it right after you load it from your input file or wherever
 
user3657941
There is still time to add another answer to the question
 
You don't want this class to accept only a few specific parameter types. What you do want is to load the correct types from the file
 
user3657941
Who is "You"?
 
wim
I think what he's trying to say is you gotta look at the bigger picture
 
10:29 PM
"You" refers to anyone who finds themselves in a similar situation
 
wim
O.P. wrote:

I want to ensure:

rating is an int
name is a str
lat, long, elev are floats
but everyone jumped to assume that it should be done in the class
in fact, it shouldn't. you have to ensure this from outside of the class itself.
 
Someone already added an answer like that, in fact it's the one with the most upvotes
 
wim
oh, right. I didn't get that far yet :)
 
user3657941
I think you folks need to look at the little picture.
 
wim
I like "single responsibility principle" en.wikipedia.org/wiki/Single_responsibility_principle
PassPredictData shouldn't be given the extra responsibility of handling/parsing/converting input data
the subject line of the question is not helping ("Enforce instance variable types when passing strings as parameters to constructor") as it's like it has already decided upon a solution to the underlying issue.
 
user3657941
10:38 PM
That would be the little picture. The OP had a clear idea of the end goal. He came to StackOverflow looking for the idiomatic Python (AKA Pythonic) way to accomplish that.
 
@wim there's been multiple laborious iterations of the title
 
wim
the Pythonic way to achieve something that is not Pythonic to do in the first place?
hmmm. It looks like David Cullen edited the title to suit his own answer :(
 
local discussion started here
 
wim
oh wait, my bad, that was O.P.
oh man, today's google doodle is amazing!
 
is it the hip-hop one?
 
wim
10:48 PM
yeah
 
okay
 
wim
when you switch the tab away and back again, the music spins up like a record
nice little attention to detail
 
wim
11:02 PM
I think the best answer is the one from a n00b stackoverflow.com/a/45597134/674039
 

« first day (2491 days earlier)      last day (2461 days later) »