What is the idiomatic python way to hide traceback errors unless a verbose or debug flag is set?
Example code:
their_md5 = 'c38f03d2b7160f891fc36ec776ca4685'
my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7'
if their_md5 != my_md5:
raise ValueError('md5 sum does not match!')
Existing output n...
Hello, I am having issues with Django models not saving. Does anyone here know what the process is for Django saving a model when .save() is applied to a newly created model?
I've been interested in the American space program for as long as I can remember, but didn't know about the women who were a vital part of its success.
I don't know how things work in The West, but I searched for literally hours for a shop where I can buy 6-32 screws to mount a few HDDs, and then I ended up dismantling my old PC and scavenging the pieces:/
and only 4 of the 20 screws were actually 6-32, the rest were almost-compatible metric screws
Yeah, even if everything else in an old PC is rubbish it's worth scavenging the screws and maybe the powersupply, unless it's burnt out. Oh, and the dead HD is good for magnets but you already know that. :)
I have two computer sitting here that I'm not using. I tell myself I'm gonna pull the hard drives, murderate them, and dispose of the rest. Didn't think of scavenging the screws.
@AndrasDeak I only caught a few episodes of it. I'll have to add that to my "To Watch" list after I finish Silicon Valley Season 3, the rest of GOT, and Halt & Catch Fire.
Amiga double density floppies had more capacity than DOS ones, but we never got quad density... Although I guess some people might have hacked together a quad density Amiga drive.
Of course, I have kicked myself in the ass for years. At one point in time, I compressed all of my first C and C++ projects into a multi-disk zip file. I even wrote on the labels what they were and numbered them. Then later, I had the bright idea to write over the last disk with something else!
As you know, the last disk contained all of the file structure information, so I never retrieved the code back ;-(
I kept telling myself I'd write a utility to extract the data. Even if it was one long ass text file, I could have broken it up from there, but never got around to that project.
I'm new to Python programming.
I was trying to achieve the following output:
Account c
Account count = 1
Successful transaction! Balance = 10000
Successful transaction! Balance = 9000
Not enough balance
This is my code
class Account:
accountCount = 0
def __init__(self, name, account...
Yeah, it can be closed right away. But he would still be confused. So there are 3 ways you can explain what's wrong, 1. In the comments 2. Edit and correct the indentation in the question itself 3. Post the correct indentation as an answer. Comments sometimes take too much back and forth messages.
what you can do with code is to add the code block, or press the code button to dedent the block if you're sure you can still reproduce the original problem with that :D
It was confusing for me also, but it becomes natural after sometime. It's like you want to join the elements of iterable, but you can also specify a delimiter.
I just ran into something strange with list comprehensions. Solving a problem suggested by a textbook, I came up with the following code. The specification requires that the input contain only characters A-Z.
def incStr1(text):
# Base case for recursion:
if text == "": return "A"
head = text[0:len(text)-1]
tail = text[-1]
# (A)
if not all([ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for ch in text]):
raise ValueError
if ch == 'Z':
ch = 'A'
head = incStr1(head)
else:
ch = ord(tail)
ch = chr(ch+1)
return head + ch
If I remove the section marked (A), then the code fails because ch is not defined. But even with (A), why should ch be defined at all? It just happens to work.
It is supposed to a Perl-style string increment. That is, "A" becomes "B", "Z" becomes "AA", etc.
The restriction/simplification suggested was that the string contain only A-Z, hence the 'if not all' statement. But after writing that, I thought, 'I don't actually need to restrict it in this way', but after removing it, it no longer works, simply because of the surprising scope of the ch symbol.
Apparently it is answered here: http://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehension-is-thi Probably a valid reason to upgrade to Python 3. Oops.
In Python 3 the list comprehension does not 'leak' the iterator symbol. But in for loops, it does leak. I guess it is still a bit confusing either way. That a 'for' loop leaks seems to make a little more logical sense, however.
Here is the fixed version:
def incStr2(text):
# Base case for recursion:
if text == "": return "A"
head = text[0:len(text)-1]
tail = text[-1]
ch = tail
if ch == 'Z':
ch = 'A'
head = incStr2(head)
elif ch == 'z':
ch = 'a'
head = incStr2(head)
elif ch == '9':
ch = '0'
head = incStr2(head)
else:
ch = ord(tail)
ch = chr(ch+1)
return head + ch
Now it works with any string that could be incremented, like 'asdjn12938'. That is more Perl-like. Of course, Perl has some weird cases like 'abc1def'. Incrementing that results in the integer 1 for some reason.
" If i remove the section marked (A), then the code fails because ch is not defined. But even with (A), why should ch be defined at all? It just happens to work."
I believe it's because it just raises a value error...since it's not defined and the script runs through each letter in your list, it'll pass it if you've got a letter and then go to it later and raise an error if you have a number...at that point ch has been defined
No. If I remove (A), then the line that follows will raise UnboundLocalError:
def incStr1(text):
# Base case for recursion:
if text == "": return "A"
head = text[0:len(text)-1]
tail = text[-1]
# (A)
#if not all([ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for ch in text]):
# raise ValueError
if ch == 'Z': # XXX
ch = 'A'
head = incStr1(head)
else:
ch = ord(tail)
ch = chr(ch+1)
return head + ch
In Python 3, the line marked XXX raises UnboundLocalError regardless, because the above list comprehension does not 'leak' ch.
Correct because by defining that ch is in A-Z in (A), it acknowledges that X is in there.if you take it away, you remove what ch is defined as. That's how I see it.
You may not have "ch=str()" but you are forcing it to recognize that ch is in A-Z.
It is a valid improvement in Python 3. But it would be nice if Python had a real notion of 'warnings'. For example, it would be nice if the interpreter in Python 2 noticed this and said "Hi there dear Programmer, I noticed you're making use of a symbol that only exists because it 'leaked out' of the above list comprehension. Maybe you should not do that."
Oh, yes,precisely.I agree wholeheartedly. You could always run a check on that or create a function that checks for that. Check for it in locals at one point or explicitly define it before leaking it.
I'm out! I've got some art I need to work on this morning. Cheers and goodluck!
Well, that doesn't really work either. If you have the foreknowledge to write extra code like that in order to check for confusing situations, you probably would have just avoided the potentially confusing code in the first place. In this case, it is something that I misunderstood about, that 'ch' was confined to the list comprehension, but it is not.
re-cbg. Damn. I see I missed a discussion about Python 2's leaky list comps. Before I go back & read the details, I'll just say that I didn't mind them. Sure, I got bitten by them in my early days, since my C instincts were trained to expect a list comp to run in its own scope, not that of the surrounding code (every block in C creates a new local scope). But it was easy to work around, and was occasionally handy, so I soon got used to it.
Bear in mind that was before Python had generators (or dict or set comprehensions). It totally makes sense to me that a generator expression creates a new scope, since a gen exp is really syntactic sugar for a generator created using def. I suppose it was a sensible thing to make list comps consistent with generators, scope-wise.
However, a Python 3 list comp is slower than a Python 2 one because it's expensive to create a new Python scope compared to a C scope. Similarly, calling a Python function is slower than executing the same code in-line.
@PM2Ring But, if you depend on the scope being leaky, this will bite you if you want to move to script to a Python 3 interpreter. So for that raeson I'd prefer to avoid it. I'm not too worried about the speed aspect. My example code uses recursion for example, which for all I know is slow as hell. But until it's a speed critical computation, I will not care much about the performance.
I guess the same C instinct made me think that the symbol was in its own scope too.
Well of course I wouldn't rely on a list comp being leaky these days because I almost always write Python 3 code. And I mostly write bi-versional code unless I'm doing something that's radically different in the 2 versions, eg low-level byte work, or Unicode.
And even before it was decided to remove the leak in Python 3 I rarely wrote code that relied on the leak, because it smells like a side-effect. And if I did, I'd mention it in a comment.
That seems reasonable. I corrected mine to the following, which, surprisingly for me at first, just happens to have the same meaning whether the 'ch = tail' line is present or not.
...
# The characters in text must be A-Z or a-z.
if not all([ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for ch in text]):
raise ValueError
head = text[0:len(text)-1]
tail = text[-1]
ch = tail
...
After all, with the way I'm thinking about the above, I could have written the following instead. In this case, the 'ch = tail' line is mandatory to produce the correct result:
# The characters in text must be A-Z or a-z.
if not all([ch in 'ZABCDEFGHIJKLMNOPQRSTUVWXY' for ch in text]):
raise ValueError
No, actually that would still be fine. Because I guess the list iterates to text[-1] last
> Now, a word of warning. I will mock an interface in this example. That doesn't mean you should only mock interfaces. I hate useless interfaces. And you want me to be happy. Please don't create an interface just for the pleasure of mocking it. Just mock the concrete class. Thank you.
BTW, it's far more efficient to pass a gen exp to all() or any() than a list comp. all() and any() short-circuit, so they stop checking items as soon as they have a definite result, but if you pass a list comp the whole list has to be created before all() or any()can start doing their tests.
Yeah, (1) needless listcomp, (2) inlined long constant, (3) string membership test, and (4) the comment doesn't seem to match the code, unless text was uppercased in a different location.
I haven't read the earlier messages on this topic yet, I just assumed it was an example list comp to have something concrete to talk about. Sensible code would do text.isupper()
In that case, you'd use a set instead of a string to test that the chars were valid.
@Brandin Guido explains why .join is a str method, not a list method. Briefly, it means that you just need one join method to handle any kind of string collection or iterable. OTOH, .join needs to make 2 passes over the collection, first to get the size of the destination string & second to copy the strings (and delimiters) to the destination. So it's more efficient to pass .join a list, list comp, or tuple than a gen exp.
Does someone know problems between GUI and recording together? (In my case: Tkinter and microphone with pyaudio). I get IOError Input overflowed. I have tried to change chunk and rate and to catch the Exception. Can someone help me with this problem? For more information (e.g. the code), click here. Thank you!
@PichiWuana Sorry, I've never used pyaudio. But you probably don't want to reduce RATE unless you want to sacrifice quality: 44100 bps is the CD standard rate.
@Brandin You can still do in with a set, and it will be faster than doing in on a string, even taking the time to construct the set into account. And of course, you could put the valid letters set into the script as a set literal, so it gets created at compile time.
Well, to me, Python programming is not about saving processor time. It is about writing things that don't make my head hurt too much when I read them later. I still don't know where the optimum is. If the 'issuperset' thing is useful in other contexts, I will try to adopt it as an idiom. But for now it reads a bit cryptically.
Hey I got a quick question, I am developing a Python CLI program that must talk to a server [ probably over HTTPS/ OR anything that makes more sense ]. What protocol should use on the CLI program. Make a TSL connection and make requests to the webserver or directly call using HTTP requests ? Any advice is much appreciated
@khajvah, sorry where could be more specific. If this helps: The CLI Program authenticates the user -> user can run commands on this local machine -> and the cli program makes a call to the webserver (Django App and a specific URL) then then a view function would be executed. If I wanted to make the data and connection more secure, then HTTPS would be good or else I should wrap then in TSL Socket
@Brandin I agree it's a bit cryptic. It may help to think of a.issuperset(b) and b.issubset(a) as complementary. Also see their even more cryptic operator versions. ;)
As I said the other day, it's silly wasting time on micro optimization; OTOH, it's good to use fast built-ins that are often running at C speed rather than reinventing the wheel with a Python loop.
Sorry if I'm a bit slow I'm typing on a phone.
@Brandin Yep. And the more you practice with them, the easier it will be to think in terms of list comps and gen exps.
Has anyone found a web framework-agnostic github webhook library? Everything wants to be either a drop-in "run these scripts" tool or a plugin for specific frameworks :/
I have a feeling you are leaning towards something that doesn't quite exist yet. Which could be exciting if you're in to making something awesome for this.
Hey can someone explain an answer to me quickly here? I found "the answer to my question" on SO but I just don't get it. It seems total magic to me, and because of that really more like a hack than a good solution.
stackoverflow.com/questions/34562113/… <- this question is exactly what I wish to do (apart from actually NOT wanting to give a "string-counter" a specific "name")
Is the "subclassing Counter to inject the superclass typing.mapping" the only way to go? - Since that would require me to come up with a name for it.
Hmm if I have a complex class for which I can need a "clear multiline-print" option (but that would be many lines), should I overload __str__() or should I make a specific decorated_print() function?
Thought so too, but I haven't seen the hyphen actually ever being enforced by spelling rules in english. (Unlike dutch where it is clearly stated when you have to use a hyphen, and you can't use the hyphen otherwise).
Pycharm uses a static typechecker to recognize what a variable is, and can hence give all possible methods - so long as it is statically determinable. (Using type hints from typinggoes a long way).
@MYGz This isn't much of an answer, but normal slicing is just a row-wise selection mechanism on DataFrames, like a boolean array. I remember in McKinney's book he said something like "This might seem inconsistent but it is very practical" or something along those lines. Obviously you've just gotta use .ix.
@linuscl since my psychic remote-viewing powers are a little rusty, yes, you have to post code in order to get help with code. Make sure it's an MCVE, and if it's more than 10 lines use a pastebin.
You'll also have to clearly describe your problem. What does "almost freeze" mean? How are you sure it's your code and not the requests you're making? Why do you think it's related to threading? Etc.
I'm serving a python script through WSGI. The script accesses a web resource through urllib, computes the resource and then returns a value.
Problem is that urllib doesn't seem to handle many concurrent requests to a precise URL.
As soon as the requests go up to 30 concurrent request, the reque...
Quote: If you need more concurrency, you'll probably have to pick up some kind of asynchronous network IO tool (eg. Eventlet seems to have a suitable example on its front page), or just launch each urlopen in its own thread.
>>> import eventlet
>>> from eventlet.green import urllib2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/site-packages/eventlet/green/urllib2.py", line 16, in <module>
('urllib', urllib))
File "/usr/lib/python3.6/site-packages/eventlet/patcher.py", line 93, in inject
module = __import__(module_name, {}, {}, module_name.split('.')[:-1])
ModuleNotFoundError: No module named 'urllib2'
first problem :(
AttributeError: module 'eventlet.green.urllib' has no attribute 'urlopen'
File "/usr/lib/python3.6/urllib/request.py", line 1320, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 24] Too many open files>