Re: LangWart: Method congestion from mutate multiplicty
While it is true that sorted(iterable) is essentially
def sorted(iterable):
tem = list(iterable)
tem.sort
return tem
the body is not an expression and cannot be substituted in an
expression. The need for the short form was thought common enough to be
worth, *on balance*, a new builtin name. It is not surprising that not
all agree.
Reversed(iterable) is more complicated because it returns an iterator,
not a list, and looks for a class-specific __reversed__ method. I think
it is more or less equivalent to the following:
def _rev_iter(seq, n):
for i in range(n-1, -1, -1):
# many people have trouble getting the range right
yield seq[i]
def reversed(iterable):
try:
return iterable.__reversed__()
except AttributeError:
try:
itlen = iterable.__len__
iterable.__getitem__
return _rev_iter(iterable, itlen)
except AttributeError:
raise TypeError("argument to reversed() must be a sequence")
Even if list mutation methods returned the list, which they do not and
for good reason, reversed(it) is not the same as list(it).reverse(). So
that part of the premise of this thread is wrong.
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson: The Ruby language attempted to save the programmer from the scourge of obtaining a four year degree in linguistics just to create intuitive identifiers "on-the-fly", and they tried to remove this ambiguity by employing "post-fix-punctuation" of the exclamation mark as a visual cue for in-place modification of the object: Ruby does not use '!' to indicate in-place modification: http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes ":"
On 09.02.2013 12:04, Joshua Robinson wrote:
> Hi *Monte-Pythons*,
>
> x = "this is a simple : text: that has colon"
> s = x.replace(string.punctuation, ""); OR
> s = x.replace(string.punctuation, "");
> print x # 'this is a simple : text: that has colon'
> # The colon is still in the text
>
> Is this a bug or am I doing something wrong ?
The latter. str.replace() only replaces complete substrings, not single
character occurences of the given pattern. That is
"foo".replace("foo", "bar") == "bar"
"foofoo".replace("foo", "bar") == "barbar"
"foofoo".replace("fo", "bar") == "barobaro"
"foofoo".replace("abcdef", "bar") == "foofoo"
Regards,
Johannes
--
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Neil Hodgson wrote: > Rick Johnson: > >> The Ruby language attempted to save the programmer from the scourge of >> obtaining a four year degree in linguistics just to create intuitive >> identifiers "on-the-fly", and they tried to remove this ambiguity by >> employing "post-fix-punctuation" of the exclamation mark as a visual cue >> for in-place modification of the object: > > Ruby does not use '!' to indicate in-place modification: > http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist Why am I not surprised that Rick's knowledge of Ruby is no deeper than his knowledge of Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson wrote: > On Friday, February 8, 2013 9:36:52 PM UTC-6, Steven D'Aprano wrote: >> Rick Johnson wrote: >> >> > The solution is simple. Do not offer the "copy-mutate" methods and >> > force all mutation to happen in-place: >> > >> > py> l = [1,2,3] >> > py> l.reverse >> > py> l >> > [3,2,1] >> > >> > If the user wants a "mutated copy" he should explicitly create a new >> > object and then apply the correct mutator method: >> > >> > py> a1 = [1,2,3] >> > py> a2 = list(a1).reverse() >> >> Oh wow, Rick has re-discovered programming in Python during the mid to >> late 1990s! >> >> [...snip: long-winded, rambling, and sarcastic response simply to convey >> that Python lists have had a "reversed" method for some time...] > > Steven, i am quite aware of the Python list method "reversed" --which > returns a copy of the current list object in reversed order--, And you have missed my point, which is that reversed(), and sorted(), were not added to the language on a whim, but because they were requested, over and over and over again. People who actually programmed using Python before reversed() and sorted() were added missed them, and consequently kept reimplementing them. You want to go back to the Bad Old Days when everyone was reimplementing the same few functions over and over again. I say, boo sucks to that. > my point is > that these types of "copy-mutate" methods superfluously pollute the object > namespace. Do you really want "method pairs" like these: > > sort, sorted > reverse, reversed Yes. > Hell, why stop there: > > append, appended "appended" is called list addition. newlist = oldlist + [item_to_append] > flatten, flattened flatten is another often requested, hard to implement correctly, function. The only reason that Python doesn't have a flatten is that nobody can agree on precisely what it should do. Like map, filter, reduce, etc. flatten is not sensibly implemented as a mutator method, but as a function. > insert, inserted "inserted" is called addition, together with list slicing when needed. newlist = [item_to_insert] + oldlist newlist = oldlist[0:5] + [item_to_insert] + oldlist[5:] > map, mapped > filter, filtered > reduce, reduced Those are nonsense. None of those are in-place mutator methods. Especially reduce, which reduces a list to a single item. You might as well have suggested "len, "lened". > extend, extended Again, "extended" is spelled list addition. Are you sure you've actually programmed in Python before? You seem awfully ignorant of language features. [...] > My point was this: All mutate methods should mutate "in-place", Well duh. All mutator methods do mutate in-place, otherwise they wouldn't be mutator methods. > if the > programmer wishes to create a mutated copy of the object, then the > programmer should /explicitly/ create a copy of the object and then apply > the correct mutator method to the copy. Been there, done that, it sucks. That's about a dozen steps backwards to a worse time in Python development. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
__class__ and type() implementation details in CPython
Hello. I've done the following in CPython 2.7.3 and 3.3.0 (and also in PyPy 2.0b1): >>> import weakref >>> x = set() >>> y = weakref.proxy(x) >>> x.__class__, type(x), isinstance(x, set) (, , True) >>> y.__class__, type(y), isinstance(y, set) (, , True) So, type doesn't use object's __class__ to determine its class. I'm looking for some CPyhton implementation details - how does class identification with type() work? According to CPython's sources it looks like there is a "marker" of actual object's class associated with each PyObject - _typeobject struct, which is used to identify the class by type(). Am I right? Thank you. - Ivan Yurchenko. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
Rick Johnson wrote:
> IMO "Set Types" should only exists as a concequence of "freezing" an
> array,
Sets are not frozen lists.
> and should have NO literal syntax avaiable.
Unfortunately, Python has a minor design flaw. One of the most common
use-cases for sets is for membership testing of literal sets:
def example(arg):
if arg in {'spam', 'ham', 'eggs', 'cheese'}:
...
Unfortunately, set literals create *mutable* sets, not frozensets. That
means that the compiler wastes time and memory creating am over-allocated
mutable set object. If set literals created immutable frozensets, there
would be some nice opportunities for the compiler to optimize this
use-case.
So, in Python 4000, my vote is for set literals { } to create frozensets,
and if you want a mutable set, you have to use the set() type directly.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, Feb 10, 2013 at 10:29 PM, Steven D'Aprano wrote: > "inserted" is called addition, together with list slicing when needed. > > newlist = [item_to_insert] + oldlist > newlist = oldlist[0:5] + [item_to_insert] + oldlist[5:] Really? Wouldn't it be easier to use slice assignment on a copy? newlist = oldlist[:]; newlist[pos:pos] = [item_to_insert] Actually, come to think of it, that scores about the same on readability. Six of one, half dozen of the other. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On 10 February 2013 04:53, Mark Janssen wrote: > On Sat, Feb 9, 2013 at 8:20 PM, Chris Angelico wrote: >> On Sun, Feb 10, 2013 at 2:54 PM, Rick Johnson >> wrote: >>> My point was this: All mutate methods should mutate "in-place", if the >>> programmer wishes to create a mutated copy of the object, then the >>> programmer should /explicitly/ create a copy of the object and then apply >>> the correct mutator method to the copy. >> >> I agree. And we can go further and declare that there is only one data >> [sarcasm] > > I have to agree with Rick, I think requiring the user to explicitly > create a new object, which is already a good and widely-used practice, > should be the Only One Way to Do It. Why should I copy a potentially large data structure just to iterate over it in reverse order? And why on earth would you want to remove the more efficient ways of doing this? > Guessing method names is far suboptimal to this simple, easy idiom. There is no guessing. If the object has a __reverse__ method then it specifically advertises that it knows how to create an iterator that gives its values in reverse order. Otherwise __len__ and __getitem__ are used. Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, 10 Feb 2013 22:29:54 +1100, Steven D'Aprano wrote: > Rick Johnson wrote: > > map, mapped > > filter, filtered > > reduce, reduced > > Those are nonsense. None of those are in-place mutator methods. > Especially reduce, which reduces a list to a single item. You might > as well have suggested "len, "lened". And, if you want those in-place, indexing trivially comes to the rescue again: lst[:] = map(transform_fn, lst) lst[:] = filter(check_fn, lst) or, as I prefer: lst[:] = [transform_fn(x) for x in lst] lst[:] = [x for x in lst if check_fn(x)] as they can be combined simply. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: __class__ and type() implementation details in CPython
Ivan Yurchenko wrote: > Hello. > > I've done the following in CPython 2.7.3 and 3.3.0 (and also in PyPy > 2.0b1): > import weakref x = set() y = weakref.proxy(x) x.__class__, type(x), isinstance(x, set) > (, , True) y.__class__, type(y), isinstance(y, set) > (, , True) > > So, type doesn't use object's __class__ to determine its class. Sometimes it does: py> class X(object): pass ... py> class Y(object): pass ... py> x = X() py> x <__main__.X object at 0xb7c9adac> py> x.__class__ = Y py> x <__main__.Y object at 0xb7c9adac> py> type(x) I believe that it depends on whether the instance being inspected is a heap-type (e.g. pure-Python object) or not. > I'm > looking for some CPyhton implementation details - how does class > identification with type() work? According to CPython's sources it looks > like there is a "marker" of actual object's class associated with each > PyObject - _typeobject struct, which is used to identify the class by > type(). Am I right? I'm not an expert on the CPython implementation, but I believe the code you want is buried somewhere in here: http://hg.python.org/cpython/file/tip/Objects/typeobject.c -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Chris Angelico wrote: > On Sun, Feb 10, 2013 at 10:29 PM, Steven D'Aprano > wrote: >> "inserted" is called addition, together with list slicing when needed. >> >> newlist = [item_to_insert] + oldlist >> newlist = oldlist[0:5] + [item_to_insert] + oldlist[5:] > > Really? Wouldn't it be easier to use slice assignment on a copy? > > newlist = oldlist[:]; newlist[pos:pos] = [item_to_insert] I don't know about "easier", but it's two statements rather than a single expression, which means you cannot easily include it as part of a larger expression. > Actually, come to think of it, that scores about the same on > readability. Six of one, half dozen of the other. Pretty much. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Mark Janssen wrote:
> On Sat, Feb 9, 2013 at 8:20 PM, Chris Angelico wrote:
>> On Sun, Feb 10, 2013 at 2:54 PM, Rick Johnson
>> wrote:
>>> My point was this: All mutate methods should mutate "in-place", if the
>>> programmer wishes to create a mutated copy of the object, then the
>>> programmer should /explicitly/ create a copy of the object and then
>>> apply the correct mutator method to the copy.
>>
>> I agree. And we can go further and declare that there is only one data
>> [sarcasm]
>
> I have to agree with Rick, I think requiring the user to explicitly
> create a new object, which is already a good and widely-used practice,
Perhaps so, but consider how you creates new objects in Python. Very rarely
do you do so with an explicit call to the constructor. For example:
n = 5 # Yes.
# or
n = int("5") # No.
alist = some_list[1:] # Yes.
# or
alist = list()
alist.extend(some_list[1:]) # No.
items = sorted(other_things + [1]) # Yes.
# or
items = other_things[:]
items.append(1)
items.sort() # Hell no.
There are many functions or methods that create new objects, apart from the
constructor. A call like:
blist = sorted(alist)
is no less explicitly creating a new list than:
blist = list(alist)
> should be the Only One Way to Do It.
Pardon me, but you've been listening to too many Perl developers. "Only One
Way To Do It" is not, and never has been, the motto of Python. You may be
thinking of the line from the Zen of Python:
py> import this
[...]
There should be one-- and preferably only one --obvious way to do it.
The emphasis is on the *obvious*, not the "only". There is an enormous
difference between prohibiting a second way to solve problems ("Only One
Way") and recommending that there should be an Obvious Way.
> Guessing method names is far
> suboptimal to this simple, easy idiom. As for the point Chris was
> making as to making all types one, I actually agree there too,
Oh dear. Chris was being sarcastic. I thought that, even if the sarcasm
wasn't obvious, his "Ook. Ook!" at the end should have given it away:
http://www.dangermouse.net/esoteric/ook.html
> it's
> just that in order to do that, python would need a unified object
> model and it doesn't have one yet.
I'm not sure what you mean by "unified object model", but I'm pretty sure
that Python has one. Everything is an object, with a single[1] hierarchy of
classes.
[1] Python 3 only. In Python 2, you have types, and you have old-style
classes, and they are separate.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Steven D'Aprano於 2013年2月9日星期六UTC+8上午11時36分52秒寫道: > Rick Johnson wrote: > > > > > The solution is simple. Do not offer the "copy-mutate" methods and force > > > all mutation to happen in-place: > > > > > > py> l = [1,2,3] > > > py> l.reverse > > > py> l > > > [3,2,1] > > > > > > If the user wants a "mutated copy" he should explicitly create a new > > > object and then apply the correct mutator method: > > > > > > py> a1 = [1,2,3] > > > py> a2 = list(a1).reverse() > > > > > > Oh wow, Rick has re-discovered programming in Python during the mid to late > > 1990s! > > > > I was there, and I remember what it was like. For about a month, you try > > hard to follow Rick's prescription. Then you realise that with a small > > helper function, you can halve the amount of code it takes to do a common > > operation: > > > > def reversed(sequence): > > seq = list(sequence) > > seq.reverse() > > return seq > > > > > > Soon you've copied this reversed() function into all your projects. And of > > course, they start to diverge... in project A, you only care about lists. > > In project B, you realise that you also need to support tuples and strings: > > > > > > def reversed(sequence): > > seq = sequence[:] > > try: > > seq.reverse() > > except AttributeError: > > seq = seq[::-1] > > return seq > > Will a temprary new list be formed here? If it is not necessary, I'll prefer a reverse generator for all lists to save the heap space and the GC burden. > > which in project C you realise can be shortened: > > > > def reversed(sequence): > > return sequence[::-1] > > > > > > until you get to project D when you realise that you also want this to work > > on dicts: > > > > def reversed(sequence): > > everything = list(sequence) > > return everything[::-1] > > > > > > and then in project E you wonder why reversed(string) returns a list: > > > > def reversed(sequence): > > everything = list(sequence)[::-1] > > if isinstance(sequence, tuple): > > return tuple(everything) > > elif isinstance(sequence, str): > > return ''.join(everything) > > return everything > > > > > > and then finally you learn about iterators and generators and become more > > comfortable with a flow-based programming paradigm and generators: > > > > def reversed(sequence): > > for item in list(sequence)[::-1]: > > yield item > > > > at which point you realise that, hell, this is so useful that pretty much > > everyone has implemented it a dozen times or more in their own projects, > > and you start to agitate for it to be added to the builtins so that there > > is *one* implementation, done *right*, that everyone can use. > > > > And then you get told that Guido's time machine has struck again, because > > Python has already had this since Python 2.4. > > > > > > > > -- > > Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
In article <[email protected]>, Steven D'Aprano wrote: > Sets are not frozen lists. Right. Tuples are frozen lists (ducking and running). -- http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Hi, Thanks for your suggestion. This is a great forum for Python. :) On Sun, Feb 10, 2013 at 4:12 PM, inq1ltd wrote: > ** > > On Saturday, February 09, 2013 03:27:16 PM Morten Engvoldsen wrote: > > > Hi Team, > > > I Have saved my output in .doc file and want to format the output with > > > > > > *Start the File > > > > > > Some data here > > > > > > > > > ***End of File* > > > > > > Can you let me know how can i do that using Python? > > > > > > Look up the textwrap module > > > > import the textwrap module. > > > > from the textwrap module you can > > import dedent, wrap, and fill > > > > These are great for formatting text. > > > > jd > > inqvista.com > > > > > > > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
On Saturday, February 09, 2013 03:27:16 PM Morten Engvoldsen wrote: > Hi Team, > I Have saved my output in .doc file and want to format the output with > > *Start the File > > Some data here > > > ***End of File* > > Can you let me know how can i do that using Python? Look up the textwrap module import the textwrap module. from the textwrap module you can import dedent, wrap, and fill These are great for formatting text. jd inqvista.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Hi Dave,
This is good code, simple but makes the Coding Standard better.. Thanks to
all again
On Sun, Feb 10, 2013 at 5:01 PM, David Hutto wrote:
> Kind of like below:
>
> david@david-HP-Compaq-dc7600-Convertible-Minitower:~$ python
> Python 2.7.3 (default, Aug 1 2012, 05:16:07)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> f = open("/home/david/file_doc.doc",'a')
> >>> text = "data here"
> >>> f.write("***Start File***\n%s\n***End File***\n" % text)
> >>> f.close()
> >>>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
I haven't looked at text wrapper, but it would probably look
something like this in a function, untested:
def text_wrapper(file_name = None, pre_text = None, text = None,
post_text = None):
f = open(file, 'a')
f.write("%s\n%s\n%s\n" % (pre_text = None, text, post_text = None)
f.close()
--
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Oops, I mean :
def text_wrapper(file_name = None, pre_text = None, text = None,
post_text = None):
f = open(file, 'a')
f.write("%s\n%s\n%s\n" % (pre_text, text, post_text)
f.close()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Hi Dave,
Thanks again for suggestion
On Sun, Feb 10, 2013 at 5:30 PM, David Hutto wrote:
> I haven't looked at text wrapper, but it would probably look
> something like this in a function, untested:
>
> def text_wrapper(file_name = None, pre_text = None, text = None,
> post_text = None):
> f = open(file, 'a')
> f.write("%s\n%s\n%s\n" % (pre_text = None, text, post_text = None)
> f.close()
>
>
> --
> Best Regards,
> David Hutto
> CEO: http://www.hitwebdevelopment.com
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Here is the full function with an instance using the function:
def text_wrapper(file_name = None, pre_text = None, text = None,
post_text = None):
f = open(file_name, 'a')
f.write("%s\n%s\n%s\n" % (pre_text, text, post_text))
f.close()
text_wrapper(file_name = r"/home/david/file_doc.doc", pre_text =
"***Start File***", text = "Some data here.", post_text = "***End
File***")
--
http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
On Sun, Feb 10, 2013 at 11:45 AM, Morten Engvoldsen wrote: > Hi Dave, > Thanks again for suggestion No problem. I haven't used my python skills in a while, so I went ahead and went through it fully. -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Any idea how i can format my output file with ********************Start file*********************** usinf Python 2.7
Hi Dave,
Thanks for your reply with full function :) Great forum.. :)
On Sun, Feb 10, 2013 at 5:46 PM, David Hutto wrote:
> Here is the full function with an instance using the function:
>
> def text_wrapper(file_name = None, pre_text = None, text = None,
> post_text = None):
> f = open(file_name, 'a')
> f.write("%s\n%s\n%s\n" % (pre_text, text, post_text))
> f.close()
>
>
> text_wrapper(file_name = r"/home/david/file_doc.doc", pre_text =
> "***Start File***", text = "Some data here.", post_text = "***End
> File***")
>
--
http://mail.python.org/mailman/listinfo/python-list
Pick random choice from variables
How do i make something with python that will ask the user for input, and then use the random.choice function to select a random choice from what the user entered. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
Am 10.02.2013 12:37 schrieb Steven D'Aprano:
So, in Python 4000, my vote is for set literals { } to create frozensets,
and if you want a mutable set, you have to use the set() type directly.
4000 sounds about long future.
In the meanwhile, a new syntax element could be introduced fpr
frozensets, such as {{ }} or something. (Although that might clutter
with a set containing a set.)
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
Statistics...help with numpy/scipy install
I'm new to Python with a new windows 8 machine (64-bit OS). Learning programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't want the latest and greatest). What I want involves functions related to the normal distribution. Based on my google research, it appears that SCIPY is a good way to go. That requires NUMPY. I don't seem to find an install that works for my environment which leads to the questions on this post: Is there an install for my environment and if so, where do I get it? If not, is there another package I should use? Or do I need to bite the bullet and install an earlier version of Python. Suggestions and comments appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pick random choice from variables
On Sun, Feb 10, 2013 at 12:43 PM, Joel Goldstick
wrote:
>
>
>
> On Sun, Feb 10, 2013 at 12:01 PM, eli m wrote:
>>
>> How do i make something with python that will ask the user for input, and
>> then use the random.choice function to select a random choice from what the
>> user entered.
Below is a snippet example:
import random as rand
selection_enter = raw_input("Enter Selection List of Three Items
Seperated By Commas: ")
selection_list = selection_enter.split(",")
print selection_list
rand_choice = rand.choice(selection_list)
print rand_choice
--
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pick random choice from variables
The first one I sent directly to you, but it used randint with a list. The second should be what you're looking for. If not, then ask a little further what you need explained. -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 10/02/2013 17:35, Rex Macey wrote: I'm new to Python with a new windows 8 machine (64-bit OS). Learning programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't want the latest and greatest). What I want involves functions related to the normal distribution. Based on my google research, it appears that SCIPY is a good way to go. That requires NUMPY. I don't seem to find an install that works for my environment which leads to the questions on this post: Is there an install for my environment and if so, where do I get it? If not, is there another package I should use? Or do I need to bite the bullet and install an earlier version of Python. Suggestions and comments appreciated. Thanks. So what exactly went wrong when you tried to install this http://sourceforge.net/projects/numpy/files/NumPy/1.7.0/ using commands that you haven't given us and got error messages that you also haven't given us? -- Cheers. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 02/10/2013 10:35 AM, Rex Macey wrote: > I'm new to Python with a new windows 8 machine (64-bit OS). Learning > programming mainly for fun. Naturally I downloaded Python 3.3 (who > doesn't want the latest and greatest). What I want involves > functions related to the normal distribution. Based on my google > research, it appears that SCIPY is a good way to go. That requires > NUMPY. I don't seem to find an install that works for my > environment which leads to the questions on this post: Is there an > install for my environment and if so, where do I get it? If not, is > there another package I should use? Or do I need to bite the bullet > and install an earlier version of Python. Suggestions and comments > appreciated. Thanks. A casual google search seems to indicate that for now, SciPy and NumPy are for Python 2.x (2.7 is the latest). I could be wrong though and often am. I know a number of popular and useful packages are not yet available on Python 3. If you need to do a lot math stuff, there's a complete python system that bundles a lot of these tools together into a nice package. It's called Sage. http://www.sagemath.org/ There are several non-python packages out there that are really handy as well: - R - if you need to do statistics. http://www.r-project.org/ - Octave - a matlab-compatible language. http://www.gnu.org/software/octave/ - SciLab - a math package that has a nice gui. http://www.scilab.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 10/02/2013 12:35 PM, Rex Macey wrote: I'm new to Python with a new windows 8 machine (64-bit OS). Learning programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't want the latest and greatest). What I want involves functions related to the normal distribution. Based on my google research, it appears that SCIPY is a good way to go. That requires NUMPY. I don't seem to find an install that works for my environment which leads to the questions on this post: Is there an install for my environment and if so, where do I get it? If not, is there another package I should use? Or do I need to bite the bullet and install an earlier version of Python. Suggestions and comments appreciated. Thanks. Rex, A good start for supplementary packages is PyPi, see: http://en.wikipedia.org/wiki/Python_Package_Index The packages in PyPi can be downloaded using easy-install, see: http://en.wikipedia.org/wiki/EasyInstall Yes, the Enthught Numpy is a good starting point. Good luck and have fun, Colin W -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, Feb 10, 2013 at 5:30 AM, Oscar Benjamin wrote: > On 10 February 2013 04:53, Mark Janssen wrote: >> I have to agree with Rick, I think requiring the user to explicitly >> create a new object, which is already a good and widely-used practice, >> should be the Only One Way to Do It. > > Why should I copy a potentially large data structure just to iterate > over it in reverse order? And why on earth would you want to remove > the more efficient ways of doing this? You're right. I responded too fast. I think reversed() and sorted() might be the only legit methods in this regard and I thank Steve D'Aprano for pointing that out. But Rick still has a valid point: it should not be taken as a general practice. The point, as I see it, is that there's no clear, documented standard on the "right way" for people to think about the issue. The existence of sorted() and reversed() actually *misinform* programmers as if this is the best practice. It isn't, it just that these are very special cases (one for a real machine efficiency and one for a very common "user efficiency") and there should probably be documentation to make that clear, so programmers don't start going that direction. I don't think there are other cases where such an idiom would be recommended. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sunday, February 10, 2013 2:39:21 AM UTC-6, Terry Reedy wrote: > While it is true that sorted(iterable) is essentially > > def sorted(iterable): >tem = list(iterable) >tem.sort >return tem > > the body is not an expression and cannot be substituted in an > expression. Yes but the body can be compressed to this single line: "list(iterable).sort()" > Reversed(iterable) is more complicated because it returns an iterator, > not a list, and looks for a class-specific __reversed__ method. > [...] Well if you're taking the position that iterators are difficult to create i say you are exaggerating a bit. Using the for loop: py> for LOCALVAR in SEQUENCE: ... do_something we can get the iterator for free. If however you want to control the iteration /without/ being locked into a loop, you can explicitly call: py> iter(seq) Or, if you prefer methods over global functions: py> seq.__iter__() Or, if python employed /true/ OOP paradigm: py> Iterator(seq) > Even if list mutation methods returned the list, which they do not and > for good reason, I am not proposing that in-place modification return the object. > reversed(it) is not the same as list(it).reverse(). So > that part of the premise of this thread is wrong. Well, it's not the same /now/, because of how Python handles this operation. The status quo is to encourage the implicit idiom over the explicit, however, this behavior could be optimized to cleanly handle /explicit/ syntax only. -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sunday, February 10, 2013 3:53:57 AM UTC-6, Neil Hodgson wrote: > Ruby does not use '!' to indicate in-place modification: Really? rb> a = [1,2,3] [1, 2, 3] rb> a.reverse [3, 2, 1] rb> a [1, 2, 3] rb> a.reverse! [3, 2, 1] rb> a [3, 2, 1] And now we will verify that a.reverse! has not assigned 'a' to a new object rb> a = [1,2,3] [1, 2, 3] rb> aID = a.object_id 78906770 rb> a.reverse! [3, 2, 1] rb> a [3, 2, 1] rb> a.object_id 78906770 I'd love to hear an explanation for that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On Sun, Feb 10, 2013 at 1:14 PM, Michael Torrie wrote: > On 02/10/2013 10:35 AM, Rex Macey wrote: > A casual google search seems to indicate that for now, SciPy and NumPy > are for Python 2.x (2.7 is the latest). I could be wrong though and > often am. I know a number of popular and useful packages are not yet > available on Python 3. My casual google search finds www.numpy.org as the first entry. Clicking on the download link, one can find numpy 1.7.0 for Python 3.3 In all fairness, this was just released a few hours and is the first official version supporting 3.3 However, numpy 1.6.2 did support 3.2 There's not yet a Scipy release supporting 3.3 so the OP may wish to downgrade to Python3.2 > > If you need to do a lot math stuff, there's a complete python system > that bundles a lot of these tools together into a nice package. It's > called Sage. http://www.sagemath.org/ Sage doesn't run natively on Windows. Not necessarily a problem but should be mentioned. -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 10 February 2013 18:14, Michael Torrie wrote: > On 02/10/2013 10:35 AM, Rex Macey wrote: >> I'm new to Python with a new windows 8 machine (64-bit OS). Learning >> programming mainly for fun. Naturally I downloaded Python 3.3 (who >> doesn't want the latest and greatest). What I want involves >> functions related to the normal distribution. What functions did you want? The math module contains the error function erf() and the random module can generate normally distributed pseudo-random numbers, e.g.: >>> import math >>> from math import erf >>> erf(0.0) 0.0 >>> erf(1.0) 0.842700792949715 >>> from random import normalvariate >>> normalvariate(0.0, 1.0) -0.2793532098124607 >> Based on my google >> research, it appears that SCIPY is a good way to go. That requires >> NUMPY. I don't seem to find an install that works for my >> environment which leads to the questions on this post: Is there an >> install for my environment and if so, where do I get it? There should be. Why doesn't it work? >> If not, is >> there another package I should use? Or do I need to bite the bullet >> and install an earlier version of Python. Suggestions and comments >> appreciated. Thanks. > > A casual google search seems to indicate that for now, SciPy and NumPy > are for Python 2.x (2.7 is the latest). I could be wrong though and > often am. I know a number of popular and useful packages are not yet > available on Python 3. numpy and scipy are both available for Python 3. They have been for some time and, on Ubuntu, can be installed from the OS repositories. For Windows the OP should use the sourceforge download page. Oscar -- http://mail.python.org/mailman/listinfo/python-list
matplotlib: Help! I need to plot colored regions based on a set of boundaries
I am attempting to plot the relative sky positions of several Astronomy images I'm studying. I want a set of axes that represent a 2-d projection of the sky (don't want to use polar projection), so my x-axis would be from 0 to 360 (right ascension) and the y-axis from about -35 to 90 (declination). I have the RA and Dec of the edges of each of my images and I want to plot the "image" as a colored rectangle, to-scale on my axes. How do I give matplotlib instructions to color-in a region of my plot based on the edges of that region? Thank you for any help you can provide. -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, Feb 10, 2013 at 6:29 AM, Steven D'Aprano
wrote:
> Mark Janssen wrote:
>> I have to agree with Rick, I think requiring the user to explicitly
>> create a new object, which is already a good and widely-used practice,
>
> Perhaps so, but consider how you creates new objects in Python. Very rarely
> do you do so with an explicit call to the constructor. For example:
>
> n = 5 # Yes.
> # or
> n = int("5") # No.
Good, alright, this is the point where the concept of a unified object
model comes into play. (Actually, I'm going to say "unified data
model" (or UDM) from now on so as to avoid the confusion that you
point out below that Python seems to already have a "unified object
model" because everything derives from "Object". The point is
actually rather subtle.)
A unified data model as I define it, specifies a canonical atomic unit
(like the unit integer) and an abstract grouping construct in which
these atomic units can be arranged. By themselves, these two can
construct arbitrary levels of data structure complexity. Add the
ability to apply names to these levels, and you have a complete data
model for a happy programming environment. My work, to give you some
context, involves the invention of a "fractal graph" which is where
the name "unified object model" came from, because a fractal graph, I
argue can represent every part of the physical world at every scale.
(Note that everything in a computer is series of these "atomic" bits
organized by the machine into "words" (merely for sake of the
efficiency that such parallelization affords), yet we have these
human-language constructs such as lists and sets (or records, files,
arrays, etc) where *no such things exist in the computer*. Hence,
the usefulness of considering a unified data model as part of the
computer *science*.)
In your example above, you can verify, for example, that the identity
of 5 and int("5") is the same -- even though you're using a
constructor syntax, you're not *constructing* anything at all, which
you may know already (somewhere in the Python docs, Guido points out
that Python pre-constructs the first 100 or so integers as I recall.)
There is, in addition, an implicit constructor for integers, such that
saying 656565 in python will actually construct the integer as if you
said "int("656565")".
In any case, one never operates or concerns oneself with copies of
atomic elements because they are all the same. It's a subtle
meta-philosophical(?) point, not that different that that which occurs
in the science of physics regarding electrons and protons ("Is there
only one electron?":
http://en.wikipedia.org/wiki/One-electron_universe).
> py> import this
> [...]
> There should be one-- and preferably only one --obvious way to do it.
Yes, that is the reference.
>> Guessing method names is far
>> suboptimal to this simple, easy idiom. As for the point Chris was
>> making as to making all types one, I actually agree there too,
>
> Oh dear. Chris was being sarcastic. I thought that, even if the sarcasm
> wasn't obvious, his "Ook. Ook!" at the end should have given it away:
Yes, I was aware of his sarcasm. But I was actually wanting to agree
with the fundamental idea: that one could reduce all data types to 1
atomic unit and 1 grouping construct, and like set theory in
mathematics, derive everything else.
>> it's
>> just that in order to do that, python would need a unified object
>> model and it doesn't have one yet.
>
> I'm not sure what you mean by "unified object model", but I'm pretty sure
> that Python has one. Everything is an object, with a single[1] hierarchy of
> classes.
Hopefully the elucidation above clears up some of that confusion.
Mark
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On 2/10/2013 1:45 PM, Rick Johnson wrote: On Sunday, February 10, 2013 2:39:21 AM UTC-6, Terry Reedy wrote: While it is true that sorted(iterable) is essentially def sorted(iterable): tem = list(iterable) tem.sort return tem the body is not an expression and cannot be substituted in an expression. Yes but the body can be compressed to this single line: "list(iterable).sort()" That single line now evaluates to None, so that does not work. Even if list mutation methods returned the list, which they do not and for good reason, I am not proposing that in-place modification return the object. It seems to me that you are, as that is the only way for 'list(iterable).sort()' to replace 'sorted(iterable)', as you proposed both originally and above. The reason sorted(iterable) was added is 'list(iterable).sort()', which newbies would try, *does not work*. Sorted was added so people would not have to write tem = list(iterable) tem.sort() del tem as they did previously, and instead could write Reversed was added not only for the same reason, but also to avoid the temporary list altogether when not actually needed, which it often or usually is not. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Mon, Feb 11, 2013 at 8:28 AM, Mark Janssen wrote: > Yes, I was aware of his sarcasm. But I was actually wanting to agree > with the fundamental idea: that one could reduce all data types to 1 > atomic unit and 1 grouping construct, and like set theory in > mathematics, derive everything else. There are many things that work fine in theory, but aren't practical. You could theoretically rewrite any Python program in Ook (or its non-G-rated cousin), but that doesn't mean that Ook's data model is worth working with. You could write a Python-to-Ook compiler, perhaps, for what that's worth. Proving these things possible may be of curiosity value, but I wouldn't want to actually _work with_ such a system. A while ago I put together a language concep[1]t that, similarly, started with nothing and let the programmer build from there. It quickly proved to have one massive fundamental flaw: that two programs, ostensibly written in the same language, could be utterly and completely different. It'd be like treating Python and bash scripts as the same language, given that the shebang at the top makes them both execute just fine. If you reduce everything to nothing, you (1) force the programmer to do a lot of unnecessary work, and (2) allow two different programmers to do that work subtly differently and thus create incompatible programs. (Python already has a little of this, in that Py2 and Py3 files aren't guaranteed compatible; but imagine if every source file were different.) [1] Posted here if you care. http://rosuav.com/1/?id=683 ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson: Really? Yes. >> a = [1,2] => [1, 2] >> a.push(3) => [1, 2, 3] >> a => [1, 2, 3] This could be called "mutation without exclamation". >> require 'WEBrick' => true >> vowels = "[aeiou]+" => "[aeiou]+" >> vowels.object_id => 2234951380 >> WEBrick::HTTPUtils._make_regex!(vowels) => /([^\[aeiou\]\+])/n >> vowels => "[aeiou]+" >> vowels.object_id => 2234951380 The counterpart, exclamation without mutation. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, Feb 10, 2013 at 1:51 PM, Chris Angelico wrote: > On Mon, Feb 11, 2013 at 8:28 AM, Mark Janssen > wrote: >> Yes, I was aware of his sarcasm. But I was actually wanting to agree >> with the fundamental idea: that one could reduce all data types to 1 >> atomic unit and 1 grouping construct, and like set theory in >> mathematics, derive everything else. > > There are many things that work fine in theory, but aren't practical. > You could theoretically rewrite any Python program in Ook (or its > non-G-rated cousin), but that doesn't mean that Ook's data model is > worth working with. Ah, but you're conflating a *data model* (which is already composed of simple theoretical elements (like 1/0)) and a *programming language*, which is composed of either an implicit or explicit data model (usually the former) AND a set of transforms that operate on it. IOW, I'm wanting to take something that is usually just inherited and historical (and thereby taken for granted), and make it something to look at. Traditional Data Structures in CompSci goes somewhat towards this end, but doesn't quite take the idea to its ultimate, and that's what I'm proposing with a unified data model. mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3 curses behavior
суббота, 9 февраля 2013 г., 23:22:47 UTC+4 пользователь Terry Reedy написал: > On 2/9/2013 6:23 AM, Vlasov Vitaly wrote: > > > Hello. > > > > > > I found strange behavior of curses module, that i can't understand. I > > > initialize screen with curses.initscr(), then i create subwin of > > > screen with screen.subwin(my_subwin_sizes). After that i fill subwin > > > with my_char in for-loop. On last char in last line subwin.addch() > > > raises exception. > > > > I have never used curses but I have used text screens. I suspect that > > addch moves the cursor to the position beyond where the character is > > added, but there is no such position. I remember having problems writing > > to the last char of a 24x80 screen without getting either a scroll or > > beep if scrolling was disabled. > > > > > This is my problem. Why? How to fix it? > > > > Perhaps this will help: > > window.leaveok(yes) > > If yes is 1, cursor is left where it is on update, instead of being at > > “cursor position.” This reduces cursor movement where possible. If > > possible the cursor will be made invisible. > > > > > (If i will ignore exception, then last char will be displayed) > > > > Otherwise, just catch the exception, as you already discovered. > > > > > Here simple example: http://pastebin.com/SjyMsHZB > > > > -- > > Terry Jan Reedy Thank you. I tried everything in my test script. win.leaveok() - no effect curses.cur_vis() - no effect win.scrollok() - start newline and place cursor on it It's only one last option: on last line last char try/except with pass. -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
The setup of numpy-1.7.0 leads to a Setup window with a message: "Python 3.3 is required for this package. Select installation to use:". Below that is an empty list box. Below that is an edit box for the Python Directory. I have Python 3.3 installed on c:\Python33. On Sunday, February 10, 2013 1:10:32 PM UTC-5, Mark Lawrence wrote: > On 10/02/2013 17:35, Rex Macey wrote: > > > I'm new to Python with a new windows 8 machine (64-bit OS). Learning > > programming mainly for fun. Naturally I downloaded Python 3.3 (who doesn't > > want the latest and greatest). What I want involves functions related to > > the normal distribution. Based on my google research, it appears that SCIPY > > is a good way to go. That requires NUMPY. I don't seem to find an install > > that works for my environment which leads to the questions on this post: Is > > there an install for my environment and if so, where do I get it? If not, > > is there another package I should use? Or do I need to bite the bullet and > > install an earlier version of Python. Suggestions and comments > > appreciated. Thanks. > > > > > > > So what exactly went wrong when you tried to install this > > http://sourceforge.net/projects/numpy/files/NumPy/1.7.0/ using commands > > that you haven't given us and got error messages that you also haven't > > given us? > > > > -- > > Cheers. > > > > Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
I should have added that the setup gives an error window "Cannot install" "Python version 3.3 required, which was not found in the registry." On Sunday, February 10, 2013 5:11:20 PM UTC-5, Rex Macey wrote: > The setup of numpy-1.7.0 leads to a Setup window with a message: "Python 3.3 > is required for this package. Select installation to use:". Below that is an > empty list box. Below that is an edit box for the Python Directory. > > > > I have Python 3.3 installed on c:\Python33. > > > > On Sunday, February 10, 2013 1:10:32 PM UTC-5, Mark Lawrence wrote: > > > On 10/02/2013 17:35, Rex Macey wrote: > > > > > > > I'm new to Python with a new windows 8 machine (64-bit OS). Learning > > > programming mainly for fun. Naturally I downloaded Python 3.3 (who > > > doesn't want the latest and greatest). What I want involves functions > > > related to the normal distribution. Based on my google research, it > > > appears that SCIPY is a good way to go. That requires NUMPY. I don't > > > seem to find an install that works for my environment which leads to the > > > questions on this post: Is there an install for my environment and if so, > > > where do I get it? If not, is there another package I should use? Or do I > > > need to bite the bullet and install an earlier version of Python. > > > Suggestions and comments appreciated. Thanks. > > > > > > > > > > > > > > > > > > > So what exactly went wrong when you tried to install this > > > > > > http://sourceforge.net/projects/numpy/files/NumPy/1.7.0/ using commands > > > > > > that you haven't given us and got error messages that you also haven't > > > > > > given us? > > > > > > > > > > > > -- > > > > > > Cheers. > > > > > > > > > > > > Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Multiple ways to access attributes
Is it considered acceptable practice (e.g. not confusing, not surprising or not Pythonic) to allow multiple ways to access the same attributes? For example, supposing I am providing access to external devices, that these parameters may vary slightly between devices (e.g. different models, etc...) and that the device may be queried for parameter meta-data (such as name, data type, data value constraints), would the following API be acceptable (in the sense alluded to above)? Or would it be generally considered a distortion of Python idealogy (e.g. like PERL's 'more than one way to do it' approach)? class option -> represents a single option -> two attributes: info (the parameter meta-data) value (the parameter getsetter) class options: -> represents the device parameter interface -> provides the following API: iter(options) -> iterable through all parameter meta-data options[0] -> access parameter 0 meta-data -> key is integer options['foo'] -> access parameter 'foo' (returns an 'option' object) -> key is basestring -> useful when processing the parameters generically options.foo -> same as options['foo'] -> useful for well-known, often used parameters (really just short-hand for the user) options.keys() -> iterator through option names (a specific meta-data field) options.values() -> iterator through option values options.items() -> iterator through (name,value) tuples -- isedev -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple ways to access attributes
On 2013-02-10 22:44, ISE Development wrote: Is it considered acceptable practice (e.g. not confusing, not surprising or not Pythonic) to allow multiple ways to access the same attributes? For example, supposing I am providing access to external devices, that these parameters may vary slightly between devices (e.g. different models, etc...) and that the device may be queried for parameter meta-data (such as name, data type, data value constraints), would the following API be acceptable (in the sense alluded to above)? Or would it be generally considered a distortion of Python idealogy (e.g. like PERL's 'more than one way to do it' approach)? class option -> represents a single option -> two attributes: info (the parameter meta-data) value (the parameter getsetter) class options: -> represents the device parameter interface -> provides the following API: iter(options) -> iterable through all parameter meta-data options[0] -> access parameter 0 meta-data -> key is integer options['foo'] -> access parameter 'foo' (returns an 'option' object) -> key is basestring -> useful when processing the parameters generically options.foo -> same as options['foo'] -> useful for well-known, often used parameters (really just short-hand for the user) options.keys() -> iterator through option names (a specific meta-data field) options.values() -> iterator through option values options.items() -> iterator through (name,value) tuples These features make it look like a dict: options['foo'], options.keys(), options.values(), options.items(). OK so far. What does iter(options) yield? If the class looks like a dict, it should probably behave like a dict, yielding the keys. I'm not sure about options[0]. Would that be the same as list(options.values())[0]? A dict would treat that in the same way as options['foo'] i.e. the 0 is a key. -1 for that. options.foo is a 'magic' attribute; it may or may not exist. -1 for that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple ways to access attributes
On 02/10/2013 05:44 PM, ISE Development wrote: Is it considered acceptable practice (e.g. not confusing, not > surprising or not Pythonic) to allow multiple ways to access > the same attributes? > > For example, supposing I am providing access to external > devices, that these parameters may vary slightly between > devices (e.g. different models, etc...) and that the device > may be queried for parameter meta-data (such as name, data > type, data value constraints), would the following API be > acceptable (in the sense alluded to above)? Or would it be > generally considered a distortion of Python idealogy (e.g. > like PERL's 'more than one way to do it' approach)? There should be one-- and preferably only one --obvious way to do it. The reason for this guideline is that if there were many similar ways to do the same thing (in the language itself), without one way standing out as an obvious, idiomatic choice, you would end up with every program using its own approach and it would be much harder to read and understand other people's programs. If there's one obvious, preferred way, you can look at code from hundreds of people and you will know immediately what they are doing and why. This does not apply to your case. You are already creating a custom interface for working with options. Does your approach make the code more readable and easier to work with? If yes, this is perfectly fine. [snip] -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Many possessions, if they do not make a man better, are at least expected to make his children happier; and this pathetic hope is behind many exertions. George Santayana -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sunday, February 10, 2013 5:29:54 AM UTC-6, Steven D'Aprano wrote: > Rick wrote: > And you have missed my point, which is that reversed(), and sorted(), were > not added to the language on a whim, but because they were requested, over > and over and over again. Well, well, this explains everything! We don't add features because of logic, or because of consistency, or even because of good sense, we simply add them to appease the masses. psst: Steven, maybe if the C and Java heads moan long enough we can get braced scoping, or, if the ruby guys pester us enough we can adopt the dollar sign to denote globals, the "@@" for class variables, and the "@" for instance variables! Oh yes! Because being loved is SO much more important than sticking to our philosophy of the Python Zen. > "appended" is called list addition. > > newlist = oldlist + [item_to_append] But where is the consistency? Yes the syntactic sugar of the "plus sign" is concise, however, the "+" operator does not "pair" intuitively with the "append" method. Even IF you transformed the "+" operator into a named method like "add" (or call the magic method "__add__") it still fails to mesh properly with "append", and the two words utterly fail to intuitively establish an "in-place" versus "copy-mutate" relationship. Consider the English definitions of "add" and "append" when applied to sequence objects: DEFINE "add" Expand a sequence of "somethings" to include additional "somethings" -- which may be another sequence of N somethings. However the exact location of the new "somethings" is not clearly intuit-able from the word "add" alone! DEFINE "append" Expand a sequence of "somethings" to include an additional "something". Here the exact location is can be intuited as: "at the end". > > flatten, flattened > > flatten is another often requested, hard to implement correctly, function. > The only reason that Python doesn't have a flatten is that nobody can agree > on precisely what it should do. Steven, the definition of flatten (as relates to sequences) is very, VERY simple: Return a new sequence that is the result of reducing a nested sequence of sequences into a single depth sequence. > Like map, filter, reduce, etc. flatten is not sensibly implemented as a > mutator method, but as a function. Only because you, along with a few other high ranking members of this community (including the BDFL himself!) have this /aversion/ to true OOP paradigm. Can you provide an example of how flatten "as a method" is incorrect versus flatten "as a function" is correct, or will this challenge be silently swept under the rug as so many before? > > insert, inserted > > "inserted" is called addition, together with list slicing when needed. > newlist = [item_to_insert] + oldlist > newlist = oldlist[0:5] + [item_to_insert] + oldlist[5: "inserted" is called "addition" by who? If are implying that "seq.__add__()" employs the semantics of the English word "addition" and seq.insert(arg) is a thin wrapper around "oldlist[0:5]+[item]+oldlist[5:]", then fine. But how will someone intuit those two methods as have a "mutating pairs relationship" from the names alone? Not to mention that calling magic methods is anti-pythonic! > > map, mapped > > filter, filtered > > reduce, reduced > > Those are nonsense. None of those are in-place mutator methods. Well not in the current implementation of Python; but they could be if we wanted them to be. Applying mutations both "in-place" and "to a copy" are very helpful. For example, Ruby supplies both forms for many commonly used operations on arrays: (However i am not a fan of these "mutator pairs") slice, slice! sort, sort! flatten, flatten! collect, collect! map, map! uniq, uniq! reject, reject! reverse, reverse! compact, compact! Steven, just because you have yet to encounter such usage does not mean the usage is "non-sense" seq.map(func) new = seq.mapped(func) seq.filter(lambda x: x<2) new = seq.filtered(lambda x: x<2) > Especially reduce, which reduces a list to a single item. Nice to see you are paying attention! I am sure you already know this, although your wording was clumsy and suggests otherwise, but reduce does NOTHING to the list itself: py> from operator import add py> a = [1,2,3] py> reduce(add, a) 6 py> a [1, 2, 3] reduce simply returns the result of the reduction; which is an Integer. However it is my strong belief that the sum function should not exist when a reduce function does. Why? Because "sum([1,2,3])" is the equivalent of "reduce(operator.add, [1,2,3])"; the latter being significantly explicit and the former being a potential linguistical interpretation nightmare. Now some might complain about this proposed removal of "sum" because the reduce function requires two arguments whereas the sum only needs one, and I say you're correct, however, this nega
Re: LangWart: Method congestion from mutate multiplicty
> > > flatten, flattened > > > > flatten is another often requested, hard to implement correctly, > > function. The only reason that Python doesn't have a flatten is > > that nobody can agree on precisely what it should do. > > Steven, the definition of flatten (as relates to sequences) is > very, VERY simple: > > Return a new sequence that is the result of reducing > a nested sequence of sequences into a single depth > sequence. What should you get if you flatten [[[1,2],[3,4]],[[5,6],[7,8]]] Should the result be [[1,2],[3,4],[5,6],[7,8]] or [1,2,3,4,5,6,7,8] I've needed both cases, depending on the situation. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Mark Janssen wrote: > A unified data model as I define it, specifies a canonical atomic unit > (like the unit integer) and an abstract grouping construct in which > these atomic units can be arranged. By themselves, these two can > construct arbitrary levels of data structure complexity. Add the > ability to apply names to these levels, and you have a complete data > model for a happy programming environment. My work, to give you some > context, involves the invention of a "fractal graph" which is where > the name "unified object model" came from, because a fractal graph, I > argue can represent every part of the physical world at every scale. How can you breathe *way* up there in space? http://www.joelonsoftware.com/articles/fog18.html P.S. not all phenomena are fractal. The elbow joint, for instance, is just a hinge, and not made of smaller elbow joints made of tinier elbow joints made of even tinier elbow joints made of ... -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Dennis Lee Bieber wrote: > On Mon, 11 Feb 2013 01:29:30 +1100, Steven D'Aprano > declaimed the following in > gmane.comp.python.general: > >> >> Oh dear. Chris was being sarcastic. I thought that, even if the sarcasm >> wasn't obvious, his "Ook. Ook!" at the end should have given it away: >> >> http://www.dangermouse.net/esoteric/ook.html >> > > Ah... and here I thought it might have been a subtle reference to > the Librarian of the Unseen University... > http://en.wikipedia.org/wiki/Unseen_University#Librarian Not so subtle. The creator of Ook obviously is a fan. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson wrote: > we can get the iterator for free. If however you want to control the > iteration /without/ being locked into a loop, you can explicitly call: > > py> iter(seq) > Or, if python employed /true/ OOP paradigm: > > py> Iterator(seq) Today I learned that the difference between "true" OOP and everything else is the presence of an initial capital letter. Thank you Rick for your deep insight. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sunday, February 10, 2013 7:30:00 AM UTC-6, Oscar Benjamin wrote: > On 10 February 2013 04:53, Mark Janssen wrote: > > [...] > > I have to agree with Rick, I think requiring the user to explicitly > > create a new object, which is already a good and widely-used practice, > > should be the Only One Way to Do It. > > Why should I copy a potentially large data structure just to iterate > over it in reverse order? That's a good question, and the answer is: "Only a fool would make a copy of ANY data structure only to simply iterate over it; be it forwards or backwards or sideways". > And why on earth would you want to remove > the more efficient ways of doing this? Well these "ways"(sic) might be more efficient, at this time, because the Python developers have defined them to be. This could be changed if they would drop the aversion to true OOP paradigm. To make this work properly you would need to optimize the constructor of the sequence object. If the user presents the seq object (say for example a list) with variable that points to an already existing list like: py> a = [1,2,3] py> for x in list(a).reverse(): ... do_something Python will not actually create a copy of the list because that would be foolish! Python would instead ITERATE over the existing object transparently. It's called OPTIMIZING CODE! By doing this we gain many things: * We don't have these foolish "mutate"<->"copy mutate" method "pairs" like: "seq.reverse()" and "seq.reversed()" * We are writing maintainable code by explicitly calling "Sequence(seq).mutate()". The intent becomes obvious even though Python may "optimize" our intentions "behind the scenes". > > Guessing method names is far suboptimal to this simple, easy idiom. > > There is no guessing. If the object has a __reverse__ method then it > specifically advertises that it knows how to create an iterator that > gives its values in reverse order. Otherwise __len__ and __getitem__ > are used. Really. And you know that simply from intuiting a seemingly unrelated method? Wow, i'd bet the detectives of many municipalities would love to rent some of your powers. What sort of esoteric rule book are you reading from my friend? -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson wrote: > On Sunday, February 10, 2013 5:29:54 AM UTC-6, Steven D'Aprano wrote: >> Rick wrote: >> And you have missed my point, which is that reversed(), and sorted(), >> were not added to the language on a whim, but because they were >> requested, over and over and over again. > > Well, well, this explains everything! > > We don't add features because of logic, or because of consistency, or even > because of good sense, we simply add them to appease the masses. They were requested because people kept re-inventing them. They kept re-inventing them because they are useful functions that make good sense to have. >> "appended" is called list addition. >> >> newlist = oldlist + [item_to_append] > > But where is the consistency? Strings use + for concatenation. Tuples use + for concatenation. Lists use + for concatenation. Seems pretty consistent to me. Are you sure you've used Python before? > Yes the syntactic sugar of the "plus sign" is concise, however, the "+" > operator does not "pair" intuitively with the "append" method. Adding "ed" to a word does not pair intuitively with the method name. You have to learn it, which in the case of most English speakers you probably did between the ages of 2 and 6. Using + to represent concatenation is no less intuitive. > Even IF you > transformed the "+" operator into a named method like "add" (or call the > magic method "__add__") it still fails to mesh properly with "append", and > the two words utterly fail to intuitively establish an "in-place" versus > "copy-mutate" relationship. So what? >> > flatten, flattened >> >> flatten is another often requested, hard to implement correctly, >> function. The only reason that Python doesn't have a flatten is that >> nobody can agree on precisely what it should do. > > Steven, the definition of flatten (as relates to sequences) is very, VERY > simple: > > Return a new sequence that is the result of reducing > a nested sequence of sequences into a single depth > sequence. Very, VERY simple until you actually implement this function, and discover that it does too much e.g. flatten([None, 23, [1, 2, 3], Point(x=2, y=3), ["spam", "ham"]]) => [None, 23, 1, 2, 3, 2, 3, 's', 'p', 'a', 'm', 'h', 'a', 'm'] So people who have *actually programmed*, instead of just talking about programming, have discovered that in practice you need to treat some sequences as primitives that don't get expanded. >> Like map, filter, reduce, etc. flatten is not sensibly implemented as a >> mutator method, but as a function. > > Only because you, along with a few other high ranking members of this > community (including the BDFL himself!) have this /aversion/ to true OOP > paradigm. > > Can you provide an example of how flatten "as a method" is incorrect > versus flatten "as a function" is correct, or will this challenge be > silently swept under the rug as so many before? Simple efficiency. The most efficient, and sensible, way to flatten a list is to create a new list. Trying to flatten a list in place is a dumb idea -- it is O(n**2), or possibly even worse. Since only an idiot would write flatten as an in-place method, any mutator version of flatten would have to use a non-mutator version, then use slicing to over-write itself: def flatten(self): new_list = flatten(self) self[:] = new_list which is fine if you absolutely have to have an in-place version, but why bother? The caller can do it themselves: mylist = flatten(mylist) [snip] >> > map, mapped >> > filter, filtered >> > reduce, reduced >> >> Those are nonsense. None of those are in-place mutator methods. > > Well not in the current implementation of Python; but they could be if we > wanted them to be. Now you're smoking crack. How can *reduce* be an in-place mutator method? py> mylist = [1, 2, 3, 4, 5] py> from operator import mul py> reduce(mul, mylist) 120 I would really like to see your implementation of a reduce method that turns a list into an int *in-place*. > Applying mutations both "in-place" and "to a copy" are > very helpful. Exactly. [snip] >> > My point was this: All mutate methods should mutate "in-place", >> >> Well duh. All mutator methods do mutate in-place, otherwise they wouldn't >> be mutator methods. > > So "reversed()" and "sorted()" mutate in-place? No. They are not mutator methods, because they do not mutate in place. >> > if the >> > programmer wishes to create a mutated copy of the object, then the >> > programmer should /explicitly/ create a copy of the object and then >> > apply the correct mutator method to the copy. >> >> Been there, done that, it sucks. That's about a dozen steps backwards to >> a worse time in Python development. > > Why? Because you have to type this > > reversed = list(seq).reverse() Are you sure you've programmed in Python before? That gives reversed = None. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Rick Johnson wrote: > On Sunday, February 10, 2013 7:30:00 AM UTC-6, Oscar Benjamin wrote: >> On 10 February 2013 04:53, Mark Janssen wrote: >> > [...] >> > I have to agree with Rick, I think requiring the user to explicitly >> > create a new object, which is already a good and widely-used practice, >> > should be the Only One Way to Do It. >> >> Why should I copy a potentially large data structure just to iterate >> over it in reverse order? > > That's a good question, and the answer is: "Only a fool would make a copy > of ANY data structure only to simply iterate over it; be it forwards or > backwards or sideways". Aren't you the fool who wants to remove reversed() and have people write: [quote] reversed = list(seq).reverse() Oh yes, you are the fool. And me the bigger fool for listening to you. Time for another six months in my killfile, methinks. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Python recv loop
Hi,
I'm implementing a python client connecting to a C-backend server and am
currently stuck to as to how to proceed with receiving variable-length byte
stream coming in from the server.
I have coded the first 4 bytes (in hexadecimal) of message coming in from the
server to specify the length of the message payload i.e. 0xad{...}
I've managed to receive and translate the message length until I reach my
second recv which I readjusted the buffer size to include the new message
length.
However that failed and recv received 0 bytes. I implemented the same algorithm
on the server side using C and it work so appreciate if you can help me on this.
# receive message length
print 'receiving data'
mlen = sock.recv(4)
try:
nbuf = int(mlen, 16)
except ValueError as e:
print 'invalid length type'
return -1
while True:
buf = sock.recv(nbuf)
if not buf:
break
slen = len(buf)
str = "{0} bytes received: {1}".format(slen, buf)
print str
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sun, Feb 10, 2013 at 4:10 PM, Steven D'Aprano wrote: > Mark Janssen wrote: > >> A unified data model as I define it, specifies a canonical atomic unit >> (like the unit integer) and an abstract grouping construct in which >> these atomic units can be arranged. By themselves, these two can >> construct arbitrary levels of data structure complexity. Add the >> ability to apply names to these levels, and you have a complete data >> model for a happy programming environment. My work, to give you some >> context, involves the invention of a "fractal graph" which is where >> the name "unified object model" came from, because a fractal graph, I >> argue can represent every part of the physical world at every scale. > > How can you breathe *way* up there in space? > > http://www.joelonsoftware.com/articles/fog18.html Haha, point taken, but I actually have an application for such a high-level abstraction -- a 3-d web. A unified information model could take the internet to the next level (much like the Internet itself did to all the disparate communications networks before). Instead of the current hypertext and cumbersome attempt at coding semantic meaning in RDF tags, (re)present the internet content in a 3-d space and let the visual cortex, along with the crowd, make the relationships. (See pangaia.sourceforge.net) > P.S. not all phenomena are fractal. The elbow joint, for instance, is just a > hinge, and not made of smaller elbow joints made of tinier elbow joints > made of even tinier elbow joints made of ... Oh, no doubt about that. Perhaps instead of fractal graph, I should call it a recursive graph -- there must be a "base case" which ends the infinite regress. For the model I've been working on, that base case is the unit integer (or the machine word with only the least-significant-bit set to "1"). Cheers, mark > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recv loop
On 02/10/2013 07:48 PM, Ihsan Junaidi Ibrahim wrote:
Hi,
I'm implementing a python client connecting to a C-backend server and am
currently stuck to as to how to proceed with receiving variable-length byte
stream coming in from the server.
I have coded the first 4 bytes (in hexadecimal) of message coming in from the
server to specify the length of the message payload i.e. 0xad{...}
Exactly how are you sending "hexadecimal" ? If that 0xad (which is only
one byte, what about the other 3 ?) is intended to be a C description,
then it's certainly not hex, it's binary. And probably little-endian,
to boot. That's a mistake, as network protocols almost always use
big-endian.
So what is the range of values for the length, and how are they actually
encoded? Are they uint32 in native binary format? And are you
permitted to change the encoding, to fix it? (If it were my choice, I'd
make it a printable decimal value, first choice, or printable hex,
second choice.)
I've managed to receive and translate the message length until I reach my
second recv which I readjusted the buffer size to include the new message
length.
However that failed and recv received 0 bytes. I implemented the same algorithm
on the server side using C and it work so appreciate if you can help me on this.
# receive message length
print 'receiving data'
mlen = sock.recv(4)
try:
nbuf = int(mlen, 16)
That supposes the count is being sent as a printable string of hex
digits. That's not what I concluded above.
except ValueError as e:
If the count starts as 0xad, I can't imagine why this exception wasn't
thrown.
print 'invalid length type'
return -1
while True:
buf = sock.recv(nbuf)
if not buf:
break
slen = len(buf)
str = "{0} bytes received: {1}".format(slen, buf)
print str
You might need to play with hexlify, if you persist in sending the count
in binary.
--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Sunday, February 10, 2013 6:12:57 PM UTC-6, Tim Chase wrote: > What should you get if you flatten > > [[[1,2],[3,4]],[[5,6],[7,8]]] > > Should the result be > > [[1,2],[3,4],[5,6],[7,8]] > > or > > [1,2,3,4,5,6,7,8] > > I've needed both cases, depending on the situation. Well providing /every/ possible solution for /every/ possible answer to /every/ problem is not going to be possible unless you are willing to endure an endless amount of complexity. My opinion is that flatten should should call seq.flatten() on all sub-sequences. That seems like the only /reasonable/ resolution to allow. At least sub-types could define how they get flattened. However, that does not solve your problem: where you wish to flatten a sequence down to a prescribed sub-depth; in your example: flatten(subdepth=1). class Sequence(): """Hypothetical sequence object.""" def flatten(self, depth=INFINITY): # ... py> seq = [[[1,2],[3,4]],0,[[5,6],[7,8]]] py> seq.flatten() [1,2,3,4,0,5,6,7,8] py> seq.flatten(depth=1) [[1,2,3,4],0,[5,6,7,8]] py> seq.flatten(depth=2) [1,2,3,4,0,5,6,7,8] py> seq.flatten(depth=3) # Throw error or just quietly return flat list??? I don't feel very good about this API though. But i admit it might be beneficial to some folks. Should this example be the built-in behavior of Sequence#flatten, probably not. But hey, here at pydev we add features that appease the masses because we want to be loved. So folks, get your votes in! :-) -- http://mail.python.org/mailman/listinfo/python-list
Logging within a class
Within __init__ I setup a log with self.log = logging.getLogger('foo') then add
a
console and filehandler which requires the formatting to be specified. There a
few
methods I setup a local log object by calling getChild against the global log
object.
This works fine until I need to adjust the formatter for a few. With this
style, I need
to redefine the handlers, so basically setup logging again.
I tried to get around this by using basicConfig and simply re-specifying format
inside
the few methods, but it didn't work.
How does one accomplish this most elegantly so I can define one log instance
with
the appropriate general console and file handlers in my class, then simply
override
the formatter for both handlers they use in a couple methods?
Thanks!
jlc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 10 February 2013 22:14, Rex Macey wrote: > I should have added that the setup gives an error window "Cannot install" > "Python version 3.3 required, which was not found in the registry." Yes, you should have added this information. Are you sure that Python 3.3 is installed? Have you tried running it? e.g. when I run "python" in my terminal I get: oscar:~$ python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >From within Python I can also query the version: >>> import sys >>> sys.version '2.7.3 (default, Sep 26 2012, 21:51:14) \n[GCC 4.7.2]' Can you get similar output to confirm that Python 3.3 is installed? Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recv loop
On 2013-02-11 00:48, Ihsan Junaidi Ibrahim wrote:
Hi,
I'm implementing a python client connecting to a C-backend server and am
currently stuck to as to how to proceed with receiving variable-length byte
stream coming in from the server.
I have coded the first 4 bytes (in hexadecimal) of message coming in from the
server to specify the length of the message payload i.e. 0xad{...}
I've managed to receive and translate the message length until I reach my
second recv which I readjusted the buffer size to include the new message
length.
However that failed and recv received 0 bytes. I implemented the same algorithm
on the server side using C and it work so appreciate if you can help me on this.
# receive message length
print 'receiving data'
mlen = sock.recv(4)
try:
nbuf = int(mlen, 16)
except ValueError as e:
print 'invalid length type'
return -1
while True:
buf = sock.recv(nbuf)
if not buf:
break
slen = len(buf)
str = "{0} bytes received: {1}".format(slen, buf)
print str
You should keep reading until you get all need or the connection is
closed:
buf = b''
while len(buf) < nbuf:
chunk = sock.recv(nbuf - len(buf))
if not chunk:
break
buf += chunk
--
http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Feb 9, 2:51 pm, Chris Angelico wrote: >> Rick Johnson wrote: >> I really don't like to read docs when learning a language, >> especially a "so-called" high level language. I prefer to learn >> the language by interactive sessions and object introspection. Then, >> when i have exhausted all abilities to intuit the solution, i will >> roll my eyes, maybe blubber an expletive, and then reluctantly crack >> open a user manual. > > What Rick means: "I want to claim that I've learned a new language, > but I want it to work exactly like the imaginary language in my mind, > and if it doesn't, I'm going to complain about it, rather than, > yaknow, actually learn a new language." Yeah, this is, pardon the french, just batshit crazy. How does one _ever_ learn _anything_ new if they expect everything to conform with their pre-established intuitions? As can be seen by his posts, the outcome is one just _doesn't_ learn. -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On 2013-02-11 00:36, Steven D'Aprano wrote: Rick Johnson wrote: On Sunday, February 10, 2013 5:29:54 AM UTC-6, Steven D'Aprano wrote: Rick wrote: And you have missed my point, which is that reversed(), and sorted(), were not added to the language on a whim, but because they were requested, over and over and over again. Well, well, this explains everything! We don't add features because of logic, or because of consistency, or even because of good sense, we simply add them to appease the masses. I remember a time when he was saying that the developers of the language were ignoring the silent majority. Now he's saying that we shouldn't simply add things to appease the masses. They were requested because people kept re-inventing them. They kept re-inventing them because they are useful functions that make good sense to have. Exactly. Practicality beats purity, and all that. -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Feb 11, 9:59 am, Rick Johnson wrote: > We don't add features because of logic, or because of consistency, > or even because of good sense, we simply add them to appease the masses. When "logic" or "good sense" are writing programs, maybe then we'll listen more to what they want in a language. "Good sense" would dictate that someone actually read documentation when dealing with a new programming language. "Logic" would indicate that expecting things outside of your control to confirm with your intuition is a fool's game; I highly recommend not reading up on any modern physics as there'll be plenty there that just makes you angry. PS pragmatism is a perfectly valid philosophical approach too. Far more practical than more "pure" approaches, and something something foolish consistency blah blah small minds. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Saturday, February 9, 2013 10:50:25 PM UTC-6, Chris Angelico wrote:
> [...]
> I don't understand. Wouldn't freezing an array (list) result in a
> tuple? And, why should there be no literal syntax for them?
>
> Having a convenient literal notation for every basic type is extremely
> handy.
Actually i must admit that you are correct. Of course the problem with literal
syntax is symbol congestion. But i have a solution. A solution that can survive
the limited number of grouping chars that python employs now. Except, i will
define them explicitly
{}: denotes ANY mapping object.
[]: denotes ANY mutable sequence object.
(): denotes ANY immutable sequence object.
<>: Hmm, there must be a good use for this one!
The key to removing complexity is to declare the literal syntax much the way
Python "represents" a "set". Observe:
py> set([1,2,3])
set([1,2,3])
Using this syntax we can apply "grouping" chars in proper context when writing
literal syntax. The only problem is how do we make this syntax unique enough to
avoid confusion and complexity??? Some hypothetical literal syntax,
"syntaxes", include:
[1,2,3] # Set literal
(1,2,3) # FrozenSet literal
set=>[1,2,3] # Set literal
set=>(1,2,3) # FrozenSet literal
set::[1,2,3] # Set literal
set::(1,2,3) # FrozenSet literal
set<[1,2,3]> # Set literal
set<(1,2,3)> # FrozenSet literal
# Set literal
# FrozenSet literal
set([1,2,3]) # Set literal
set((1,2,3)) # FrozenSet literal
...and to avoid conflicts with the "set" function, we just remove the set
function! Only the types list, dict, and tuple(bka:StaticList!) should have a
built-in constructor function, the remaining should have a typical OOP style
constructor:
mySet = Set([1,2,3])
mySetLiteral = set([1,2,3])
--
http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On Sun, Feb 10, 2013 at 5:14 PM, Rex Macey wrote: > I should have added that the setup gives an error window "Cannot install" > "Python version 3.3 required, which was not found in the registry." I'm guessing that you installed a 64-bit python and are using a 32-bit numpy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recv loop
In article ,
Ihsan Junaidi Ibrahim wrote:
> I'm implementing a python client connecting to a C-backend server and am
> currently stuck to as to how to proceed with receiving variable-length byte
> stream coming in from the server.
>
> I have coded the first 4 bytes (in hexadecimal) of message coming in from the
> server to specify the length of the message payload i.e. 0xad{...}
Is this server that you're talking to something that you have control
over, i.e. are you stuck with this protocol? Given a choice, I'd go
with something like JSON, for which pre-existing libraries for every
language under the sun.
But, let's assume for the moment that you're stuck with this
length-value encoding. OK, but it's going to be more complicated than
you think. [I assume we're talking TCP here?]
Carefully read the documentation for socket.recv():
> socket.recv(bufsize[, flags]) [...] The maximum amount of data to be received
> at once is specified by bufsize.
Linger on the word "maximum", and try to grok the fullness of of how
annoying that can be. What it means is that if the other side sent 120
bytes (octets), recv() might return all 120 at once, or it might return
them one at a time, or anything in between.
So, what you need to do is call recv() repeatedly in a loop, each time
passing it a value for bufsize which represents the amount left in the
message (i.e. the original message length parsed earlier minus all the
little bits and pieces that have been read so far).
Keep in mind, you also need to do this when you recv() the first 4
octets, which make up the length field. What you've got, recv(4), will
work MOST of the time, but it's perfectly legal for recv() to return a
short read. You can't predict how fragmentation and retry timeouts and
all sorts of low-level crud will cause your message boundaries to get
scrambled.
> # receive message length
> print 'receiving data'
> mlen = sock.recv(4)
> try:
> nbuf = int(mlen, 16)
> except ValueError as e:
> print 'invalid length type'
> return -1
>
> while True:
> buf = sock.recv(nbuf)
>
> if not buf:
> break
>
> slen = len(buf)
> str = "{0} bytes received: {1}".format(slen, buf)
> print str
Do you actually *know* what the value of nbuf is? Is it possible that
(somehow) it's 0? You should print (log, whatever), the value of nbuf,
just to make sure.
And, once you'e got all this working, tear it all out and convert to
using something sane like JSON. Let somebody else worry about all the
horrible details.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
On Feb 8, 4:29 pm, Rick Johnson wrote:
> That's a strange thing to say when you go on to provide an example that tests
> the validity of the object "each and every time":
Here's a tip: context is important. I was referring to not having to
*explicitly* test if a label *is defined* in order to be able to use
it, which is something you need to do in other languages, such as
Javascript:
var func = function() { throw EventException; }
a = func()
if ( a == '1') ... // this raises a ReferenceError as 'a' is not
defined
if ( typeof a !== 'undefined' && a == '1')... // this guards
against the ReferenceError
> And i find it to be incredibly asinine.
I find your smugness to be much the same.
> Consider this:
> if connect("my:db") as db:
>
>
> No need to make a call and then test for the validity of the call when you
> can do both simultaneously AND intuitively.
No need to learn a language when you can just make crap up and whine
when it doesn't work.
> *school-bell-rings*
You're "schooling" others using a hypothetical variant of an existing
language which you believe should conform to your a priori assumptions
about how such a language should work? You're "schooling" people who
_read the documentation_ when you admit to not doing so yourself?
You're not asinine, you're just an asshole.
--
http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: Namespace asinitiy and the folly of the global statement
On Feb 9, 2:25 pm, Michael Torrie wrote: > Rick seems to know his stuff > about Tk programming, but his knowledge of programming language theory > and formal computing seems quite informal. Not informal, "intuited". If he doesn't already know something, it's apparently not important. -- http://mail.python.org/mailman/listinfo/python-list
cafebabe python macosx easter egg?
$ hexdump -n4 -C $(which python) | awk '{print $2 $3 $4 $5 }'
--
http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: Namespace asinitiy and the folly of the global statement
On Mon, Feb 11, 2013 at 1:42 PM, alex23 wrote: > On Feb 9, 2:25 pm, Michael Torrie wrote: >> Rick seems to know his stuff >> about Tk programming, but his knowledge of programming language theory >> and formal computing seems quite informal. > > Not informal, "intuited". If he doesn't already know something, it's > apparently not important. I wonder how he learned about Tk. To be quite frank, I've not found tkinter to be particularly intuitive, and I've been doing GUI programming since the early 90s (with a wide variety of toolkits). Mind, that's not necessarily an indictment of tkinter per se; MOST windowing toolkits take a bit of mastering. But my general estimate is that it takes roughly as long to learn a GUI toolkit as to learn a language, and takes comparable effort. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and timeout -> running a shell command / want to guard against infinite loops
On Tuesday, 19 August 2003 15:01:01 UTC+12, Marcus Liddle wrote:
>
>
> Hi
>
> I'm trying to get a really simple python program to
> run a bash testing script and kill itself if its
> been running to long (ie infinite loop)
>
> create the thread object - test = TestThread()
> run the command - test.do_command("infloop.bash")
> if t.isAlive(): ...stop it
>
> any good ideas?
>
> cheers
> Marcus
> --
> Senior Assistant [mailto:[email protected]]
> Dept. of Computer ScienceUniversity of Canterbury
> Phone: +64 3 366-7001 ext: 7871 Office: 323
> [ http://www.cosc.canterbury.ac.nz/~marcus/index.html ]
Well you might try reroute the encryption subprocessors manually, but you'd
have to leave the The Code Matrix in order to do that. Have you tried brushing
you teeth and putting the cap back on? The things people for SEO huh? It would
appear my Author ranked name appears here, so I thought my future-self would
reply to my past self, thus applying entanglement theory, wave force particle
acceleration to bend the fabric of the universe as we know it, blowing the
infinite loop out of existence. -- thank you MrGoogle
-- thank you Marcus Liddle
(no relation to Alice Liddle from the Liddle House)
--
http://mail.python.org/mailman/listinfo/python-list
Re: cafebabe python macosx easter egg?
On Mon, Feb 11, 2013 at 5:10 PM, Rodrick Brown wrote:
> $ hexdump -n4 -C $(which python) | awk '{print $2 $3 $4 $5 }'
I believe that's used as a file signature. All you're doing is looking
at the first four bytes of the file; 0xCAFEBABE is used as a signature
by Java class files, and some others. You can probably find the same
signature in other programs on your system.
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Re: cafebabe python macosx easter egg?
On Sun, Feb 10, 2013 at 10:10 PM, Rodrick Brown wrote:
> Subject: cafebabe python macosx easter egg?
>
> $ hexdump -n4 -C $(which python) | awk '{print $2 $3 $4 $5 }'
cafebabe
~ $ # Huh. Let's google...
http://en.wikipedia.org/wiki/Hexspeak :
"0xCAFEBABE ("cafe babe") is used by Mach-O to identify Universal
object files, and by the Java programming language to identify Java
bytecode class files."
Some background:
http://en.wikipedia.org/wiki/Mach-O : "Mach-O […] is a file format for
executables […] used by most systems based on the Mach kernel" (OS X's
kernel is based on the Mach kernel.)
http://en.wikipedia.org/wiki/Universal_binary :
"A universal binary is, in Apple parlance, an executable file or
application bundle that runs natively on either PowerPC or […] Intel
64-based Macintosh computers; it is an implementation of the concept
more generally known as a fat binary."
Confirmation:
"OS X ABI Mach-O File Format Reference":
https://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html
:
struct fat_header
[...]
Fields:
magic
An integer containing the value 0xCAFEBABE in big-endian byte order format.
So, there you have it. Mach-O and Java bytecode just happen to use the
same magic number. Coincidence.
Cheers,
Chris R.
--
http://mail.python.org/mailman/listinfo/python-list
Import redirects
I have a package (say "foo") that I want to rename (say, to "bar"), and for compatibility reasons I want to be able to use the old package name to refer to the new package. Copying files or using filesystem symlinks is probably not the way to go, since that means any object in the modules of the package would be duplicated, changing one will not cause the other to be updated. Instead, I tried the following as the content of `foo/__init__.py`: import sys import bar sys.modules['foo'] = bar To my surprise, it seems to work. If I `import foo` now, the above will cause "bar" to be loaded and be used, which is expected. But even if I `import foo.baz` now (without first `import foo`), it will now correctly import "bar.baz" in its place. Except one thing: it doesn't really work. If I `import foo.baz.mymod` now, and if in "bar.baz.mymod" there is a statement `import bar.baz.depmod`, then it fails. It correctly load the file "bar/baz/depmod.py", and it assigns the resulting module to the package object bar.baz as the "depmod" variable. But it fails to assign the module object of "mymod" into the "bar.baz" module. So after `import foo.baz.mymod`, `foo.baz.mymod` results in an AttributeError saying 'module' object has no attribute 'mymod'. The natural `import bar.baz.mymod` is not affected. I tested it with both Python 2.7 and Python 3.2, and I see exactly the same behavior. Anyone knows why that happen? My current work-around is to use the above code only for modules and not for packages, which is suboptimal. Anyone knows a better work-around? -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On 11/02/2013 02:05, alex23 wrote: I highly recommend not reading up on any modern physics as there'll be plenty there that just makes you angry. Spoil sport. Fancy not wanting rr's views on string theory :) -- Cheers. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On Mon, Feb 11, 2013 at 6:19 PM, Mark Lawrence wrote: > On 11/02/2013 02:05, alex23 wrote: >> >> >> I highly recommend not reading up on any >> modern physics as there'll be plenty there that just makes you angry. >> > > Spoil sport. Fancy not wanting rr's views on string theory :) Is that Unicode string theory or ASCII string theory? Can I get a ringside seat at the debate between Rick and jmf on which kind of string theory was the wronger decision? ChrisA (And on whether "wronger" is permitted on this forum. Have at it,trolls!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Import redirects
On 11/02/2013 06:50, Isaac To wrote: I have a package (say "foo") that I want to rename (say, to "bar"), and for compatibility reasons I want to be able to use the old package name to refer to the new package. My apologies for the over engineering, but this is the best I could come up with. import bar as foo -- Cheers. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Import redirects
On Mon, Feb 11, 2013 at 6:28 PM, Mark Lawrence wrote: > On 11/02/2013 06:50, Isaac To wrote: >> >> I have a package (say "foo") that I want to rename (say, to "bar"), and >> for compatibility reasons I want to be able to use the old package name >> to refer to the new package. > > > My apologies for the over engineering, but this is the best I could come up > with. > > import bar as foo That puts it into sys.modules as bar, though; you'd need to change the import in every place it's used. If that's acceptable, great, but my reading of the OP was that the goal was to let other scripts import foo and get bar. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
On 11/02/2013 07:24, Chris Angelico wrote: On Mon, Feb 11, 2013 at 6:19 PM, Mark Lawrence wrote: On 11/02/2013 02:05, alex23 wrote: I highly recommend not reading up on any modern physics as there'll be plenty there that just makes you angry. Spoil sport. Fancy not wanting rr's views on string theory :) Is that Unicode string theory or ASCII string theory? Can I get a ringside seat at the debate between Rick and jmf on which kind of string theory was the wronger decision? I guess that the black market would put the price beyond the pocket of the average Python programmer. ChrisA (And on whether "wronger" is permitted on this forum. Have at it,trolls!) And I'll allow wronger as you're the righter. -- Cheers. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
