Re: Tuple Comprehension ???
On 21/02/2023 19:11, avi.e.gr...@gmail.com wrote: In your own code, you may want to either design your own functions, or use them as documented or perhaps create your own wrapper functions that carefully examine what you ask them to do and re-arrange as needed to call the function(s) you want as needed or return their own values or better error messages. As a silly example, this fails: max(1, "hello") Max expects all arguments to be of compatible types. You could write your own function called charMax() that converts all arguments to be of type str before calling max() or maybe call max(... , key=mycompare) where compare as a function handles this case well. The key point is that you need to adapt yourself to what some function you want to use offers, not expect the language to flip around at this point and start doing it your way and probably breaking many existing programs. Yes, consistency is a good goal. Reality is a better goal. I don't think overengineering is a good thing. Good design utilizes associativity so a person don't get amazed by inconsistency in things that expected to be similar. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuple Comprehension ???
On 21/02/2023 04:13, Hen Hanna wrote: (A) print( max( * LisX )) (B) print( sum( * LisX ))<--- Bad syntax !!! What's most surprising is (A) is ok, and (B) is not. even tho' max() and sum() have (basically) the same syntax... ( takes one arg , whch is a list ) i've been programming for many years...( just knew to Python ) LOL, python is full of surprises. I'd definitely step into the same piece of... Someday. Of course 'Builtin functions' section explains that, but the inconsistency is weird. My response is absolutely useless, just two cents on the issue. Maybe someone will fix that. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: File write, weird behaviour
Looks like the data to be written is buffered, so actual write takes place after readlines(), when close() flushes buffers. See io package documentation, BufferedIOBase. The solution is file.flush() after file.write() Can't deny, such a behaviour looks utterly weird. Try to avoid designing your software this way. Axy. On 19/02/2023 14:03, Azizbek Khamdamov wrote: Example 1 (works as expected) file = open("D:\Programming\Python\working_with_files\cities.txt", 'r+') ## contains list cities # the following code adds new record to the beginning of the file, expected behaviour file.write("new city\n") file.close() Example 2 (weird behaviour) file = open("D:\Programming\Python\working_with_files\cities.txt", 'r+') ## contains list cities # the following code DOES NOT add new record TO THE BEGINNING of the file IF FOLLOWED BY readline() and readlines()# Expected behaviour: new content should be added to the beginning of the file (as in Example 1) file.write("new city\n") file.readlines() file.close() I could not find anything in documentation to explain this strange behaviour. Why is this happening? -- https://mail.python.org/mailman/listinfo/python-list
Fun with python string formatting
Hi all, what do you see looking at format string syntax https://docs.python.org/3/library/string.html#formatstrings ? In particular, at something like this: {h[1].red.jumbo-header:Hello, World!} Yes, this is syntactically correct statement and if we tweak Formatter methods, we can generate such an output: Hello, World! Someone might need a booze to catch sight of arguments and css classes in the source statement, okay: let it be Aligote markup. Although I haven't implemented HTML rendering yet (my actual needs were reST and Markdown), this does generate plain text and Markdown now. However, I'm discouraged at the moment. Without nested markup the implementation is very small and nice. With more or less complex formatting, such as nested lists, there's a need to analyse upper level statements and to enforce some rules. Also, there's a pain with indentation, but that's mainly because I was too lazy and based my implementation on previous work instead of writing a better one from scratch. There are some undefined points such as how to render paragraphs. Use strict {p:text} directive or just split literal text by doubly newlines. Can't decide whether to cut down all the complexity and revert recursion level to 2 or proceed with rich markup. Anyway, below is the rendered specification in plain text. Here's the source code https://github.com/declassed-art/clabate/blob/main/clabate/extras/aligote.py and the specification https://github.com/declassed-art/clabate/blob/main/clabate/examples/aligote_spec.py If this looks funny and you have any crazy ideas what can be added to or changed in the specification, let me know. Axy. Aligote markup specification Headings {h1:heading} {h2:heading} {h3:heading} {h4:heading} {h5:heading} {h6:heading} Styles -- {b:bold text} {i:italic text} {b:bold and {i:italic} text} {i:italic and {b:bold} text} {u:underline text} {s:strike-through text} {sub:subscript text} {sup:superscript text} Links - {link[optional text]:URL} Examples: {link:http://declassed.art} {link[Declassed Art]:http://declassed.art} Rendered as: http://declassed.art Declassed Art (http://declassed.art) Lists - Unordered lists --- {ul: {li:item one, can be markup} {li:item two can be multi-line} {li:etc} } Rendered as: * item one, can be {b:markup} * item two can be multi-line * etc Ordered lists - {ol: {li:item one} {li:item two} {li:etc} } Rendered as: 1. item one 2. item two 3. etc Nested lists {ul: {li:item one} {li:item two} {ol: {li:item one, multi-line} {li:item two} } {li:etc} } Rendered as: * item one * item two 1. item one, multi-line 2. item two * etc Optional arguments -- XXX Markdown does not support arbitrary numbering, does it? {ol: {li[3]:item 3} {li[5]:item 5 {ol: {li:ordinal is rendered as 5.1} {li[3]:ordinal is rendered as 5.3} {li[5][5]:ordinal is rendered as 5.5} {li: ordinal is rendered as 5.6} } } } Rendered as: 3. item 3 5. item 5 5.1. ordinal is rendered as 5.1 5.3. ordinal is rendered as 5.3 5.5. ordinal is rendered as 5.5 5.6. ordinal is rendered as 5.6 Optional argument for unordered list is the bullet character. Default is `*`: {ul: {li:item 1} {li[+]:item 2} {li[-]:item 3} } Rendered as: * item 1 + item 2 - item 3 Quirks -- {ol: {li:item one} Basically, lists may contain any literal text. In terms of python formatting this is not an error, but that's not good for rendering. {li:item two} } Rendered as: 1. item one Basically, lists may contain any literal text. In terms of python formatting this is not an error, but that's not good for rendering. 2. item two Syntax highlighting --- {python: print('Hello, world!') } Rendered as: print('Hello, world!') -- https://mail.python.org/mailman/listinfo/python-list
Announcing Clabate 0.5.0: minimalistic class-based templates for Python
Hi there, although it's quite old my side project, it has reached the point where I don't want to add anything more. It's a simple template system based on standard string formatting. You declare your template strings as class attributes and they are formatted in the right order. For dynamic content you can use class properties, and inline invocations, such as 'hello, {my_db:get_name({person_id!r})}' https://github.com/declassed-art/clabate Axy -- https://mail.python.org/mailman/listinfo/python-list
Re: Panoptisch - A way to understand your project's dependencies and find malicious packages
On 08/12/2022 17:52, Aarnav Mahavir Bos wrote: Hello all, I would like to share Panoptisch, a FOSS(Free and Open Source Software) tool I've been working on. Hi there, I added your project to my watch list, keep on your work. A couple of points: First, I glanced at the code and in the very first file I opened, https://github.com/R9295/panoptisch/blob/master/panoptisch/__init__.py, I see main(). I usually place such a code in __main__.py Second, in addition to AST analysis it would be nice to implement a sandbox with import hooks. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Passing information between modules
On 18/11/2022 10:53, Stefan Ram wrote: Can I use "sys.argv" to pass information between modules as follows? in module A: import sys sys.argv.append( "Hi there!" ) in module B: import sys message = sys.argv[ -1 ] This idea has a couple of flaws so can be regarded as bad. However, if nothing else works (including suggested globals.py module), then os.environ could be a better way. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Are these good ideas?
On 15/11/2022 04:36, Dan Stromberg wrote: On Mon, Nov 14, 2022 at 11:33 AM Axy via Python-list wrote: On 14/11/2022 17:14, Stephen Tucker wrote: > Hi, > > I have two related issues I'd like comments on. > > Issue 1 - Global Values Your "global variables" module acts exactly as a singleton class. Which is apparently a design pattern that some now believe is regrettable. Exactly. I dislike it too and always avoid. However, it could be a good starting point. Stepping directly into class-based approach would raise the same question: where to place global instance of that class. Gradual refactoring might have greater side effect of better overall design where many issues simply vanished by themselves. Maybe, (c) will change in favor of well-designed classes, who knows? Dropping singleton code is not a difficult task. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Are these good ideas?
On 14/11/2022 17:14, Stephen Tucker wrote: Hi, I have two related issues I'd like comments on. Issue 1 - Global Values Your "global variables" module acts exactly as a singleton class. Funny, you could (and maybe you do) write in your functions import global_vars_module as self as the first step of refactoring. From personal experience, when I worked at work we used modules for globals as well, but over time such an approach looked more and more ugly and finally was rejected. Issue 2 - Passed Parameters I am now facing another situation where I am wanting to pass 6 or 7 parameters down through several layers of logic (function A calling function B calling ... ) and for results to be passed back. Nothing fancy here, we used dicts for args and results. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Superclass static method name from subclass
On 11/11/2022 16:21, Ian Pilcher wrote: Is it possible to access the name of a superclass static method, when defining a subclass attribute, without specifically naming the super- class? Contrived example: class SuperClass(object): @staticmethod def foo(): pass class SubClass(SuperClass): bar = SuperClass.foo ^^ Is there a way to do this without specifically naming 'SuperClass'? There is, but it's weird. I constructed classes from yaml config so I did not even know the name of super class but I wanted similar things for my clabate templates and I implemented superattr() which works for me: class BasePage: body = 'Hello' class MySpecificPage(BasePage): body = superattr() + 'World' Actually, it's suboptimally elegant code. Artistic code, to be clear, as if you looked at modern art and thought: WTF? Also, it's specific for templates only and supports only __add__. But I think the approach can be extended to a general superclass() if you log __getattr__ calls and apply them in __get__ method same way. I realize this reply is not an immediate help and probably won't help, but there's always a way out. Axy. Here's the code: class superattr: ''' This is a descriptor that allows extending attributes in a simple and elegant way: my_attr = superattr() + some_addition_to_my_attr ''' def __init__(self): self.additions = [] def __set_name__(self, owner, name): print('__set_name__', name) self.attr_name = name def __get__(self, obj, objtype=None): for cls in obj.__class__.__mro__[1:]: try: value = getattr(cls, self.attr_name) except AttributeError: continue for a in self.additions: value = value + a return value raise AttributeError(self.attr_name) def __add__(self, other): print('__add__:', other) self.additions.append(other) return self Full article: https://declassed.art/en/blog/2022/07/02/a-note-on-multiple-inheritance-in-python -- https://mail.python.org/mailman/listinfo/python-list
Re: xml.etree and namespaces -- why?
I have no idea why, I used to remove namespaces, following the advice from stackoverflow: https://stackoverflow.com/questions/4255277/lxml-etree-xmlparser-remove-unwanted-namespace _ns_removal_xslt_transform = etree.XSLT(etree.fromstring(''' xmlns:xsl="http://www.w3.org/1999/XSL/Transform;> ''')) xml_doc = _ns_removal_xslt_transform( etree.fromstring(my_xml_data) ) Later on, when I worked with SVG, I used BeautifulSoup. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: xml.etree and namespaces -- why?
I mean, it's worth to look at BeautifulSoup source how do they do that. With BS I work with attributes exactly as you want, and I explicitly tell BS to use lxml parser. Axy. On 19/10/2022 14:25, Robert Latest via Python-list wrote: Hi all, For the impatient: Below the longish text is a fully self-contained Python example that illustrates my problem. I'm struggling to understand xml.etree's handling of namespaces. I'm trying to parse an Inkscape document which uses several namespaces. From etree's documentation: If the XML input has namespaces, tags and attributes with prefixes in the form prefix:sometag get expanded to {uri}sometag where the prefix is replaced by the full URI. Which means that given an Element e, I cannot directly access its attributes using e.get() because in order to do that I need to know the URI of the namespace. So rather than doing this (see example below): label = e.get('inkscape:label') I need to do this: label = e.get('{' + uri_inkscape_namespace + '}label') ...which is the method mentioned in etree's docs: One way to search and explore this XML example is to manually add the URI to every tag or attribute in the xpath of a find() or findall(). [...] A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions. Good idea! Better yet, that dictionary or rather, its reverse, already exists, because etree has used it to unnecessarily mangle the namespaces in the first place. The documentation doesn't mention where it can be found, but we can just use the 'xmlns:' attributes of the root element to rebuild it. Or so I thought, until I found out that etree deletes exactly these attributes before handing the element to the user. I'm really stumped here. Apart from the fact that I think XML is bloated shit anyway and has no place outside HTML, I just don't get the purpose of etree's way of working: 1) Evaluate 'xmlns:' attributes of the element 2) Use that info to replace the existing prefixes by {uri} 3) Realizing that using {uri} prefixes is cumbersome, suggest to the user to build their own prefix -> uri dictionary to undo the effort of doing 1) and 2) 4) ...but witholding exactly the information that existed in the original document by deleting the 'xmlns:' attributes from the tag Why didn't they leave the whole damn thing alone? Keep intact and keep the attribute 'prefix:key' literally as they are. For anyone wanting to use the {uri} prefixes (why would they) they could have thrown in a helper function for the prefix->URI translation. I'm assuming that etree's designers knew what they were doing in order to make my life easier when dealing with XML. Maybe I'm missing the forest for the trees. Can anybody enlighten me? Thanks! self-contained example import xml.etree.ElementTree as ET def test_svg(xml): root = ET.fromstring(xml) for e in root.iter(): print(e.tag) # tags are shown prefixed with {URI} if e.tag.endswith('svg'): # Since namespaces are defined inside the tag, let's use the info # from the 'xmlns:' attributes to undo etree's URI prefixing print('Element :') for k, v in e.items(): print(' %s: %s' % (k, v)) # ...but alas: the 'xmlns:' attributes have been deleted by the parser xml = ''' http://www.inkscape.org/namespaces/inkscape; xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd; xmlns="http://www.w3.org/2000/svg; xmlns:svg="http://www.w3.org/2000/svg;> ''' if __name__ == '__main__': test_svg(xml) -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 16/10/2022 18:43, Antoon Pardon wrote: Op 16/10/2022 om 17:03 schreef Avi Gross: Interesting idea, Anton. I would be interested in hearing more detail on how it would work. Although much of programming has been centered on the Latin alphabet and especially English, that may change. I can imagine a customized compiler or interpreter that uses key words in the local language instead of for or while or if or else or even import. Please, please please... forget about that idea. I know examples. They had no future, and have no future. Either RMS or ESR once have written in one of their book: "Please write in C". Same here: please speak in English. Although, if you like that idea who can stop you? In such a case I vote for ภาษาไทย Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: Can you help me with this Python question?
Well, although I never used pandas and never will, if that's about artworks, that's mine. Obviously, you need to iterate columns and sum values returned by the snippet you provided. A quick search tells us to use colums property. So, it might look like this: na_sum = sum(df[name].isnull().sum() for name in df.columns) Axy On 13/10/2022 13:44, Sarah Wallace wrote: For a python class I am taking.. In this challenge, you'll be working with a DataFrame that contains data about artworks, and it contains many missing values. Your task is to create a variable called na_sum that contains the total number of missing values in the DataFrame. When that's completed, print out your answer! Hint: The code given below will give you the number of missing (NaN) values for the *Name* column in the DataFrame. How would you edit the code to get the missing values for every column in the DataFrame? Extra hint: You'll be returning a single number which is the final sum() of everything. df['Name'].isnull().sum() -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 10/10/2022 06:15, avi.e.gr...@gmail.com wrote: Chris, a short(er) answer to your addition below. I did not at first share your perception but maybe do now. If the argument was that ELSE and other constructs like FINALLY or CATCH are horrible because they follow other code and important things should be first, that is a silly argument. You know, sometimes I'm of the same opinion, especially looking at "defer" efforts in Go. However, I wouldn't judge that in terms of mental capabilities. Every construct has some initial rationale but sometimes even best practices eventually become notorious. There are many point of views to every feature but in general features aren't divine and worth revising even this looks disparaging. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 10/10/2022 19:25, Weatherby,Gerard wrote: pylint, at least, provides a warning: fe.py:4:0: W0120: Else clause on loop without a break statement (useless-else-on-loop) I'm using flake8, it does not, alas. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 10/10/2022 15:52, Weatherby,Gerard wrote: I wonder if for/else could have been less confusing if it was referred to as for-break-else and if the else clause was only valid syntax if the for loop actually contained a break statement in the first place. Sounds reasonable. It would be something alike UnboundLocalError when a local variable referenced before assignment. If they won't remove "else" completely in far future, that checking really worths implementing now. Actually, I think a warning would be sufficient, as in the following quick prototype. If someone can implement this quickly in CPython, that would be great (last time I hacked it, it was 2.4) Axy. import ast tree = ast.parse(''' # sample code a = 0 for i in 'asd': a += i while x: pass else: print('wow') break print(i) else: print(0) ''', mode='exec') def check_ast(node): if isinstance(node, (ast.For, ast.AsyncFor, ast.While)): if node.orelse and have_no_break(node.body): print(f'Warning: the loop at line {node.lineno} has no "break" statement,' f' "else" clause at line {node.orelse[0].lineno} won\'t run') else: for child in ast.iter_child_nodes(node): check_ast(child) def have_no_break(loop_body): for node in loop_body: if isinstance(node, (ast.For, ast.AsyncFor, ast.While)): # nested loop check_ast(node) elif isinstance(node, ast.Break): return False elif isinstance(node, list): for child in ast.iter_child_nodes(node): if have_no_break(child) == False: return False return True for node in tree.body: check_ast(node) -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 10/10/2022 15:52, Weatherby,Gerard wrote: Core developer Raymond Hettinger explains the history starting at 15:40 https://www.youtube.com/watch?v=OSGv2VnC0go (which I found on stackoverflow https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops ) TL:DR The “else” is a historical artificial from the way developers thought during the transition from unstructured (i.e. “GOTO”) programming to structured programming. Since we all do structured now, it seems odd. From: Python-list on behalf of Calvin Spealman Date: Monday, October 10, 2022 at 10:38 AM To: python-list@python.org Subject: Re: for -- else: what was the motivation? *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On Sat, Oct 8, 2022 at 5:35 PM rbowman wrote: On 10/7/22 21:32, Axy wrote: So, seriously, why they needed else if the following pieces produce same result? Does anyone know or remember their motivation? In real scenarios there would be more logic in the for block that would meet a condition and break out of the loop. If the condition is never met, the else block runs. To steal from w3schools: fruits = ["apple", "peach", "cherry"] for x in fruits: print(x) if x == "banana": break else: print("Yes we got no bananas") I wonder if for/else could have been less confusing if it was referred to as for-break-else and if the else clause was only valid syntax if the for loop actually contained a break statement in the first place. Sounds reasonable. It would be something alike UnboundLocalError when a local variable referenced before assignment. If they won't remove "else" completely in far future, that checking really worths implementing now. Excellent stackoverflow link, thanks! Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 10/10/2022 12:24, Chris Angelico wrote: On Mon, 10 Oct 2022 at 21:57, Axy via Python-list wrote: Not sure what you mean, but a for-else without a break is quite useless. What exactly ARE you arguing here? The else is associated with the break to the exact extent that one is essential to the other's value. I'm not arguing. That was just for the record, how things are done in Python. Basically, I simply asked a question and got a definite answer and clear understanding shortly, in a few replies. All the rest of this thread looks irrelevant to me, it's about coding style and probably should be continued under a different title, but I'm not interested to participate in it. Here's where the "rest of this thread" started: Actually the reason I never used "else" was the violation of the rule of beauty "shortest block first". You disparaged a feature on the basis of a style rule that few of us had heard of or agree with. Oh, I'm really sorry. My apologies. We all agree that coding style is important; none of us would see block length as a reason to avoid using an else clause on a for loop. As I understand from the above there must be a committee that delegates a speaker? Where to read rules? How to participate? There's something beyond this list I'm not aware of yet? Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
Not sure what you mean, but a for-else without a break is quite useless. What exactly ARE you arguing here? The else is associated with the break to the exact extent that one is essential to the other's value. I'm not arguing. That was just for the record, how things are done in Python. Basically, I simply asked a question and got a definite answer and clear understanding shortly, in a few replies. All the rest of this thread looks irrelevant to me, it's about coding style and probably should be continued under a different title, but I'm not interested to participate in it. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 09/10/2022 03:33, Jach Feng wrote: Axy 在 2022年10月8日 星期� �上午11:39:44 [UTC+8] 的信中寫道: Hi there, this is rather a philosophical question, but I assume I miss something. I don't remember I ever used else clause for years I was with python and my expectation was it executed only if the the main body was never run. Ha-ha! I was caught by this mental trap. So, seriously, why they needed else if the following pieces produce same result? Does anyone know or remember their motivation? Just curious. Axy. print('--- with else') for i in [1,2,3]: print(i) else: print(4) for i in []: print(i) else: print(5) print('--- without else') for i in [1,2,3]: print(i) print(4) for i in []: print(i) print(5) The else is always coming with the break, not the for. However, the compiler does not complain. There are [for ...], [for...break...], and[for...break...else], That's implied and contradicts Zen of Python, I think. If "else" came with "break" there had to be a strong indication of that, namely indentation, as it takes place for all other statements with their clauses. However, there's no such an explicit connection between "break" and "else". That's the point. Well, sorry for this addition to the discussion which went weird way. I should had to be cautious mentioning particular coding style, that's a totally different subject, actually. Let's close it at last. but the [for...else] is insane. Not in Python. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
Since many languages allow placing multiple statements on one line or spreading one over many lines, it seems that the number of lines in code can be adjusted. If I have a line like: Alpha, beta, gamma, delta = 1, 2, 3, 4 Could that be rewritten as 4 or more lines? Surely! Especially if you're paid for SLOC :-))) By the way, does "else" clause after affect cyclomatic complexity metric? I mean "for" loops. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
Yes, I'm aware that code readability becomes irrelevant for short-duration projects. Beside the point. I'm wondering how important it really is to have the shortest block first. I also might be wrong in terminology, anyway, there are many rules that make programmer's life easier, described in the literature from the old good "How to write unmaintainable code" to "The Art of Readable Code". And I hope there are a lot of recent books on this subject I did not track and read yet. Also not really a justification for "shortest block first". Wanting some elaboration on that. What's the value in it? Well, the value is productivity. No need to save puzzles "what this hanging else belongs to?" regardless of semantic, which ideally should not be a puzzle as well. Code small things first and return early, same as taking a test: do easy and quick things first and boring and difficult ones later. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
On 09/10/2022 05:47, Chris Angelico wrote: On Sun, 9 Oct 2022 at 15:39, Axy via Python-list wrote: Got it, thanks! Actually the reason I never used "else" was the violation of the rule of beauty "shortest block first". With if--else you can easily follow this rule by inverting "if" expression, but with for--else you can't. The loop body of the simplest example is already three lines, in real life things are much worse. That's not a rule I've ever been taught; how important is it? ChrisA It gets important if the lifetime of your project is more than three months and is extremely important if more than 10 years. But, it depends. I also might be wrong in terminology, anyway, there are many rules that make programmer's life easier, described in the literature from the old good "How to write unmaintainable code" to "The Art of Readable Code". And I hope there are a lot of recent books on this subject I did not track and read yet. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
Got it, thanks! Actually the reason I never used "else" was the violation of the rule of beauty "shortest block first". With if--else you can easily follow this rule by inverting "if" expression, but with for--else you can't. The loop body of the simplest example is already three lines, in real life things are much worse. So it was probably the first time I used "else" because I had only one line in my loop which appended data packets to the buffer and if "else" behaved as I thought it would meant I have no more data and could just return early, terminating outer loop with no other boolean logic. I have no idea why I thought so, some language might had such a semantic. Maybe my own I developed 20 years ago, but I could not invent that by myself, I definitely had some source of inspiration. Python is awesome because it's semantic is clear for the majority, but there are places that look odd. In case of "for", "else" looks logically tied with "for" clause, but actually it is not. It's tied with "break" statement and I overlooked that even after re-reading the language reference. If "else" was named like "never_broken_loop" or "nobreak", the semantic would be perfectly clear. But, what's done is done. I guess the real motivation was avoiding moving such patterns to a separate functions, say, "find_banana" where early returns make "else" absolutely unnecessary. Cheers. Axy. On 08/10/2022 06:49, rbowman wrote: On 10/7/22 21:32, Axy wrote: So, seriously, why they needed else if the following pieces produce same result? Does anyone know or remember their motivation? In real scenarios there would be more logic in the for block that would meet a condition and break out of the loop. If the condition is never met, the else block runs. To steal from w3schools: fruits = ["apple", "peach", "cherry"] for x in fruits: print(x) if x == "banana": break else: print("Yes we got no bananas") -- https://mail.python.org/mailman/listinfo/python-list
for -- else: what was the motivation?
Hi there, this is rather a philosophical question, but I assume I miss something. I don't remember I ever used else clause for years I was with python and my expectation was it executed only if the the main body was never run. Ha-ha! I was caught by this mental trap. So, seriously, why they needed else if the following pieces produce same result? Does anyone know or remember their motivation? Just curious. Axy. print('--- with else') for i in [1,2,3]: print(i) else: print(4) for i in []: print(i) else: print(5) print('--- without else') for i in [1,2,3]: print(i) print(4) for i in []: print(i) print(5) -- https://mail.python.org/mailman/listinfo/python-list
Re: Asynchronous execution of synchronous functions
Did you check the ThreadPoolExecutor or the ProcessPoolExecutor? They won't give you atomic writes unless you add a Lock or a Condition, but they will execute your code in another thread or process. Yes, I did, but they are too complicated to use. I'd like something for humans, such as asynchronizer = InThreadExecutor() result = await asynchronizer.run(myfunc, myargs, mykwargs) and I almost implemented that borrowing code from asyncsqlite (doves fly slowly, electric mail is even slower :)), but... Keep in mind that Python's threads have a global interpreter lock (GIL) that prevents full parallelism. Processes work as expected, but require IPC and pickable objects in and out. yes, that became a problem. So, I revoke my question. Went out to redesign the whole approach. Thanks for reply! Axy. -- https://mail.python.org/mailman/listinfo/python-list
Asynchronous execution of synchronous functions
Hi there, is there a library to call functions in context of a thread? For example, as in asyncsqlite which has a thread and a queue I mean has anyone generalized such an approach already? If not, I'll do it myself, no problem. It's a kind of tiny stuff, like atomicwrites, which is quite difficult to dig out with modern search engines that have already rolled down to hell a decade ago. Axy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Conecting to MySQL
trying to connect to MYSQL it appears the error msg below: InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused) [image: conexao.png] How can i fix that.? What do you use for connection? Does the firewall interfere with the connection? Firewall usually causes connection to hang and timeout with no response. But in this case connection looks immediately refused which means either port number is wrong or mysql is not listening on 127.0.0.1. Axy -- https://mail.python.org/mailman/listinfo/python-list
Clabate: minimalistic class-based templates for Python
Hi all, this is a test message after tweaking my self-hosted mail server and the subject is just in case if you receive it https://declassed.art/en/blog/2022/06/29/clabate-class-based-templates Previously I tried to reply to someone here but the message was rejected. Did not post to mail lists from my own mail server before, and this is the only problem left to dig in. Sorry for bothering. Axy -- https://mail.python.org/mailman/listinfo/python-list