« first day (2924 days earlier)      last day (2028 days later) » 

2:01 PM
@Kevin so lets say a.py was reading from a csv and do_some_difficult_work() transformed the csv and returned that transformed data... test.py imports a.py... each time i called test.py would a.py be doing that csv stuff... so if i call test.py 1000 times, would my csv be read 1000 times or just the once
 
A thousand times.
 
right
 
Running a script twice will cause it to do all the work it already did again, unless you go out of your way to avoid this. The conventional approach is to save the result to a file or database.
 
i figured writing it to a file was going to be the answer... i was wondering if i could make it so the result was kinda in the module, "compiled per se", so that it was read only once even if called 1000 times
(compiled/serialized, my terminology is wrong)
 
For example,
c:\Users\Kevin\Desktop>type test.py
import os

SAVED_DATA_FILENAME = "mydata.txt"

def do_some_difficult_work():
    print("Doing some difficult work... Boy this is really hard.")
    return 23

if not os.path.isfile(SAVED_DATA_FILENAME): #saved data doesn't exist yet
    data = do_some_difficult_work()
    with open(SAVED_DATA_FILENAME, 'w') as file:
        file.write(str(data))
else:                                       #saved data was created last time
    with open(SAVED_DATA_FILENAME) as file:
The first time this program executes, it calls do_some_difficult_work(). The second and third time, it skips calling that function and grabs it from the file.
Storing the data in the module itself is... Not impossible, but it's more of a parlor trick than something you would actually do in production-quality code. Self-modifying .py files tend to be much more of a headache than they're worth.
 
2:10 PM
@Aran-Fey You're right, recursion limit isn't about cycles, just stacksize
I feel betrayed
 
alright, cheers @Kevin back to the drawing board
 
@Arne Yeah, the name is misleading
 
if data["level"] == 3:
from levels import level_003 as level
levelreturn = level.level()
if levelreturn == "a":
data["recipe"] = 0
elif levelreturn == "b":
data["recipe"] = 1
elif levelreturn == "c":
data["recipe"] = 2
elif levelreturn == "d":
data["recipe"] = 3
data["level"] += 1
save()
s.qp(data["recipe"])
if data["level"] == 4:
from levels import level_004 as level
levelreturn = level.level(data["recipe"])
why am i getting a keyerror (note that in the if data["level"]==3: block is where I first defined data["recipe"]
 
Are you sure levelreturn is "a" or "b" or "c" or "d"?
 
@DanielNewell Hard to say without seeing the original indentation. Consult An Illustrated Guide To Formatting Code In Chat and try submitting your code again.
Remember that you can't mix plaintext and code in one multiline message
 
2:16 PM
sorry about the indentation
and yes, levelreturn is a
b c or d
if data["level"] == 3:
  from levels import level_003 as level
  levelreturn = level.level()
  if levelreturn == "a":
     data["recipe"] = 0
  elif levelreturn == "b":
     data["recipe"] = 1
  elif levelreturn == "c":
     data["recipe"] = 2
  elif levelreturn == "d":
    data["recipe"] = 3
  data["level"] += 1
  save()
  s.qp(data["recipe"])
if data["level"] == 4:
  from levels import level_004 as level
  levelreturn = level.level(data["recipe"])
ok now it works
 
Ok, there we go. I'll just clean up the previous attempts...
 
@JonClements I suspect a bug. ctrl+o is there in earlier versions as well
 
i gotta go
 
What line is the KeyError occurring on? Is it the last one?
 
2:19 PM
@AndrasDeak yeah it is.... shadow found something on ipython's issue tracker ^^^
 
If the only time you assign to data["recipe"] is inside the if data["level"] == 3: block, then it's possible that data["recipe"] doesn't exist when you're in the if data["level"] == 4: block.
 
@JonClements good, good :)
 
Unless you have reason to believe that the first block will always always always execute before the second block. Just going from the information available to me, that's not a certainty, but maybe you can draw different conclusions based on the structure of your data.
 
@JonClements oh this is great. I learned ctrl+o from that exact issue :) But I was searching for an unrelated reason, I merely wanted to know how I can force multiple single-line statements to be a single block. I never read the actual bug report :D
 
heh :)
 
2:23 PM
it seems 7.1 might come out as early as this weekend
 
BTW, scattering import statements through your code is not recommended. import statements should almost always be placed at the top of the file. There are some excdptions to that rule, eg importing modules that are only used rarely, or only when the module is run as a stand-alone script, but even then you put the imports at the top of the function that needs them, or in the latter case, at the top of the if __name__ block. You don't mix them into the normal flow of your code.
 
2:43 PM
A puzzle: is it possible to construct a tuple that contains itself? e.g. t is t[0] is True.
 
Also, variable names like "x_001", "x_002", "x_003" are something of a red flag that your code could refactor to use a list x and reference x[0], x[1], etc.
 
It's easy enough to do with lists: seq = []; seq.append(seq). But you don't have the benefit of mutability here.
 
You could have a tuple containing a list containing a tuple
t[0][0] is t
 
Sure, as long as you've got a mutable item anywhere in the data structure, there's an opening.
But I want immutability all the way down.
 
The linter always gives me trouble with "statement too long".
 
2:47 PM
I will accept solutions that temporarily violate immutability, perhaps by twiddling bits in process memory directly via ctypes
 
that's what I'm working on
 
Rebinding the name tuple to a mutable type doesn't count though
9/10ths credit if you can hack tuple literals to create a different type
 
>>> import ctypes
>>> tup = 1,
>>> elemptr = ctypes.c_longlong.from_address(id(tup)+3*8)
>>> elemptr.value = id(tup)
>>> tup
((...),)
>>> tup[0] is tup and type(tup) is tuple
True
 
Beautiful :-)
 
I like that it has a recursive tuple repr
I figured I can drop the refcount part since it's self-referential
 
2:51 PM
You might have a bytecode-twiddling option without resorting to ctypes
 
@PaulMcG a, but for that you'd have to know what you're doing
@vash_the_stampede closed
 
I wonder if you can call pickle.dumps on tup and get a string that you can then use to create recursive tuples without using ctypes directly. I would try myself, but the Pythons on my machine don't seem to respect Andras' solution. It obstinately insists that tup is still (1,).
And then segfaults to add insult to injury
 
hmm
I used 3.7
 
2:58 PM
3.6, for me
 
3.5 and 3.6 works too. Windows perhaps?
 
Quite possibly.
bit-twiddling ctype programs have historically had about a 20% success rate on my machine
Oh good, it works on Ideone, so I can play around with it anyway
Traceback (most recent call last):
  File "./prog.py", line 7, in <module>
RecursionError: maximum recursion depth exceeded while pickling an object
Darn.
pickle works on recursive lists, so I hoped it would extend to all recursive types.
 
sys.setrecursionlimit(float('inf')), done
 
Try dill instead of pickle, it has some added smart w.r.t. pickling callable code, might also have bits to handle an impossible recursive tuple
 
I don't want to denial-of-service-attack Ideone... Unless they cross me.
I'll try dill, but it would be more fun to use only standard libs.
Or uh I guess by "I'll try dill" I mean "I'll see if Ideone has it, and cry if it doesn't"
 
user10177566
hello everyone
 
hello
 
user10177566
i am creating a twitter alert in python
 
user10177566
i did it
 
user10177566
but i want it to iterate over multiple twitter name
 
3:18 PM
If this is about any of your five questions in the past day, please read the room rules before asking
 
user10177566
yes i am going to post a link stackoverflow.com/questions/52876759/…
 
"yes" as in "thank you, I've read the rules before going further with my inquiry"?
 
user10177566
Yes i have read the rules...
 
OK, thanks
 
user10177566
somebody please can have a look.
 
3:21 PM
> Don't ask for answers to your recent Stack Overflow questions.
 
Somebody already has, you just linked to their comment
 
It's in the rules that you claim to have read.
 
user10177566
aah!
 
user10177566
sorry to bother you guys
 
user10177566
good bye
 
3:24 PM
see you
 
See ya
 
I'm 100 thousand percent sure we've had dozens of questions like this, and I'm also sure that most of them would make for better canonicals than that one. But I can't find any of them. Anyone have a dupe?
 
3:40 PM
Did that guy ak333 just ask how to define a function?
 
we don't know and they've left
 
if data["level"] == 3:
  from levels import level_003 as level
  levelreturn = level.level()
  if levelreturn == "a":
     data["recipe"] = 0
  elif levelreturn == "b":
     data["recipe"] = 1
  elif levelreturn == "c":
     data["recipe"] = 2
  elif levelreturn == "d":
    data["recipe"] = 3
  data["level"] += 1
  save()
  s.qp(data["recipe"])
if data["level"] == 4:
  from levels import level_004 as level
  levelreturn = level.level(data["recipe"])
can someone help me with the code
 
^ no mcve
 
data["recipe"] won't work in the second block
 
"won't work"
 
3:42 PM
i get a keyerror
 
Are you setting data["recipe"] on that execution path?
 
@DanielNewell I already told you why I think it's broken: the second block can run independently of the first.
Consider a simpler example:
def f(x):
    d = {}
    if x == 3:
        d["blah"] = 1
        x += 1
    if x == 4:
        print(d["blah"])
 
Let me put on my "I've already told you what you're asking again" face. >:(
 
When you call f(3), this runs both blocks and the print call succeeds. But if you call f(4), it crashes with a KeyError.
 
3:44 PM
i never saw it sorry
 
@AndrasDeak isn't that a rooster's head?
 
If you're thinking "ah, but I can guarantee that both blocks will always execute in order", then you're going to need to provide an MCVE that demonstrates it
 
what is a mcve?
 
(never done that before, is it okay to do this ^^?)
 
3:45 PM
@JonClements no, that's Ɛ:^
reopening only to close again is usually an antipattern, but this already has two reopen votes
 
@shad0w_wa1k3r Nothing wrong with reopening and closing again. But we don't do it much in practice since it's hard to round up enough people to do it successfully
 
heh
 
if level == 3:
  import level3
  levelrecipe == "a":
if level ==4:
  import level4
  level4.level(levelrecipe)
 
@DanielNewell syntax error
as requested
 
:)
(routine rant about not being able to retract reopen vote)
checking meta for this
 
3:50 PM
Now Andras and I must fight to the death to determine whether reopening-then-closing is an antipattern or not
 
morning cabbage
 
@AndrasDeak oh okay... that just looks like an ascii representation of something one should really see a doctor about :)
 
No decision on this, so hopefully it lies somewhere on some TODO list of SO - meta.stackoverflow.com/questions/355481/…
 
if i write an array of named tuples (e.g. [word(word='AbC', sanitisedOne='abc', sanitisedTwo='abc', sanitisedFour='abc')...]) to a text file, then read that back in, best way to get it back to the data structure in python?
 
I'd probably try pickle first.
 
3:52 PM
probably
 
@Jarede for the record, square brackets define a list, not an array
 
yeah you're right
i'm not a python coder by day
 
Hmm, I just tried pickling a namedtuple and it didn't work. Unfortunate.
 
def  levelc(recipe):
    if recipe == "a":
        print("A")
    else:
        print(":/")
level = 3
if level == 3:
  levelrecipe = "a"
  level == 4
if level ==4:
  levelc(levelrecipe)
 
@DanielNewell level == 4 <-- this is a no-op
 
3:55 PM
oh nvm
now i don't get why my code ain't working
 
@Jarede I'd probably convert the namedtuples to lists and then encode that as json
 
@DanielNewell If you're trying to construct an MCVE for us, you're doing a good job at "minimal", but not "verifiable". The shortened code has to raise the same exception that the original code does.
 
@vash_the_stampede closed
 
@Kevin also "complete"
 
3:58 PM
wait
how do i call for a global variable in a module
like if file a is
foo = "bar"
how will i get foo in file b
 
import a; print(a.foo)
 
OR from a import foo
 
@AndrasDeak I categorize "runs without raising a NameError" under Complete, and "actually demonstrates the problem" under Verifiable. I acknowledge that there are other valid interpretations, though
 
I see
I always thought of completeness as something that reproduces OP's code, and verifiable as something we can run ourselves too
 
4:02 PM
that doesn't work
 
though "not relying on a 10k-line csv file" is also completeness in my head, so I pretty much consider the V to be redundant
 
Traceback (most recent call last):
File "main.py", line 81, in <module>
from levels import level_004 as level
File "/home/runner/levels/level_004.py", line 2, in <module>
from main import data
File "/home/runner/main.py", line 82, in <module>
levelreturn = level.level()
AttributeError: module 'levels.level_004' has no attribute 'level'
 
then python is broken
 
import shortcuts as s
from main import data
def level():
is the beginning of levels/level_004
i guess i;ll work on it tomorrow
g2g
kthxbai
 
giving it a rest could help a lot
 
4:03 PM
Circular imports, mmmhm
 
Possible circular import there, which can interfere with global values. If levels.level_004 imports main, make sure that main doesn't import levels.level_004
Beaten
 
Kevin'd*
:D
 
@shad0w_wa1k3r RecursionError
 
I kind of wish Python would raise an exception for circular imports, but alas
There are valid use cases for intentional circular imports, but I still don't like it.
I'm quite surprised that pickle can't pickle namedtuples. I don't think of namedtuple as a particularly complicated class, so this seems like an odd oversight
 
@Kevin umm... you're trying to pickle the class and an instance... does just pickling instances work?
(eg - pickle [y, z] instead of [x, y] ?)
 
4:09 PM
Oops. Let's see.
Got my hopes up for a second :-)
 
Should work if you change x = to Fred =
 
Hmm, so it does. That's an unusual requirement if you ask me :-I
 
What magic is pickle doing that it requires a name lookup on the global scope
 
Well, you wouldn't you want pickle to actually dump the implementation of your class into the file, would you? Classes and functions are pickled as references (i.e. names)
>>> dumps(int)
b'\x80\x03cbuiltins\nint\nq\x00.'
 
4:13 PM
stackoverflow.com/questions/52861057/… uncelar, output format invalid, no response for proper output
 
Does that mean pickle also fails if you try to pickle a class that's defined inside a function?
 
Is it considered bad form to answer bad questions?
 
Yep: AttributeError: Can't pickle local object 'f.<locals>.Fred'
 
I just noticed my typo up there. I wonder how often I accidentally a word without noticing.
 
4:16 PM
Why would python name it's serialization module pickle?
 
In the real world, pickling is a process of preserving food in a form suitable for long-term storage. So it kind of makes sense from that angle.
 
my guess would be that it preserves the object
 
I don't think you can unpickle actual pickles, so the metaphor breaks down a little there
 
morning cabbage
 
@Aran-Fey missing out miss there is sooooo ironic... nice one :)
 
4:19 PM
simplejson will do what i want (list of named tuples to json)
 
stackoverflow.com/questions/52860199/… broad, op solved problem in comments
 
On the topic of typos, I found a spelling error while playing Hollow Knight yesterday, which surprised me since it's been out for a year and has had a million sales.
 
recbg
 
Granted it was in a dialog box towards the end of the game in an area that you don't need to visit to get the basic ending, so considerably fewer than a million people have probably seen it
 
stackoverflow.com/questions/52826171/… off topic, op issue was 20 lines earlier in unposted code
 
4:25 PM
Oh btw guys... anyone interested in playing Trine 2: The Complete Story on Steam at some point... I've still got 2 copies I can gift from an offer I got quite a while back sitting about...
 
I picked up a copy from a Humble Bundle many months ago. I liked squishing monsters with wizard cubes.
 
oh what is that
 
I think I've seen its name in GOG newsletters
 
@Kevin yeah... I'd seen a little bit of play-through (probably the Yogscast) on YT ages ago and while it's not a particularly recent game, it was one I was interested in (just not at £15 for a copy) so was quite happy to spend £4 for 3 copies :)
 
hello
 
4:30 PM
hello
 
can any one help me with this thread ? stackoverflow.com/questions/52875481/…
looks like no one :D
 
Generous of you to give everyone 2.5 minutes before deciding that :)
 
apologies
:)
 
lol
 
wim
any backport of venv to pythoff?
 
@vaultah alright man
please everyone dont help
 
you can count on me
 
lol so sassy
 
@AndrasDeak Thank you
@vaultah btw i dont see such rule in room's bible
@ex080 lol
 
Just search for "Don't ask for answers to your recent Stack Overflow questions" on that page.
 
4:49 PM
@HassanMehmood there's generally no reason to bring to attention in chat a question that's only 3 hours old... you've commented on the answer you've been given... why isn't it good enough... have you edited your question to reflect queries/points raised there/to add further information etc...
 
@JonClements calm down relax, i think i made a mistake coming here. If you look at the solution do you really favor that approach ?
 
Nope - but then you haven't made it clear anywhere why you don't or exactly what you're looking for either... you can edit your questions/comment for a reason :)
 
@JonClements now thats something i can do
 
yeah Jon, calm down now
 
4:53 PM
EVERYBODY JUST CALM DOWN!!!!
 
Hi Jack!
 
everyone take a chill pill
 
@Hassan absolutely - one you don't have to frequent chat to do so.... although you're most welcome to hang out and chat with us - we're a friendly bunch. If after another day or so - you still get nothing and you've done what you can edit it, we'll be happy to review it again and help you out with any other suggestions/advice or possibly even a solution if we can. Keep calm and carry on :)
 
@JonClements alright, thank you for your support :D
 
4:56 PM
@Hassan thanks for having a more positive attitude :D
 
@JonClements dude, i was being sarcastic :D lol
 
So much positivity in the air
 
oh darn, if only I'd have noticed that sighs... being a Brit. I'm generally good at that :p
 
@JonClements oh please, dont tell this "brit" thingy to me. I have one colleague from brit, i can better imagine. anyways never mind. This forum looks like worth spending itme
 
Found my doppleganger doppelganger! stackoverflow.com/users/3848411/show-stopper
 
5:00 PM
how could the both of you have such a unique avatar? :PPP
 
I don't understand why the provided answer isn't suitable. I mean, ok it's not exactly 'there' yet but a few print and I could see what could be done to make it better so /shrug
 
@Jerry because, the answer may be right for current period (duration provided for data), but eventually when an update comes it won't work plus adding split("\n") add unnecessary empty spaces
 
This meta discussion will very soon turn into a not-so-meta discussion. Improve the question or give feedback to the answerer. Don't elaborate here.
 
^ (was just about to add to the not-so-meta discussion, but realized before Andras's reply :D )
 
5:04 PM
well good luck then, I don't think your question is clear
 
alright
 
chat is nice, meta + SO
best of both, and much less of the worse of both
 
nevermind, i solved it with pandas :) and deleted the post
 
PANDAS RULE!
 
I prefer red pandas slightly more
 
5:07 PM
Nothing those cute guys can't solve without a little bamboo
 
I have a particular liking to the Kung Fu pandas :-p
 
@shad0w_wa1k3r isn't there only one of those?
 
I'm unsure now, but probably yeah
pretty sure he can teach the others though :D
 
Many panda monks in world of warcraft when that expansion hit.
 
the only panda i like is pandas
:P
I mean the python lib
 
5:12 PM
it must be a sad panda, working under a python
 
@piRSquared except bothering to procreate? :)
 
that's a scary panda you got yourself there bud
 
recbg
 
Looks like a malformed version of that rubix cube that wasn't a cube thing that you had to reshape into a hexagon or whatever it was...
 
5:19 PM
@Jerry true python pandas
 
I am scared
very much scared
 
so now everyone started trolling pandas
?
 
@AnttiHaapala Hello finland
 
@HassanMehmood cbg to you too
 
5:22 PM
@AnttiHaapala Kiitos
 
@HassanMehmood where are you located?
 
@AnttiHaapala Finland
 
@HassanMehmood but city
 
@AnttiHaapala Oulu
 
so am I and @IljaEverilä
 
5:23 PM
@AnttiHaapala that was quite funny, thanks
 
@AnttiHaapala thats nice, hauska tavata
 
@HassanMehmood I guess I successfully stalked you in L-in
 
@AnttiHaapala alright, it would be nice to catch up someday
 
@HassanMehmood we've been thinking about organizing a python meetup in oulu
 
@AnttiHaapala it would be awesome tbh
@AnttiHaapala let me know, if i can be any help in coordination or sth
 
5:40 PM
I'm mourning the loss of 100k rep that just shattered on the kitchen floor )-;
 
aww :(
 
I'll spend the appropriate amount of time in denial where I'll look to replace that mug... somehow. However, I'm already thinking that I'll just get a steel one and put an SO sticker on it
 
@piRSquared my Checkpoint Charlie mug is enamel... it should be mandatory that every mug have a choice of enamel too.
that's also why I seldom dare to use my NATO mug :(
 
how did u lose 100k rep
I cant even get 100
 
@ex080 dropped a SO mug
 
5:45 PM
he dropped his 100k rep celebratory mug
 
oh i see
lmao
There are a 1000 hundreds in 100,000
 
Ask for another one once you reach 200k
3
 
That does remind me I should ask the CM team for another mug (or two) but will probably wait until 100k (whenever that happens - not looking like this year at this rate)
 
I hope to reach 100 by next year this time
 
the problem is that the questions are so bad
it is like all time low in especially
 
5:52 PM
these weeks or these months?
 
Why would you iterate a namedtuple object, iterating a tuple absolutely does not make senseAntti Haapala 5 secs ago
@AndrasDeak these years
 
hehe
 
here is another guy who thinks tuple is an immutable list
 
wait, you can't iterate a namedtuple?
you can, phew
 
@AndrasDeak you can
"phew"
 
5:54 PM
This is the second time this week I've heard that you shouldn't treat tuples like immutable lists and honestly I don't know where this is coming from
 
well if something with "tuple" in the name can't be iterated over, it would be weird :D
 
Iterating over a tuple frequently makes sense, but iterating over a namedtuple is really weird.
 
I understand why you wouldn't usually want this, but it's still a sequence
Sep 26 at 18:38, by Andras Deak
> Tuples are for heterogeneous data, list are for homogeneous data.
Tuples are *not* read-only lists.

—Guido van Rossum
and you typically don't loop over heterogeneous data
 
def __getattr__(self, attr):
	if attr == "book_title":
		return self.book.title
Is that the wrong way to use __getattr__?
 
The chains of old are unbound and the seals broken, GVR no longer has power in these halls
 
5:56 PM
@malan: Why would you do that instead of just using thing.book.title?
 
Also, why would you do that with __getattr__ instead of just creating a book_title property?
 
@malan yes that will work too, but remember to raise AttributeError in else
 
Because it's a sub object
@AnttiHaapala okay
 
What's a sub object?
 
but yes, in general case you'd want to have a property
 
5:57 PM
@AndrasDeak Perhaps wrong terminology
 
use __getattr__ only if they're somewhat dynamically computed.
 
Or just delegate to self.book:
def __getattr__(self, attr):
    return getattr(self.book, attr)
 
@property
def book_title(self):
     return self.book.title
 
@AnttiHaapala I think that just answered my next question
 
the getattr makes sense is written like this:
 
5:59 PM
 
def __getattr__(self, attr):
    if attr.startswith('book_')
        return getattr(self.book, attr.replace('book_', 1))
    raise AttributeError(f'No such attribute {attr}')
 

« first day (2924 days earlier)      last day (2028 days later) »