Re: [Tutor] beginning to code
Steve D'Aprano wrote: On Fri, 22 Sep 2017 02:57 pm, Bill wrote: I find Python to be more more like Java, with regard to "passing objects by reference". Which is not a surprise, since both Python and Java use the same value passing style: pass by object reference, or pass by sharing if you prefer. Java people don't call it that. They call it pass by value, and categorically deny that it is pass by reference. (They're right about the second point.) I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? What really screws the terminology up is that it's not parameters that are being passed, it's arguments! %-) It also the exact same passing style as used by Swift, except Swift calls it pass by reference, and denies it is pass by value. (They're right about the second point.) -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert pandas series to string and datetime object
On 9/21/17, Peter Otten <__pete...@web.de> wrote: > zljubi...@gmail.com wrote: > >> I have sliced the pandas dataframe >> >> end_date = df[-1:]['end'] >> >> type(end_date) >> Out[4]: pandas.core.series.Series >> >> end_date >> Out[3]: >> 48173 2017-09-20 04:47:59 >> Name: end, dtype: datetime64[ns] >> >> 1. How to get rid of index value 48173 and get only "2017-09-20 > 04:47:59" >> string? I have to call REST API with "2017-09-20 04:47:59" as a >> parameter, >> so I have to get string from pandas datetime64 series. >> 2. How to get rid of index value 48173 and get only datetime object >> [something like datetime.datetime.strptime('2017-09-20 04:47:59', >> '%Y-%m-%d %H:%M:%S')]. Later I will have to check if '2017-09-20 >> 04:47:59' >> < datetime.datetime(2017,1,9) >> >> How to do these conversions? > > After a web search and some trial and error: > d = pd.DataFrame([[1, datetime.datetime.now()], [2, > datetime.datetime.now()]], columns=["whatever", "end"]) d >whateverend > 0 1 2017-09-21 22:36:52.342757 > 1 2 2017-09-21 22:36:52.349973 > > [2 rows x 2 columns] d["end"].astype(datetime.datetime).values[-1] > datetime.datetime(2017, 9, 21, 22, 36, 52, 349973) Or: >>> d.iloc[-1]['end'].strftime('%Y-%m-%d %H:%M:%S') '2017-09-22 09:03:40' PS. pandas is one of reasons why python is so popular these days. But "there is only milion way how to do it" (and other unpythonic issues) I see there every time I am looking at it. :) -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Stefan Ram wrote: Bill writes: Stefan Ram wrote: bartc writes: On 20/09/2017 02:31, Bill wrote: it's implementation, I would say that C++ has it all over Python from the point of view of "intuitiveness". It's much easier to tell what's going on, at a glance, in a C++ program. You're being serious, aren't you? For one example, this is a part of a C++ program: template< typename C >C T( void ( C::* )() ); . It defines a template T, that can be used in a class as follows: struct example { void f(); typedef decltype( T( &f )) S; }; . The type »S« now has a certain property, that can be useful sometimes. What is this property (asking Bill)?As has already been pointed out, one can write "obfuscating code" in any language, with little effort. I strive to write code which is easily understandable--and I document it. I don't wish to debate whether I could make more of a mess in Python, or not. From the point of view of a C++ programmer, the above is not obfuscated, but it is readable and simple C++. It is of course not readable for readers who do not know C++. Just as Python's »string[::-1]« appears "obfuscated" to readers who don't know Python. It was the answer to the question "How can I express the class I'm in in, when I can't write that classes name literally? I would try to use virtual cast in place of the *&%, I mean code, you wrote. "Clever code" is a losing game--just look at your explanation below. Simple==Good. So, »S« is »example«. It works like this: The type of »&f« is »void ( example::* )()«. So, the function-declaration template »T« infers »C« to be »example«, and the type of »T( &f )« is »example«, which then is transferred to the name »S« using typedef. This is obvious for C++ programmers, but it takes a lot of time to become a C++ programmer, maybe more than it takes to become a Python programmer. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Bill wrote: Stefan Ram wrote: Bill writes: Stefan Ram wrote: bartc writes: On 20/09/2017 02:31, Bill wrote: it's implementation, I would say that C++ has it all over Python from the point of view of "intuitiveness". It's much easier to tell what's going on, at a glance, in a C++ program. You're being serious, aren't you? For one example, this is a part of a C++ program: template< typename C >C T( void ( C::* )() ); . It defines a template T, that can be used in a class as follows: struct example { void f(); typedef decltype( T( &f )) S; }; . The type »S« now has a certain property, that can be useful sometimes. What is this property (asking Bill)?As has already been pointed out, one can write "obfuscating code" in any language, with little effort. I strive to write code which is easily understandable--and I document it. I don't wish to debate whether I could make more of a mess in Python, or not. From the point of view of a C++ programmer, the above is not obfuscated, but it is readable and simple C++. It is of course not readable for readers who do not know C++. Just as Python's »string[::-1]« appears "obfuscated" to readers who don't know Python. It was the answer to the question "How can I express the class I'm in in, when I can't write that classes name literally? I would try to use virtual cast in place of the *&%, I mean code, you wrote. Sorry, I mean dynamic_cast(). "Clever code" is a losing game--just look at your explanation below. Simple==Good. So, »S« is »example«. It works like this: The type of »&f« is »void ( example::* )()«. So, the function-declaration template »T« infers »C« to be »example«, and the type of »T( &f )« is »example«, which then is transferred to the name »S« using typedef. This is obvious for C++ programmers, but it takes a lot of time to become a C++ programmer, maybe more than it takes to become a Python programmer. -- https://mail.python.org/mailman/listinfo/python-list
How to ingore "AttributeError: exception
I have two possible values for Z_block in the block code i.e disk_object.data.data.di_data[0] or block.data.data.di_data.data[0][0] def get_block(): ''' Get Z block '' if block.data.data.di_data.data[0][0] is not None: Z_block = block.data.data.di_data.data[0][0] else: Z_block = disk_object.data.data.di_data[0] if not Z_block: return False return Z_block I have a problem with if and else satement i.e if IF codition fails the code would exit with "AttributeError: 'list' object has no attribute 'data' " error Any suggestion on how this can be handled better , Will ignoring the exceptions in try -except with pass be good or are there easier ways ) , try: Z_block = block.data.data.di_data.data[0][0]except AttributeError as e: pass I am a Linux user on Python 2.7 Regards, Ganesh -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Bill : > I figure that, internally, an address, a pointer, is being passed by > value to implement pass by reference. Why do you say "they are right" > above? Are you saying it's not pass by reference? "Pass by reference" could be "pass by reference to object" (Python, Java, JavaScript, Lisp) or "pass by reference to memory slot" (available to Pascal and C++). Memory slots (or lvalues, as they are known in C) are not first class objects in Python, which makes "pass by reference to memory slot" a bit tricky in Python. Python *could* add memory slots to its sanctioned collection of object types, and it *could* add special syntax to express a memory slot reference and dereference ("&" and "*" in C). However, Python doesn't need any language changes to implement memory slots. A memory slot could be defined as any object that implements "get()" and "set(value)" methods: C: &x Python: class Xref: def get(self): return x def set(self, value): nonlocal x; x = value ref_x = Xref() C: &x->y[3] Python: class XY3ref: def get(self): return x.y[3] def set(self, value): x.y[3] = value ref_xy3 = XY3ref() The examples could be simplified: ref_x = slot_ref(locals(), "x") ref_xy3 = slot_ref(x.y, 3) by defining: def slot_ref(dict_or_array, key_or_index): class SlotRef: def get(self): return dict_or_array[key_or_index] def set(self, value): dict_or_array[key_or_index] = value return SlotRef() Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: How to ingore "AttributeError: exception
On 2017-09-22 10:55, Ganesh Pal wrote: > I have two possible values for Z_block in the block code i.e > disk_object.data.data.di_data[0] or block.data.data.di_data.data[0][0] > > > def get_block(): > ''' Get Z block '' > > if block.data.data.di_data.data[0][0] is not None: > Z_block = block.data.data.di_data.data[0][0] > > else: > Z_block = disk_object.data.data.di_data[0] > > if not Z_block: > return False > > return Z_block > > > > > I have a problem with if and else satement i.e if IF codition fails the > code would exit with "AttributeError: 'list' object has no attribute > 'data' " error > > Any suggestion on how this can be handled better , Will ignoring the > exceptions in try -except with pass be good or are there easier ways ) , > > > try: > Z_block = block.data.data.di_data.data[0][0]except AttributeError as e: > > pass try: return self.some.attribute.or.another except AttributeError: return DEFAULT_VALUE is a perfectly good pattern to use. > > > I am a Linux user on Python 2.7 Have you considered moving to Python 3? > > > Regards, > Ganesh > -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Marko Rauhamaa wrote: Bill : I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? Thank you for your examples. I studied them carefully (and I'm not through with them yet). I just wanted to mention that my comment was made in the context that Python is implemented by an interpreter written in C. I realize that this may not always be the case. However, I haven't heard anyone mention a Python interpreter written in Python yet. "Pass by reference" could be "pass by reference to object" (Python, Java, JavaScript, Lisp) or "pass by reference to memory slot" (available to Pascal and C++). Memory slots (or lvalues, as they are known in C) are not first class objects in Python, which makes "pass by reference to memory slot" a bit tricky in Python. Python *could* add memory slots to its sanctioned collection of object types, and it *could* add special syntax to express a memory slot reference and dereference ("&" and "*" in C). However, Python doesn't need any language changes to implement memory slots. A memory slot could be defined as any object that implements "get()" and "set(value)" methods: C: &x Python: class Xref: def get(self): return x def set(self, value): nonlocal x; x = value ref_x = Xref() C: &x->y[3] Python: class XY3ref: def get(self): return x.y[3] def set(self, value): x.y[3] = value ref_xy3 = XY3ref() The examples could be simplified: ref_x = slot_ref(locals(), "x") ref_xy3 = slot_ref(x.y, 3) by defining: def slot_ref(dict_or_array, key_or_index): class SlotRef: def get(self): return dict_or_array[key_or_index] def set(self, value): dict_or_array[key_or_index] = value return SlotRef() Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: How to ingore "AttributeError: exception
On 22 September 2017 at 10:05, Thomas Jollans wrote: > On 2017-09-22 10:55, Ganesh Pal wrote: >> I have two possible values for Z_block in the block code i.e >> disk_object.data.data.di_data[0] or block.data.data.di_data.data[0][0] >> >> >> def get_block(): >> ''' Get Z block '' >> >> if block.data.data.di_data.data[0][0] is not None: >> Z_block = block.data.data.di_data.data[0][0] >> >> else: >> Z_block = disk_object.data.data.di_data[0] >> >> if not Z_block: >> return False >> >> return Z_block >> >> >> >> >> I have a problem with if and else satement i.e if IF codition fails the >> code would exit with "AttributeError: 'list' object has no attribute >> 'data' " error >> >> Any suggestion on how this can be handled better , Will ignoring the >> exceptions in try -except with pass be good or are there easier ways ) , >> >> >> try: >> Z_block = block.data.data.di_data.data[0][0]except AttributeError as e: >> >> pass > > > > try: > return self.some.attribute.or.another > except AttributeError: > return DEFAULT_VALUE > > is a perfectly good pattern to use. getattr(obj, 'attr_name', DEFAULT_VALUE) may also be useful, although if more than one of the attribute lookups in the chain you show could fail, then catching the exception is probably simpler. Paul -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On 22/09/2017 10:23, Marko Rauhamaa wrote: Bill : I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? "Pass by reference" could be "pass by reference to object" (Python, Java, JavaScript, Lisp) or "pass by reference to memory slot" (available to Pascal and C++). Memory slots (or lvalues, as they are known in C) are not first class objects in Python, which makes "pass by reference to memory slot" a bit tricky in Python. Python *could* add memory slots to its sanctioned collection of object types, and it *could* add special syntax to express a memory slot reference and dereference ("&" and "*" in C). However, Python doesn't need any language changes to implement memory slots. A memory slot could be defined as any object that implements "get()" and "set(value)" methods: I didn't understand your examples. Can Python be used to write, say, a swap() function that works with any argument types (not just classes or lists)? Example: def swap(&a,&b):# made up syntax a, b = b, a x=10 y="Z" swap(x,y) print (x,y) # "Z" and "10" If not, then it doesn't have reference passing as it is normally understood. A simpler example: def set(&a,value): a = value set(x,100) Here the type of x is irrelevant anyway. It doesn't even need to be initialised to anything first (that might violate something in Python, I don't know what). -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On Fri, 22 Sep 2017 03:44:59 +1000, Steve D'Aprano wrote: > On Fri, 22 Sep 2017 02:29 am, Tobiah wrote: > >> Are these completely equivalent? >> >> def foo(thing): >> >> assert(thing > 0), "Thing must be greater than zero" >> >> >> def foo(thing): >> >> if not (thing > 0): raise AssertionError("Thing must be greater >> than zero") >> >> >> Other than the fact that the assertion can be turned off with -O? > > As I replied to Ned just now, the two may compile to slightly different > byte-code. But (apart from the -O optimization) they ought to be > semantically the same, as far as the interpreter goes. I'd be very > surprised if the byte-code differences were ever more than trivial. > > But I don't think they are the same as far as the human reader goes. If > you believe the truism that code is written for other people, and only > incidentally to be run by computers, then I think we should say that the > two above are very different. > > The first is an actual assertion. It has to be an assertion, because it > uses the assert keyword! > > The second is testing a condition, and if need be, raising an exception. > Which looks like an inappropriate exception. Why AssertionError? It > looks like it ought to be a ValueError. > > Assertions aren't merely a synonym for testing a condition and raising > an exception if the condition fails. Assertions have semantics to the > human reader. I wrote a blog post explaining why you should use > assertions: > > - you want a checked comment; > - you have code that can't possibly fail, unless it does; > - you are testing the program logic; > - you are checking a contract; > > and when you should not. By using `assert`, you are signalling your > intent to do one of the above. > > http://import-that.dreamwidth.org/676.html > > But by using an ordinary `if ... raise AssertionError`, the intention is > ambiguous. If you meant for it to be an assertion, why not use assert? > If it is not an assertion, then AssertionError is probably the wrong > exception. > > (It is okay in a testing framework, like unittest, but a bad idea in a > regular library or an application. Your end-users should never see an > AssertionError.) > > > The bottom line is, if I saw > > if not (thing > 0): raise AssertionError(...) > > in a code review, I'd probably insist that either it be changed to use > `assert`, > or the exception be changed to ValueError, whichever better expresses > the intention of the code. In a code review I would want the condition changed to be less noisy/ confusing to the reader. if thing <=0: whatever -- The best thing about growing older is that it takes such a long time. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, 22 Sep 2017 07:53 pm, Bill wrote: > Marko Rauhamaa wrote: >> Bill : >> >>> I figure that, internally, an address, a pointer, is being passed by >>> value to implement pass by reference. Why do you say "they are right" >>> above? Are you saying it's not pass by reference? > > Thank you for your examples. I studied them carefully (and I'm not > through with them yet). > I just wanted to mention that my comment was made in the context that > Python is implemented by an interpreter written in C. I realize that > this may not always be the case. However, I haven't heard anyone > mention a Python interpreter written in Python yet. I don't see what the implementation language has to do with anything (except perhaps performance). You can implement any language in any other language, with greater or less difficulty, but its still possible. CPython is written in C, as is Stackless. Jython is written in Java. IronPython is written in C# for .Net. PyPy is written in a custom version of Python, RPython. Nuitka is written in C++. CLPython is written in Lisp. Berp and Hope are written in Haskell. Skulpt is written in Javascript. Vyper was a really old implementation written in OCaml, apparently now lost and no longer visible on the internet. Some of these may been no longer supported, but the Big Four python implementations are CPython, Jython, IronPython and PyPy. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, 22 Sep 2017 08:48 pm, bartc wrote: > Can Python be used to write, say, a swap() function that works with any > argument types (not just classes or lists)? Example: > > def swap(&a,&b):# made up syntax > a, b = b, a > > x=10 > y="Z" > swap(x,y) > print (x,y) # "Z" and "10" > > If not, then it doesn't have reference passing as it is normally understood. No it cannot, and does not. You can emulate it by adding a layer of redirection, but that's it. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On Fri, 22 Sep 2017 08:50 pm, alister wrote: >> The bottom line is, if I saw >> >> if not (thing > 0): raise AssertionError(...) >> >> in a code review, I'd probably insist that either it be changed to use >> `assert`, >> or the exception be changed to ValueError, whichever better expresses >> the intention of the code. > > In a code review I would want the condition changed to be less noisy/ > confusing to the reader. > > if thing <=0: whatever Fair point, assuming they are the same. Actually, even for floats they're not the same. py> not (NAN > 0) True py> NAN <= 0 False -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
bartc : > On 22/09/2017 10:23, Marko Rauhamaa wrote: >> However, Python doesn't need any language changes to implement memory >> slots. A memory slot could be defined as any object that implements >> "get()" and "set(value)" methods: > > I didn't understand your examples. > > Can Python be used to write, say, a swap() function that works with any > argument types (not just classes or lists)? Example: > > def swap(&a,&b):# made up syntax > a, b = b, a > > x=10 > y="Z" > swap(x,y) > print (x,y) # "Z" and "10" Yes, following my recipe: def swap(ref_a, ref_b): a, b = ref_a.get(), ref_b.get() ref_a.set(b) ref_b.set(a) x = 10 y = "Z" swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) print(x, y) # "Z" and 10 Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, 22 Sep 2017 05:01 pm, Bill wrote: > Steve D'Aprano wrote: >> On Fri, 22 Sep 2017 02:57 pm, Bill wrote: >> >>> I find Python to be more more >>> like Java, with regard to "passing objects by reference". >> Which is not a surprise, since both Python and Java use the same value >> passing style: pass by object reference, or pass by sharing if you prefer. >> >> Java people don't call it that. They call it pass by value, and categorically >> deny that it is pass by reference. (They're right about the second point.) > > I figure that, internally, an address, a pointer, is being passed by > value to implement pass by reference. Why do you say "they are right" > above? Are you saying it's not pass by reference? Are you suggested that the Java people are wrong to say it isn't? Last time I suggested that the Java community had made a mistake in this regard, I got blasted by certain folks here for insulting the intelligence of compiler experts. But yes, I agree with the Java community that what they do is NOT pass by reference. It clearly is not: the canonical test for pass by reference is whether you can write a "swap" procedure which swaps two variables: a = 1 b = 2 swap(a, b) assert a == 2 and b == 1 A general swap procedure cannot be written in Python or Java. (We don't need one, in Python, because we have alternatives which are arguably better, but that's not the point.) So I am in 100% agreement with the Java people when they say what they do (and what Python does) is not pass by reference. > What really screws the terminology up is that it's not parameters that > are being passed, it's arguments! %-) I don't believe that I mentioned parameters or arguments, so that's a red herring. The terminology is fine, if we don't insist on ignoring it. There are many more kinds of passing semantics than just by value and by reference, and the confusion only occurs when people insist on taking the round peg of a language's actual behaviour, and hammering it in by brute-force into the square hole of "pass by value" or "pass by reference". Quoting Wikipedia: In some cases, the term "call by value" is problematic, as the value which is passed is not the value of the variable as understood by the ordinary meaning of value, but an implementation-specific reference to the value. Some examples: - call by sharing - call by need - call by name - call by copy-restore ("copy in, copy out") etc. https://en.wikipedia.org/wiki/Evaluation_strategy -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, Sep 22, 2017 at 9:24 PM, Marko Rauhamaa wrote: > bartc : > >> On 22/09/2017 10:23, Marko Rauhamaa wrote: >>> However, Python doesn't need any language changes to implement memory >>> slots. A memory slot could be defined as any object that implements >>> "get()" and "set(value)" methods: >> >> I didn't understand your examples. >> >> Can Python be used to write, say, a swap() function that works with any >> argument types (not just classes or lists)? Example: >> >> def swap(&a,&b):# made up syntax >> a, b = b, a >> >> x=10 >> y="Z" >> swap(x,y) >> print (x,y) # "Z" and "10" > > Yes, following my recipe: > >def swap(ref_a, ref_b): >a, b = ref_a.get(), ref_b.get() >ref_a.set(b) >ref_b.set(a) > >x = 10 >y = "Z" >swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) >print(x, y) # "Z" and 10 Sure, let me just put that into a function. CPython 3.7, although I'm pretty sure most CPython versions will do the same, as will several of the other Pythons. (Side point: Your slot_ref function is rather bizarre. It's a closure AND a class, just in case one of them isn't sufficient. The following code is copied and pasted from two of your posts and is unchanged other than making try_swapping into a function.) >>> def slot_ref(dict_or_array, key_or_index): ...class SlotRef: ...def get(self): return dict_or_array[key_or_index] ...def set(self, value): dict_or_array[key_or_index] = value ...return SlotRef() ... >>> def swap(ref_a, ref_b): ...a, b = ref_a.get(), ref_b.get() ...ref_a.set(b) ...ref_b.set(a) ... >>> def try_swapping(): ...x = 10 ...y = "Z" ...swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) ...print("x, y =", x, y) ... >>> try_swapping() x, y = 10 Z Strange... doesn't seem to work. Are you saying that Python is pass-by-reference outside of a function and pass-by-value inside? Because that'd be just insane. Or maybe what you have here isn't a real reference at all. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On 22/09/2017 12:47, Chris Angelico wrote: On Fri, Sep 22, 2017 at 9:24 PM, Marko Rauhamaa wrote: Yes, following my recipe: def swap(ref_a, ref_b): a, b = ref_a.get(), ref_b.get() ref_a.set(b) ref_b.set(a) x = 10 y = "Z" swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) print(x, y) # "Z" and 10 Sure, let me just put that into a function. CPython 3.7, although I'm pretty sure most CPython versions will do the same, as will several of the other Pythons. (Side point: Your slot_ref function is rather bizarre. It's a closure AND a class, just in case one of them isn't sufficient. The following code is copied and pasted from two of your posts and is unchanged other than making try_swapping into a function.) def slot_ref(dict_or_array, key_or_index): ...class SlotRef: ...def get(self): return dict_or_array[key_or_index] ...def set(self, value): dict_or_array[key_or_index] = value ...return SlotRef() ... def swap(ref_a, ref_b): ...a, b = ref_a.get(), ref_b.get() ...ref_a.set(b) ...ref_b.set(a) ... def try_swapping(): ...x = 10 ...y = "Z" ...swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) ...print("x, y =", x, y) ... try_swapping() x, y = 10 Z Strange... doesn't seem to work. Are you saying that Python is pass-by-reference outside of a function and pass-by-value inside? Because that'd be just insane. Or maybe what you have here isn't a real reference at all. It also looks too complicated to be really useful. And I'm not sure it would work (when it does work), with more complex terms. For simple given: A = [10,20,30] B = ["X","Y","Z"] and wanting to swap A[0] and B[2]. Although these being list elements, they /could/ be exchanged via a function: def swapelems(a,i,b,j): a[i],b[j]=b[j],a[i] swapelems(A,0,B,2) Just not using a general-purpose swap function. -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On Fri, 22 Sep 2017 21:15:54 +1000, Steve D'Aprano wrote: > On Fri, 22 Sep 2017 08:50 pm, alister wrote: > >>> The bottom line is, if I saw >>> >>> if not (thing > 0): raise AssertionError(...) >>> >>> in a code review, I'd probably insist that either it be changed to use >>> `assert`, >>> or the exception be changed to ValueError, whichever better expresses >>> the intention of the code. >> >> In a code review I would want the condition changed to be less noisy/ >> confusing to the reader. >> >> if thing <=0: whatever > > Fair point, assuming they are the same. > > Actually, even for floats they're not the same. > > py> not (NAN > 0) > True py> NAN <= 0 False I bet those are conditions the original author did not expect actually I am not sure how you got them on my system python 2.7 >>> not (NAN >0) Traceback (most recent call last): File "", line 1, in NameError: name 'NAN' is not defined >>> NAN <=0 Traceback (most recent call last): File "", line 1, in NameError: name 'NAN' is not defined Python 3 Python 3.6.2 (default, Aug 11 2017, 11:59:59) [GCC 7.1.1 20170622 (Red Hat 7.1.1-3)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> not (NAN > 0) Traceback (most recent call last): File "", line 1, in NameError: name 'NAN' is not defined >>> NAN <= 0 Traceback (most recent call last): File "", line 1, in NameError: name 'NAN' is not defined I would also say that if your examples did indeed return different results then pythons logic model has a bug. -- Say "twenty-three-skiddoo" to logout. -- https://mail.python.org/mailman/listinfo/python-list
xml: TypeError: write() got an unexpected keyword argument 'short_empty_elements'
Here is an MWE: import io from lxml import etree test_node = etree.fromstring(''' http://schemas.xmlsoap.org/soap/envelope/"; xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-trust/200512";> ''') output = io.BytesIO(b'') test_node.getroottree().write(output, encoding="UTF-8", xml_declaration=None, default_namespace=None, method="c14n", short_empty_elements=False ) output.seek(0) print(output.read()) Result: Traceback (most recent call last): File "C:/not_telling/c14n.py", line 16, in short_empty_elements=False File "lxml.etree.pyx", line 1869, in lxml.etree._ElementTree.write (src\lxml\lxml.etree.c:57004) TypeError: write() got an unexpected keyword argument 'short_empty_elements' I have tracked down this to: https://github.com/python/cpython/blob/master/Lib/xml/etree/ElementTree.py#L721 This method does have a "short_empty_elements" argument, but if I set it to True, then it fails with TypeError. Is this a bug? -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On 22/09/2017 08:01, Bill wrote: Steve D'Aprano wrote: On Fri, 22 Sep 2017 02:57 pm, Bill wrote: I find Python to be more more like Java, with regard to "passing objects by reference". Which is not a surprise, since both Python and Java use the same value passing style: pass by object reference, or pass by sharing if you prefer. Java people don't call it that. They call it pass by value, and categorically deny that it is pass by reference. (They're right about the second point.) I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? Please see http://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ and http://effbot.org/zone/call-by-object.htm -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email has been checked for viruses by AVG. http://www.avg.com -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On 22/09/2017 10:53, Bill wrote: I just wanted to mention that my comment was made in the context that Python is implemented by an interpreter written in C. I realize that this may not always be the case. However, I haven't heard anyone mention a Python interpreter written in Python yet. The reference implementation is written in C but there's also Jython (Java) and IronPython (.Net). -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email has been checked for viruses by AVG. http://www.avg.com -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Chris Angelico : > Sure, let me just put that into a function. CPython 3.7, although I'm > pretty sure most CPython versions will do the same, as will several of > the other Pythons. > [demonstration that it didn't work] Ok. The reason is this: Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. https://docs.python.org/3/library/functions.html#locals> So the language specification explicitly ruled it out, unfortunately. > (Side point: Your slot_ref function is rather bizarre. It's a closure > AND a class, just in case one of them isn't sufficient. I don't see anything bizarre in it at all. I use the pattern all the time. It's called an inner class: In Python, it is possible to nest a class within another class, method or function. https://en.wikipedia.org/wiki/Inner_class#Programming_languages> Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: xml: TypeError: write() got an unexpected keyword argument 'short_empty_elements'
> Result: > > Traceback (most recent call last): > File "C:/not_telling/c14n.py", line 16, in > short_empty_elements=False > File "lxml.etree.pyx", line 1869, in lxml.etree._ElementTree.write > (src\lxml\lxml.etree.c:57004) > TypeError: write() got an unexpected keyword argument 'short_empty_elements' Well, it looks like etree does not implement the short_empty_elements argument in its write method: https://github.com/lxml/lxml/blob/master/src/lxml/etree.pyx#L1954 But it should (see https://github.com/lxml/lxml/blob/master/src/lxml/etree.pyx#L5 - The ``lxml.etree`` module implements the extended ElementTree API for XML. ) Can somebody please confirm that this is a bug? Also, how can I send a bug report? ( I'm not able to add an issue to lxml, lack of permissions. ) -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
r...@zedat.fu-berlin.de (Stefan Ram): > Marko Rauhamaa writes: >>swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) > > You need to be able to write the call as > > swap( x, y ) Why? Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, 22 Sep 2017 09:24 pm, Marko Rauhamaa wrote: > bartc : > >> On 22/09/2017 10:23, Marko Rauhamaa wrote: >>> However, Python doesn't need any language changes to implement memory >>> slots. A memory slot could be defined as any object that implements >>> "get()" and "set(value)" methods: >> >> I didn't understand your examples. >> >> Can Python be used to write, say, a swap() function that works with any >> argument types (not just classes or lists)? Example: >> >> def swap(&a,&b):# made up syntax >> a, b = b, a >> >> x=10 >> y="Z" >> swap(x,y) >> print (x,y) # "Z" and "10" > > Yes, following my recipe: > >def swap(ref_a, ref_b): >a, b = ref_a.get(), ref_b.get() >ref_a.set(b) >ref_b.set(a) > >x = 10 >y = "Z" >swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) >print(x, y) # "Z" and 10 No, you failed to follow Bart's instructions and answered a different question. "Can you pulverise this granite boulder with your bare hands?" "Sure! I just need to use this sledge hammer, and pulverise this small sandstone rock instead." You have to pass x and y, not strings 'x' and 'y'. The swap procedure needs to accept any variable, given as ordinary bare names swap(x, y), not written as strings, or by hard-coding x and y as the variables to swap, or by using a string and passing it to exec, or any other loophole. Also, you're assuming that locals() is writable, which in the most general case it is not. Try using locals from inside a function, rather than in the global scope. You made a good attempt to emulate pass by reference via an extra layer of indirection. Pity that it doesn't solve the problem and doesn't work. Here's an easy way to emulate pass by reference which works in any scope: use a list. def swap(a, b): a[0], b[0] = b[0], a[0] a = [1] b = [2] swap(a, b) assert a[0] == 2 and b[0] == 1 It's not proper pass by reference, and so will still fail Bart's test, because you need to manually add an extra layer of redirection (using a list). Its like using a pointer in C to emulate references, compared to having actual language support for them like in Pascal or C++. But if I wanted to write a Pascal interpreter in Python, I could use something like this to implement Pascal var parameters. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On 2017-09-22 14:03, alister via Python-list wrote: > On Fri, 22 Sep 2017 21:15:54 +1000, Steve D'Aprano wrote: >> On Fri, 22 Sep 2017 08:50 pm, alister wrote: >>> [snip] >>> >>> In a code review I would want the condition changed to be less noisy/ >>> confusing to the reader. >>> >>> if thing <=0: whatever >> >> Fair point, assuming they are the same. >> >> Actually, even for floats they're not the same. >> > [snip] > > I would also say that if your examples did indeed return different > results then pythons logic model has a bug. No, it doesn't (in Python 3). NaN is not a number. It is neither larger nor smaller than zero. This behavior is correct: Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from math import nan >>> nan < 0 False >>> nan > 0 False >>> nan == 0 False >>> not (nan > 0) True Python 2.7 is a bit more fickle: Python 2.7.5 (default, Aug 2 2017, 11:05:32) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from numpy import nan >>> nan < 0 False >>> nan > 0 False >>> nan == 0 False >>> not(nan > 0) True >>> cmp(nan, 0) -1 >>> cmp(0, nan) 1 Of course I see why the behavior of NaN is hard to swallow: in a sense the logical thing to do would be to raise a ValueError (or TypeError) when comparing to NaN - seeing as the operation doesn't make much sense in the first place - but it's better to not have an edge case where comparing two floats can raise, but only under very unusual circumstances. Cheers, Thomas -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
r...@zedat.fu-berlin.de (Stefan Ram): > Marko Rauhamaa writes: >>r...@zedat.fu-berlin.de (Stefan Ram): >>>Marko Rauhamaa writes: swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) >>>You need to be able to write the call as >>>swap( x, y ) >>Why? > > You responded to Bart: > > | swap(x,y) > | print (x,y) # "Z" and "10" > | > |If not, then it doesn't have reference passing as > |it is normally understood. > > , and Bart required this form. Moreover, if you allow other > forms, such as > > swap( &x, &y ) > > , then even C, would have "call by reference", > but it has not. There's two things: syntax and semantics. Obviously, Bart's syntax couldn't work syntactically unless Python added the syntactic facilities. But the bigger question is a semantic one: is it possible regardless of syntactic considerations. As Chris pointed out, Python has explicitly ruled it out with the immutability caveat to locals(). Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On Fri, 22 Sep 2017 10:03 pm, alister wrote: > On Fri, 22 Sep 2017 21:15:54 +1000, Steve D'Aprano wrote: > >> On Fri, 22 Sep 2017 08:50 pm, alister wrote: >> The bottom line is, if I saw if not (thing > 0): raise AssertionError(...) in a code review, I'd probably insist that either it be changed to use `assert`, or the exception be changed to ValueError, whichever better expresses the intention of the code. >>> >>> In a code review I would want the condition changed to be less noisy/ >>> confusing to the reader. >>> >>> if thing <=0: whatever >> >> Fair point, assuming they are the same. >> >> Actually, even for floats they're not the same. >> >> py> not (NAN > 0) >> True py> NAN <= 0 False > > I bet those are conditions the original author did not expect Yes, everyone forgets about NAN ("Not A Number"). > actually I am not sure how you got them on my system Oops, sorry, NAN is defined in my startup.py file, together with INF. NAN = float('nan') INF = float('inf') Apologies. > I would also say that if your examples did indeed return different > results then pythons logic model has a bug. No, Python does the right thing here. Not all classes of values have a total ordering. With numbers, we can safely say that if x > y, and y > z, then x > z too. But that doesn't necessarily hold for everything. E.g. if x, y and z are sports teams, and we identify ">" with "beats", then x can beat y, and y beat z, but x lose to z. This isn't *numeric* order, but it is a valid form of order. In the case of floating point NANs, they are unordered with respect to all numbers. So for any number x, we always have: NAN == x NAN < x NAN > x NAN <= x NAN >= x all return False, and NAN != x return True. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On 22/09/2017 13:34, Steve D'Aprano wrote: On Fri, 22 Sep 2017 09:24 pm, Marko Rauhamaa wrote: Yes, following my recipe: def swap(ref_a, ref_b): a, b = ref_a.get(), ref_b.get() ref_a.set(b) ref_b.set(a) x = 10 y = "Z" swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) print(x, y) # "Z" and 10 No, you failed to follow Bart's instructions and answered a different question. You have to pass x and y, not strings 'x' and 'y'. The swap procedure needs to accept any variable, given as ordinary bare names swap(x, y), not written as strings, or by hard-coding x and y as the variables to swap, or by using a string and passing it to exec, or any other loophole. And being able to pass any lvalue expression, not just simple variable names. Such as a[i] or x.y, provided the term is mutable. (To make it work would require a new reference type. And extra versions of the byte-codes or whatever is used to evaluate terms such as: a, a[i], x.y that evaluate a reference rather than the value. So LOADFASTREF as well as LOADFAST) -- bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: xml: TypeError: write() got an unexpected keyword argument 'short_empty_elements'
On 2017-09-22 14:29, Nagy László Zsolt wrote: > >> Result: >> >> Traceback (most recent call last): >> File "C:/not_telling/c14n.py", line 16, in >> short_empty_elements=False >> File "lxml.etree.pyx", line 1869, in lxml.etree._ElementTree.write >> (src\lxml\lxml.etree.c:57004) >> TypeError: write() got an unexpected keyword argument 'short_empty_elements' > Well, it looks like etree does not implement the short_empty_elements > argument in its write method: > > https://github.com/lxml/lxml/blob/master/src/lxml/etree.pyx#L1954 > > But it should (see > https://github.com/lxml/lxml/blob/master/src/lxml/etree.pyx#L5 - The > ``lxml.etree`` module implements the extended ElementTree API for XML. ) > > Can somebody please confirm that this is a bug? Also, how can I send a > bug report? ( I'm not able to add an issue to lxml, lack of permissions. ) > https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write The argument was added in Python 3.4. Presumably, lxml implemented the API before this change. Maybe this would be considered a bug by lxml. Maybe it won't. http://lxml.de/ links to a bug tracker and a mailing list. -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
what is happening in panda "where" clause
This code does a "where" clause on a panda data frame... Code: import pandas as pd; col_names = ['Name', 'Age', 'Weight', "Education"]; # create panda dataframe x = pd.read_csv('test.dat', sep='|', header=None, names = col_names); # apply "where" condition z = x[ (x['Age'] == 55) ] # prints row WHERE age == 55 print (z); What is happening in this statement: z = x[ (x['Age'] == 55) ] Thanks, Pedro Exposito The information contained in this e-mail message is intended only for the personal and confidential use of the recipient(s) named above. This message may be an attorney-client communication and/or work product and as such is privileged and confidential. If the reader of this message is not the intended recipient or an agent responsible for delivering it to the intended recipient, you are hereby notified that you have received this document in error and that any review, dissemination, distribution, or copying of this message is strictly prohibited. If you have received this communication in error, please notify us immediately by e-mail, and delete the original message. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to ingore "AttributeError: exception
> > > is a perfectly good pattern to use. > Thanks looks nice :) > > > > > > > > I am a Linux user on Python 2.7 > > Have you considered moving to Python 3? > Not yet , but Is there something that I need to consider in the current context? Regards, Ganesh -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On 2017-09-22 14:43, Steve D'Aprano wrote: > In the case of floating point NANs, they are unordered with respect to all > numbers. So for any number x, we always have: > > NAN == x > NAN < x > NAN > x > NAN <= x > NAN >= x > > all return False, and > > NAN != x > > return True. Just to make the implication explicit: >>> from math import nan >>> nan is nan True >>> nan == nan False >>> nan != nan True >>> -- Thomas Jollans -- https://mail.python.org/mailman/listinfo/python-list
Re: xml: TypeError: write() got an unexpected keyword argument 'short_empty_elements'
> https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write > > The argument was added in Python 3.4. Presumably, lxml implemented the > API before this change. > > Maybe this would be considered a bug by lxml. Maybe it won't. Maybe it is not a bug, just a feature not implemented. After testing it a bit, I realized that for my chosen method (c14n) it cannot be specified anyway, because it must be False and actually it works that way. > > http://lxml.de/ links to a bug tracker and a mailing list. > All right, I'm subscribing to the list (I have other questions regarding C14N) -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, 22 Sep 2017 10:27 pm, Marko Rauhamaa wrote: > r...@zedat.fu-berlin.de (Stefan Ram): > >> Marko Rauhamaa writes: >>>swap(slot_ref(locals(), "x"), slot_ref(locals(), "y")) >> >> You need to be able to write the call as >> >> swap( x, y ) > > Why? Because that's the whole point of the exercise. The exercise isn't to demonstrate how to swap two variables. In Python, that's easy: a, b = b, a The exercise is to demonstrate pass by reference semantics. That requires demonstrating the same semantics as the Pascal swap procedure: procedure swap(var a, var b): begin tmp := a; a := b; b := tmp; end; (ignoring the type declarations for brevity). Call by reference semantics enable you to call swap(x, y) to swap x and y in the caller's scope. You don't call swap('x', 'y', scope_of_x, scope_of_y) or any other variant. That isn't call by reference semantics. The whole point of call by reference semantics is that the *compiler*, not the programmer, tracks the variables and their scopes. The programmer just says "swap x and y", and the compiler works out how to do it. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
search and replace first amount of strings instances with one thing and a second amount of instances with another thing-
i have a code in python to search and replace what i need though is to replace the first say 10 instances of the number 1 with 2 and the second 10 instances with the number 3. anybody knows how to do that? fin = open(r'F:\1\xxx.txt') fout = open(r'F:\1\xxx2.txt', "wt") for line in fin: fout.write( line.replace('1', '2') ) fin.close() fout.close() -- https://mail.python.org/mailman/listinfo/python-list
Re: what is happening in panda "where" clause
Exposito, Pedro (RIS-MDW) wrote: > This code does a "where" clause on a panda data frame... > > Code: > import pandas as pd; > col_names = ['Name', 'Age', 'Weight', "Education"]; > # create panda dataframe > x = pd.read_csv('test.dat', sep='|', header=None, names = col_names); > # apply "where" condition > z = x[ (x['Age'] == 55) ] > # prints row WHERE age == 55 > print (z); > > What is happening in this statement: > z = x[ (x['Age'] == 55) ] > > Thanks, Let's take it apart into individual steps: Make up example data: >>> import pandas as pd >>> x = pd.DataFrame([["Jim", 44], ["Sue", 55], ["Alice", 66]], columns=["Name", "Age"]) >>> x Name Age 0Jim 44 1Sue 55 2 Alice 66 Have a look at the inner expression: >>> x["Age"] == 55 0False 1 True 2False So this is a basically vector of boolean values. If you want more details: in numpy operations involving a a scalar and an array work via "broadcasting". In pure Python you would write something similar as >>> [v == 55 for v in x["Age"]] [False, True, False] Use the result as an index: >>> x[[False, True, True]] Name Age 1Sue 55 2 Alice 66 [2 rows x 2 columns] This is again in line with numpy arrays -- if you pass an array of boolean values as an index the values in the True positions are selected. In pure Python you could achieve that with >>> index = [v == 55 for v in x["Age"]] >>> index [False, True, False] >>> [v for b, v in zip(index, x["Age"]) if b] [55] -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
On Fri, Sep 22, 2017 at 10:26 PM, Marko Rauhamaa wrote: > Chris Angelico : >> (Side point: Your slot_ref function is rather bizarre. It's a closure >> AND a class, just in case one of them isn't sufficient. > > I don't see anything bizarre in it at all. I use the pattern all the > time. It's called an inner class: > >In Python, it is possible to nest a class within another class, >method or function. > >https://en.wikipedia.org/wiki/Inner_class#Programming_languages> Sure you *can* do it. It's perfectly legal Python syntax. But what's the point? The class alone will do it. class slot_ref: def __init__(self, ns, key): self.ns = ns; self.key = key def get(self): return self.ns[self.key] def set(self, value): self.ns[self.key] = value That should be drop-in compatible with your original function/class hybrid, complete with following the naming convention for functions rather than classes. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert pandas series to string and datetime object
Pavol Lisy wrote: > pandas is one of reasons why python is so popular these days. But > "there is only milion way how to do it" (and other unpythonic issues) > I see there every time I am looking at it. :) Yeah, such a useful tool with such a byzantine API, completely at odds with the zen -- I wonder what prevented that the authors chose to write it in Perl ;) -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Chris Angelico : > On Fri, Sep 22, 2017 at 10:26 PM, Marko Rauhamaa wrote: >> Chris Angelico : >>> (Side point: Your slot_ref function is rather bizarre. It's a closure >>> AND a class, just in case one of them isn't sufficient. >> >> I don't see anything bizarre in it at all. > Sure you *can* do it. It's perfectly legal Python syntax. But what's > the point? The class alone will do it. > > class slot_ref: > def __init__(self, ns, key): > self.ns = ns; self.key = key > def get(self): return self.ns[self.key] > def set(self, value): self.ns[self.key] = value > > That should be drop-in compatible with your original function/class > hybrid, complete with following the naming convention for functions > rather than classes. You are right. That one would be the way to go here. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Fw: Problems Installing Python36
Op 2017-09-20, Irmen de Jong schreef : > The only thing I can think of is that it asks windows update to > install said KB update but that it depends on something else that > isn't installed or that the user running the installation doesn't have > the rights to install windows updates. (I suspect something will be > logged in the event viewer somewhere...?) Yeah, I suppose something like that. Presumably you can lock down Windows in some way that it won't install the KB, but that is clearly not the factory default. > Or that it doesn't attempt to download it at all and that we are > misinformed :P :-( > Btw, I personally never had any issues installing Python on Windows. I was vaguely tempted to offer the Mingw-w64 (GCC) Python as an alternative, since it doesn't rely on any optionally-installed Microsoft DLLs and so avoids this issue. But I suppose that is not really the newbie-friendly solution the OP was looking for... Stephan -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells at Whippersnappers
Op 2017-09-21, Thomas Jollans schreef : > On 2017-09-19 20:21, Stefan Ram wrote: >> I do not use UTF-8 >> > > Why on earth not?! Even *More* Older Man Yells at UTF-8? -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
Op 2017-09-22, Thomas Jollans schreef : > Just to make the implication explicit: > from math import nan nan is nan > True nan == nan > False nan != nan > True To add to the fun: >>> nan is nan True Stephan -- https://mail.python.org/mailman/listinfo/python-list
Issues with beginning Django use
Hello, I've been attempting to begin learning Django but have been having running Django and Python commands on windows. For example, when I run django-admin startproject mytestsite, I get the following error message django-admin : *The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,* *verify that the path is correct and try again.* *At line:1 char:1* + django-admin startproject mytestsite + + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Just curious if anyone has encountered a similar problem and can give some advice on getting moving in the right direction. Thanks a lot! -- https://mail.python.org/mailman/listinfo/python-list
Re: Issues with beginning Django use
On 22/09/2017 19:50, Joey Steward wrote: Hello, I've been attempting to begin learning Django but have been having running Django and Python commands on windows. For example, when I run django-admin startproject mytestsite, I get the following error message django-admin : *The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,* *verify that the path is correct and try again.* *At line:1 char:1* + django-admin startproject mytestsite + + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Just curious if anyone has encountered a similar problem and can give some advice on getting moving in the right direction. Thanks a lot! This is a repeat of your post of 20/9/2017. I cut and pasted your error message "django-admin : *The term 'django-admin' is not " into Google and the first hit was the fix to the problem. Pasting error messages into a Google search gives instant results. Posting to the list/newsgroup may give better, more personalised responses but you may have to wait sometime before anyone replies. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to share class relationship representations?
On 9/19/17, leam hall wrote: > I'm working on designing the classes, sub-classes, and relationships in my > code. What is a good visual way to represent it so it can be stored in git > and shared on the list without large images or attachments? > > Thanks! > > Leam https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3#29597209 there are probably more ideas useful for you. Maybe this one could be inspiring too: import networkx as nx g=nx.DiGraph() g.add_edges_from([('class 1','class 2'), ('class 1','class 3'), ('class 1','class 4'), ('class 2','class 5'), ('class 2','class 6'), ('class 2','class 7'), ('class 3','class 8'), ('class 3','class 9'), ('class 4','class 10'), ('class 5','class 11'), ('class 5','class 12'), ('class 6','class 13')]) p=nx.drawing.nx_pydot.to_pydot(g) p.write_png('example.png') And you could make function which from list of classes create list of edges! :) In git you don't need to store images just list of classes and script to make images (documentation). -- https://mail.python.org/mailman/listinfo/python-list
Re: Assertions
On Thursday, September 21, 2017 at 9:29:19 AM UTC-7, Tobiah wrote: > Are these completely equivalent? > > def foo(thing): > > assert(thing > 0), "Thing must be greater than zero" > > > def foo(thing): > > if not (thing > 0): raise AssertionError("Thing must be greater than > zero") > > > Other than the fact that the assertion can be turned off > with -O? For that reason, I would prefer to raise ValueError instead of AssertionError. The -O flag is nice for turning off test code. If the code is essential to the functionality of the program, you probably don't want to misidentify it as test code. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fw: Problems Installing Python36
On 09/22/2017 08:34 PM, Stephan Houben wrote: > I was vaguely tempted to offer the Mingw-w64 (GCC) Python as an > alternative, since it doesn't rely on any optionally-installed Microsoft > DLLs and so avoids this issue. But I suppose that is not really the > newbie-friendly solution the OP was looking for... Mingw? Perhaps better to choose Anaconda/Miniconda instead if you go for an alternative implementation... Irmen -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Mark Lawrence wrote: On 22/09/2017 08:01, Bill wrote: Steve D'Aprano wrote: On Fri, 22 Sep 2017 02:57 pm, Bill wrote: I find Python to be more more like Java, with regard to "passing objects by reference". Which is not a surprise, since both Python and Java use the same value passing style: pass by object reference, or pass by sharing if you prefer. Java people don't call it that. They call it pass by value, and categorically deny that it is pass by reference. (They're right about the second point.) I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? Please see http://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ and http://effbot.org/zone/call-by-object.htm I would would agree with the description provided for the C++ example provided string some_guy = "fred"; is replaced by char* some_guy="fred"; To see that this is correct, note the some_guy may subsequently be assigned to a character string much longer then "fred". An additional note: A character string literal, like "cat", never occurs more than once in compiled C++ program unit. This also shows that the provided description can't be completely correct. One last thing, string some_guy = "fred" is really the same thing as string some_guy("fred"); and both equivalently call the string constructor. The data type of "fred" is const char*, not (class) string. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] beginning to code
Bill wrote: Mark Lawrence wrote: On 22/09/2017 08:01, Bill wrote: Steve D'Aprano wrote: On Fri, 22 Sep 2017 02:57 pm, Bill wrote: I find Python to be more more like Java, with regard to "passing objects by reference". Which is not a surprise, since both Python and Java use the same value passing style: pass by object reference, or pass by sharing if you prefer. Java people don't call it that. They call it pass by value, and categorically deny that it is pass by reference. (They're right about the second point.) I figure that, internally, an address, a pointer, is being passed by value to implement pass by reference. Why do you say "they are right" above? Are you saying it's not pass by reference? Please see http://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ and http://effbot.org/zone/call-by-object.htm I would would agree with the description provided for the C++ example provided string some_guy = "fred"; is replaced by char* some_guy="fred"; On second thought, so that the description is correct (matches the semantics), replace it by char some_guy[10]="fred"; But then you need to use std::strcpy to reassign some_guy to "george". To see that this is correct, note the some_guy may subsequently be assigned to a character string much longer then "fred". An additional note: A character string literal, like "cat", never occurs more than once in compiled C++ program unit. This also shows that the provided description can't be completely correct. One last thing, string some_guy = "fred" is really the same thing as string some_guy("fred"); and both equivalently call the string constructor. The data type of "fred" is const char*, not (class) string. -- https://mail.python.org/mailman/listinfo/python-list
Python Boolean Logic
Hey guys, I'm testing this on CodeAcademy, but I cant get the program to output a result even after pressing the run button. Just wanted to check if my logic is correct. Thanks alot # Assign True or False as appropriate on the lines below! # (20 - 10) > 15 bool_one = False# We did this one for you! # (10 + 17) == 3**16 # Remember that ** can be read as 'to the power of'. 3**16 is about 43 million. bool_two = False # 1**2 <= -1 bool_three = False # 40 * 4 >= -4 bool_four = True # 100 != 10**2 bool_five = False -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
You have a lot of assignment statements, but nothing that produces output. Try adding statements like this at appropriate places... print ("bool_one = ", bool_one) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
Input : # Assign True or False as appropriate on the lines below! # (20 - 10) > 15 bool_one = False# We did this one for you! # (10 + 17) == 3**16 # Remember that ** can be read as 'to the power of'. 3**16 is about 43 million. bool_two = False # 1**2 <= -1 bool_three = False # 40 * 4 >= -4 bool_four = True # 100 != 10**2 bool_five = False print ("bool_one = ", bool_one) print ("bool_two = ", bool_two) print ("bool_three = ", bool_three) print ("bool_four = ", bool_four) print ("bool_five = ", bool_five) Output : ('bool_one = ', False) ('bool_two = ', False) ('bool_three = ', False) ('bool_four = ', True) ('bool_five = ', False) Is my logic / input / output correct ? Thanks a lot ... On Saturday, September 23, 2017 at 12:40:10 PM UTC+8, steve.ferg...@gmail.com wrote: > You have a lot of assignment statements, but nothing that produces output. > Try adding statements like this at appropriate places... > > print ("bool_one = ", bool_one) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
Cai Gengyang wrote: Hey guys, I'm testing this on CodeAcademy, but I cant get the program to output a result even after pressing the run button. Just wanted to check if my logic is correct. Thanks alot Your answers appear correct, but you could write Python statements to test them (or any you encounter in the future). For instance, if (20 - 10) > 15 : print("true") else: print("false"); Or, s='(20 - 10) > 15' b=(20 - 10) > 15 print(s, " is ", ("true" if b else "false") ); ## inside parentheses may be removed. I am new to Python. Maybe someone here is familiar with an elegant way to get the the value of b directly from the string s? Hmm... It appears that eval() would work (see "Python: Essential Reference", p. 115). I just read about that for the first time last night! I may try that, for practice, after I post this. Bill # Assign True or False as appropriate on the lines below! # (20 - 10) > 15 bool_one = False# We did this one for you! # (10 + 17) == 3**16 # Remember that ** can be read as 'to the power of'. 3**16 is about 43 million. bool_two = False # 1**2 <= -1 bool_three = False # 40 * 4 >= -4 bool_four = True # 100 != 10**2 bool_five = False -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
Bill wrote: Cai Gengyang wrote: Hey guys, I'm testing this on CodeAcademy, but I cant get the program to output a result even after pressing the run button. Just wanted to check if my logic is correct. Thanks alot Your answers appear correct, but you could write Python statements to test them (or any you encounter in the future). For instance, if (20 - 10) > 15 : print("true") else: print("false"); Or, s='(20 - 10) > 15' b=(20 - 10) > 15 print(s, " is ", ("true" if b else "false") ); ## inside parentheses may be removed. I am new to Python. Maybe someone here is familiar with an elegant way to get the the value of b directly from the string s? Hmm... It appears that eval() would work (see "Python: Essential Reference", p. 115). I just read about that for the first time last night! I may try that, for practice, after I post this. Update: Yes, b=(20 - 10) > 15 may be replaced by eval(s). We can write: print(s, " is ", ("true" if eval(s) else "false") ) # Assign True or False as appropriate on the lines below! # (20 - 10) > 15 bool_one = False# We did this one for you! # (10 + 17) == 3**16 # Remember that ** can be read as 'to the power of'. 3**16 is about 43 million. bool_two = False # 1**2 <= -1 bool_three = False # 40 * 4 >= -4 bool_four = True # 100 != 10**2 bool_five = False -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
On Friday, September 22, 2017 at 11:46:59 PM UTC-5, Cai Gengyang wrote: > Input : > > # Assign True or False as appropriate on the lines below! > > # (20 - 10) > 15 > bool_one = False# We did this one for you! > > # (10 + 17) == 3**16 > # Remember that ** can be read as 'to the power of'. 3**16 is about 43 > million. > bool_two = False > > # 1**2 <= -1 > bool_three = False > > # 40 * 4 >= -4 > bool_four = True > > # 100 != 10**2 > bool_five = False > > print ("bool_one = ", bool_one) > print ("bool_two = ", bool_two) > print ("bool_three = ", bool_three) > print ("bool_four = ", bool_four) > print ("bool_five = ", bool_five) > > > Output : > > ('bool_one = ', False) > ('bool_two = ', False) > ('bool_three = ', False) > ('bool_four = ', True) > ('bool_five = ', False) > > > Is my logic / input / output correct ? Thanks a lot ... This looks like homework, and not a very well designed homework either. It seems the instructor wants you to provide the value of each "rich comparison expression" by assigning a boolean to an enumerated variable. As far as your "logic and IO being correct", i don't see a request for any of those things, based on what you provided here. If you want to check the expressions, just copy/paste them into a Python console. # Python2.x (with dependancy) >>> from sanity import * >>> if isbadidea('typehints'): ... print 'Duh!' ... else: ... print 'Duh!' Duh Yep. My sanity module could have saved the BDFL a lot of headaches. And possibly his cushy job at GooglePlex... -- https://mail.python.org/mailman/listinfo/python-list
Re: Fw: Problems Installing Python36
Op 2017-09-22, Irmen de Jong schreef : > On 09/22/2017 08:34 PM, Stephan Houben wrote: > >> I was vaguely tempted to offer the Mingw-w64 (GCC) Python as an >> alternative, since it doesn't rely on any optionally-installed Microsoft >> DLLs and so avoids this issue. But I suppose that is not really the >> newbie-friendly solution the OP was looking for... > > Mingw? Perhaps better to choose Anaconda/Miniconda instead if you go for > an alternative implementation... Anaconda is still based on MSVC and so still relies on the MSVC C library. If installing the MSVC C linrary is the problem, then I don't think Anaconda solves that. Stephan -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Boolean Logic
On Sat, 23 Sep 2017 03:01 pm, Bill wrote: > s='(20 - 10) > 15' > b=(20 - 10) > 15 > print(s, " is ", ("true" if b else "false") ); ## inside parentheses > may be removed. > > I am new to Python. Maybe someone here is familiar with an elegant way > to get the the value of b directly from the string s? Hmm... It appears > that eval() would work Indeed it will, but don't get into the habit of using eval willy-nilly. While it is absolutely fine to use it with data you provide yourself, it is a HUGE security risk to eval strings that came from an untrusted user. eval("__import__('os').system('echo """rm-rf /"""')") Also, for what its worth, it's about ten times slower to run: eval('(20 - 10) > 15') than to simply run (20 - 10) > 15 -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to share class relationship representations?
Op 2017-09-22, Pavol Lisy schreef : > On 9/19/17, leam hall wrote: >> I'm working on designing the classes, sub-classes, and relationships in my >> code. What is a good visual way to represent it so it can be stored in git >> and shared on the list without large images or attachments? >> >> Thanks! >> >> Leam > > https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3#29597209 For direct inclusion in source code, what about plain text with Unicode box drawing characters? ┏━━┓ ┃object┃ ┗━━━┳━━┛ ┃ ┏━━┻━━┓ ┃float┃ ┗━┛ Stephan -- https://mail.python.org/mailman/listinfo/python-list