Re: Everything is an object in python - object class and type class

2015-06-02 Thread Mark Lawrence

On 03/06/2015 05:16, Eddilbert Macharia wrote:


Sadly yes i have worked with java, and that is what is causing me so much 
grief.In java objects are instance of a class.pretty simple.



You might like to read 
http://dirtsimple.org/2004/12/python-is-not-java.html and 
http://dirtsimple.org/2004/12/java-is-not-python-either.html


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Eddilbert Macharia
On Tuesday, June 2, 2015 at 2:27:31 PM UTC+3, Steven D'Aprano wrote:
> On Tue, 2 Jun 2015 08:36 pm, Eddilbert Macharia wrote:
> 
> > you guys are just confusing me, you are going in loops, and still i have
> > understood ,what makes everything in python an object. hey is where i'm at
> > : *** type in python refers to data types e.g. int, str, boolean e.t.c.
> > right ?
> 
> Yes. Also classes you create with the "class" keyword:
> 
> class K(object):
> ...
> 
> K is now a "type", just like int, str, list, object, etc.
> 
> 
> > *** The interpreter creates two classes type and object when setting up a
> > python environment. right ?
> 
> Many more than just two: it also creates list, str, dict, etc. But *first*
> it has to create type and object. So you are correct.
> 
> 
> > *** The creator (metaclass) of all data types (i.e. int,str) in python is
> > the class type. right ?
> 
> Correct.
> 
> [Aside: I'm only talking about Python 3 here. In Python 2 there is also a
> second hierarchy of classes, called "classic classes" or "old-style
> classes", which are *not* subclasses of type. But let's just ignore them,
> because they are gone in the most recent versions of Python.]
> 
> 
>  isinstance(int,type)
> > True
> > 
> > *** The instance of class type is a data type an instance of class type.
> > right ?
>  type(type)
> > 
> 
> type has many instances, not just one.
> 
> Instances of int are individual ints, like 0, 1, 2, 3, ...
> 
> Instances of type are individual types, like int, dict, str, list, ...
> 
> But one of those many instances of type is, yes, type itself! So *one* of
> the instances of type is type, which is also an instance of itself:
> 
>  isinstance(type,type)
> > True
> 
> Correct. This makes type special. Most types are *not* instances of
> themselves:
> 
> py> isinstance(int, int)
> False
> 
> 
> > *** Class type gets some of its behavior from class object through
> > inheritance.right ?
> > 
>  issubclass(type,object)
> > True
> 
> Correct.
> 
> 
> > *** instance of class object is type, in the sense it created using class
> > type which inherits from class object.right ?
> > 
>  isinstance(object,type)
> > True
>  isinstance(object,object)
> > True
> > 
> > so is it right to say, everything in python is an object because they
> > are instance of the class type which inherits from class object ?
> 
> No! That's not what we mean when we say "everything is an object".
> 
> Eddilbert, have you programmed in any other languages? It would help you
> understand if you have.

Sadly yes i have worked with java, and that is what is causing me so much 
grief.In java objects are instance of a class.pretty simple.

> 
> "Object" has a general meaning in computer science and programming, it is a
> compound data structure that is explicitly linked to a type which provides
> functionality that operates on that data structure.
> 
> In the programming language C, *no* values are objects. C has types (int16,
> uint32, bool, and many more) but no objects.
> 
> In the programming language Java, *some* values are objects, and some values
> are not objects.
> 
> In the programming language Python, *all* values are objects, in the general
> sense. That is what we mean by "Everything is an object".
> 
> Let's go back in time about 15 years or so. We're now using Python 1.5. In
> Python 1.5, there is no built-in object, and type is just a function, not a
> class:
> 
> >>> import sys
> >>> print sys.version
> 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)]
> >>> object
> Traceback (innermost last):
>   File "", line 1, in ?
> NameError: object
> >>> type
> 
> 
> 
> In Python 1.5, classes you create do not inherit from object, because object
> does not exist! BUT even in Python 1.5, it is true that everything is an
> object.
> 
> Remember, "object" can refer to two things:
> 
> - *specifically* the class called "object";
> 
> - the *general concept* of objects, from object oriented programming.
> 
> 
> In Python 1.5:
> 
> - everything is an object [the general concept]
> 
> - nothing is an instance of the class called "object"
> 
> 
> In Python 2:
> 
> - everything is an object [the general concept]
> 
> - some things, but not all things, are instances of the class
>   called "object"
> 
> 
> In Python 3:
> 
> - everything is an object [the general concept]
> 
> - everything is an instance of the class called "object"
> 
> 
> 
> 

I think then in python object and instance of a class are entirely different 
things.

in OOP and python - object is a representation of a real thing, or a concept 
.e.g a person,number and the concept of classes- which is the concept of 
create/representing other objects using a programming language to the machine.

class - This is what is used to create/represent objects in the machine using a 
programming language

class instance - This is the output of the classes this is a representation of 
an object.


> -- 
> Steven

-- 

Issuing commands using "exec_command()" of paramiko AND also sending commands together

2015-06-02 Thread Pythonista
Using paramiko's exec_command(), i would like to send a command, process its 
output and do it for several other commands. I notice that its not quick enough 
or something like that.

How would I handle that scenario AND also providing multiple commands together 
(there is 1 post on stackoverflow for issuing multiple commands but I am not 
sure if someone has tried it. It didnt work for me!

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-06-02 Thread Ian Kelly
On Tue, Jun 2, 2015 at 11:19 AM, Marko Rauhamaa  wrote:
> Steven D'Aprano :
>
>> On Fri, 29 May 2015 12:00 pm, Steven D'Aprano wrote:
>>
>> [...]
>>> in a language where classes are
>>> themselves values, there is no reason why a class must be instantiated,
>>> particularly if you're only using a single instance of the class. Anyone
>>> ever come across a named design pattern that involves using classes
>>> directly without instantiating them?
>>>
>>> I'm basically looking for a less inelegant term for "instanceless class"
>>> -- not so much a singleton as a zeroton.
>>
>> C# has these, and calls them static classes.
>
> I guess Python has them, too, and calls them modules.

Indeed. I find it amusing that C# has special syntax to work around
what is ostensibly a design feature -- that all code must be contained
in a class (or struct).

But then, the same practice also exists in Java, where there is no
specific syntax for it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Skip Montanaro
Folks, I'm not interested in rehashing this. I don't know what all the
open file descriptors are. Some/many/most will have been opened by
underlying C++ libraries and will not have been opened by code at the
Python level. I do think the addition of an os.fsync() attempt on each
file descriptor before calling os.close() makes some sense to me.
Beyond that, I'm not sure there's more that can be done.

I sent my last message simply because I was surprised os.closerange()
existed. I have no idea why it didn't turn up in my original
searching.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Ian Kelly
On Tue, Jun 2, 2015 at 3:47 PM, Mark Lawrence  wrote:
> The classic response to "Super Considered Harmful" for those who may be
> interested is
> https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ and
> recently https://www.youtube.com/watch?v=EiOglTERPEo

I feel slightly cheated. In the video he promises to show how to do
dependency injection using super, but in both of the examples given,
every instance of "super()" could simply be replaced with "self" and
the result would be the same. That's just taking advantage of the MRO,
not super.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help on this sorted function

2015-06-02 Thread Chris Angelico
On Wed, Jun 3, 2015 at 6:25 AM, fl  wrote:
> I am still new to Python. How to get the sorted dictionary output:
>
> {1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

Since dictionaries don't actually have any sort of order to them, the
best thing to do is usually to simply display it in order. And there's
a very handy function for doing that: a pretty-printer.

>>> import pprint
>>> pprint.pprint({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

This one comes with Python, so you can use it as easily as that above
example. Or you could do it this way:

>>> from pprint import pprint
>>> pprint({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

For a lot of Python data structures, this will give you a tidy and
human-readable display.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-02 Thread Chris Angelico
On Wed, Jun 3, 2015 at 7:27 AM, fl  wrote:
> I just see the tutorial says Python can return value in function, it does
> not say multiple data results return situation. In C, it is possible.
> How about Python on a multiple data return requirement?

Technically, neither C nor Python can return multiple values from a
single function call. In Python, the most common way to do this is to
return a tuple, which can then be unpacked; as other posts in this
thread have shown, this can look a lot like returning multiple values,
and it's pretty convenient. In C, the nearest equivalent is passing a
number of pointers as parameters, and having the function fill out
values. Python's model is a lot closer to what you're saying than C's
model is :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Chris Angelico
On Wed, Jun 3, 2015 at 7:06 AM, Alain Ketterlin
 wrote:
> I've no idea what the OP's program was doing, so I'm not going to split
> hairs. I can't imagine why one would like to mass-close an arbitrary set
> of file descriptors, and I think APIs like os.closerange() are toxic and
> an appeal to sloppy programming.

When you fork, you get a duplicate referent to every open file in both
parent and child. Closing them all in the child is very common, as it
allows the parent to continue owning those file descriptors (so that
when you close it in the parent, the resource is really closed). One
notable example is with listening sockets; bind/listen in the parent,
then fork (maybe to handle a client), then terminate the parent
process. You now cannot restart the parent without aborting the child,
as the child now owns that listening socket (even if it never wants to
use it). There are some specific ways around this, but not on all OSes
(eg Linux only added support for SO_REUSEPORT in 3.9), and the best
way has always been to make sure the children don't hang onto the
listening socket. (There are other good reasons for doing this, too.)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Marko Rauhamaa
Grant Edwards :

> On 2015-06-02, Ian Kelly  wrote:
>> Accepting for the sake of argument that "something to be subclassed"
>> is a reasonable definition of object,
>
> Huh?  You can't subclass an object.  You can subclass a Class.

More to the point: you don't need classes for objects -- even in the
deepest OOP sense.

In Python, classes are little more than constructor functions.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is 'palindrome' defined?

2015-06-02 Thread Marko Rauhamaa
John Ladasky :

> On Monday, June 1, 2015 at 2:22:02 AM UTC-7, Marko Rauhamaa wrote:
>
>> Sota-apina nakataan raastimeen.
>>   Apelle pane emit.
>>   Saarnaa takanani paatos.
>> 
>> (= "The war monkey will be chucked into a grater.
>> Hand the pistils to father-in-law.
>> Pathos does preach behind me.")
>
> With this post, you have convinced me that 1) Finnish is a very
> interesting, and even poetic, language; and that 2) eating the velvet
> off of reindeer antlers must have a very similar effect to LSD. :^)

The phonetic structure of Finnish is ideal for palindromes, unlike
English.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Marko Rauhamaa
Alain Ketterlin :

> Marko Rauhamaa  writes:
>> First, if close() fails, what's a poor program to do?
>
> Warn the user? Not assume everything went well? It all depends on the
> application, and what the file descriptor represents.

The problem here is in the system call contract, which is broken.
There's no fix. The man page admonition is just hand-waving without
constructive advice.

>> Try again?
> Could be a good idea on NFS or other kind of mounts.

Maybe close() will fail for ever.

> I can't imagine why one would like to mass-close an arbitrary set of
> file descriptors,

That's standard practice before execking a file. Failure to do that can
seriously hurt the parent process. For example, the parent (or child)
will never read an EOF from file descriptor if its duplicate is open in
an unwitting child process. Also, the number of open files in the system
may grow over all limits or simply waste kernel resources.

Close-on-exec is nice, maybe. However, you don't have control over all
file descriptors. Loggers, high-level library calls and others open
files without the application programmer knowing or having direct
control over.

> and I think APIs like os.closerange() are toxic and an appeal to
> sloppy programming.

And you recommend what instead?


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the difference between list() and list?

2015-06-02 Thread John Gordon
In <3ada3275-68c9-421c-aa19-53c312c42...@googlegroups.com> fl 
 writes:

> I find the following results are interesting, but I don't know the difference
> between list() and list.

'list()' invokes the list class, which creates and returns a new list.
Since you haven't passed any arguments, the list is empty.

'list' refers to the list class itself.

Here is a more in-depth example, using functions instead of classes:

def hello(name):
return 'Hello'.

If you call this function, like so:

greeting = hello()
print greeting

You will get the output 'Hello'.

But, if you just REFER to the function, instead of actually CALLING it:

greeting = hello
print greeting

You will get this output:



Because you omitted the double parentheses, you're getting the hello
function object itself, instead of the RESULT of that function.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-02 Thread sohcahtoa82
On Tuesday, June 2, 2015 at 2:27:37 PM UTC-7, fl wrote:
> Hi,
> 
> I just see the tutorial says Python can return value in function, it does 
> not say multiple data results return situation. In C, it is possible.
> How about Python on a multiple data return requirement?
> 
> 
> Thanks,

You return a tuple, set, or other iterable.  For example:

def return_two_values():
return 1, 2

a, b = return_two_values()
print a
print b

This would print:
1
2

Note though that when doing something like this, you have to be really careful 
that if you have multiple calls to `return` in your function, that they will 
ALL return the same number of values.  Otherwise, when the tuple/list/etc. is 
unpacked, you'll get an error.

def return_two_values():
# ... do some stuff
if someCondition:
print "someCondition was true!"
return 0
return 1, 2

a, b = return_two_values()

Here, if someCondition ended up being False, then an exception would be thrown.

Keep in mind that the unpacking of the returned value into the variables `a` 
and `b` works with *ANY* iterable.  So if you returned 'abc' and unpacked it 
into three variables, then the first would contain 'a', the second 'b', and the 
third 'c'.

You can also just return a dictionary if you want to return multiple values.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-02 Thread John Gordon
In <3bbe49da-e989-4a8c-a8a9-75d3a786f...@googlegroups.com> fl 
 writes:

> Hi,

> I just see the tutorial says Python can return value in function, it does 
> not say multiple data results return situation. In C, it is possible.
> How about Python on a multiple data return requirement?

Python functions can return lists, tuples, dictionaries, or any other
container-like object.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the difference between list() and list?

2015-06-02 Thread Joel Goldstick
On Tue, Jun 2, 2015 at 5:33 PM, fl  wrote:
> Hi,
>
> I find the following results are interesting, but I don't know the difference
> between list() and list.
>
>
>
>
>
>
 nums=list()
 nums
> []
 xx=list
 xx
> 
 nums
> []
 print(xx)
> 
 print(nums)
> []

>
>
>
> Could you tell me that?

list is the name of a built-in function that returns a list object
when you set xx = list, you are giving that function a new name -- 'xx'
when you invoke the function:  xx() or list() it returns a list
>
> Thanks,
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can Python function return multiple data?

2015-06-02 Thread Joel Goldstick
On Tue, Jun 2, 2015 at 5:27 PM, fl  wrote:
> Hi,
>
> I just see the tutorial says Python can return value in function, it does
> not say multiple data results return situation. In C, it is possible.
> How about Python on a multiple data return requirement?
>
>
> Thanks,
> --
> https://mail.python.org/mailman/listinfo/python-list

Yes!

def my_function(n):
return n, n*2

a_number, its_double = my_function(3)

a_number will be 3, its_double will be 6

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


What is the difference between list() and list?

2015-06-02 Thread fl
Hi,

I find the following results are interesting, but I don't know the difference
between list() and list.






>>> nums=list()
>>> nums
[]
>>> xx=list
>>> xx

>>> nums
[]
>>> print(xx)

>>> print(nums)
[]
>>> 



Could you tell me that?

Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Can Python function return multiple data?

2015-06-02 Thread fl
Hi,

I just see the tutorial says Python can return value in function, it does 
not say multiple data results return situation. In C, it is possible.
How about Python on a multiple data return requirement?


Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Grant Edwards
On 2015-06-02, Ian Kelly  wrote:

>>> Sorry.  I meant "object" in the sense of OOP:  something you might
>>> extend or make a derived class with.
>>
>> I'm not sure you get to define which properties of objects you want
>> not to count.
>
> Accepting for the sake of argument that "something to be subclassed"
> is a reasonable definition of object,

Huh?  You can't subclass an object.  You can subclass a Class.

-- 
Grant Edwards   grant.b.edwardsYow! I want to so HAPPY,
  at   the VEINS in my neck STAND
  gmail.comOUT!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is 'palindrome' defined?

2015-06-02 Thread John Ladasky
On Monday, June 1, 2015 at 2:22:02 AM UTC-7, Marko Rauhamaa wrote:

> Sota-apina nakataan raastimeen.
>   Apelle pane emit.
>   Saarnaa takanani paatos.
> 
> (= "The war monkey will be chucked into a grater.
> Hand the pistils to father-in-law.
> Pathos does preach behind me.")

With this post, you have convinced me that 1) Finnish is a very interesting, 
and even poetic, language; and that 2) eating the velvet off of reindeer 
antlers must have a very similar effect to LSD.  :^)


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Alain Ketterlin
Marko Rauhamaa  writes:

> Alain Ketterlin :
>
>> The close(2) manpage has the following warning on my Linux system:
>>
>> | Not checking the return value of close() is a common but
>> | nevertheless serious programming error. It is quite possible that
>> | errors on a previous write(2) operation are first reported at the
>> | final close(). Not checking the return value when closing the file
>> | may lead to silent loss of data. This can especially be observed
>> | with NFS and with disk quota.
>> | 
>>
>> (I haven't followed the thread, but if your problem is to make sure
>> fds are closed on exec, you may be better off using the...
>> close-on-exec flag. Or simply do the bookkeeping.)
>
> The quoted man page passage is a bit untenable.
>
> First, if close() fails, what's a poor program to do?

Warn the user? Not assume everything went well?  It all depends on the
application, and what the file descriptor represents.

> Try again?

Could be a good idea on NFS or other kind of mounts.

> How do you get rid of an obnoxious file descriptor?

You don't, you check everything before closing the file, with fsync()
for example.

I've no idea what the OP's program was doing, so I'm not going to split
hairs. I can't imagine why one would like to mass-close an arbitrary set
of file descriptors, and I think APIs like os.closerange() are toxic and
an appeal to sloppy programming.

-- Alain.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help on this sorted function

2015-06-02 Thread Joonas Liik
my_dict = {1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

# dict.items() returns an iterator that returns pairs of (key, value) pairs
# the key argument to sorted tells sorted what to sort by,
operator.itemgetter is a factory function , itemgetter(1)== lambda
iterable: iterable[1]
sorted_dict = sorted(my_dict.items(), key=itemgetter(1))

# at this moment sorted dict is a generator of key-value tuples in the
right order
sorted_dict = OrderedDict(sorted_dict) # turn the generator in to an actual
dict.

# notice: regular dicts are NOT ORDERED, you need a special type of dict to
preserve the order, hence OrderedDict
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help on this sorted function

2015-06-02 Thread Joonas Liik
>>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
>>> ff
[1, 2, 3, 4, 5]

sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) is equivalent to
sorted(iter({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}))

and iter(dict) iterates over the dict keys, so when you do
iter({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) you essentially get
[1,2,3,4,5]
and sorted([1,2,3,4,5]) returns [1,2,3,4,5]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help on this sorted function

2015-06-02 Thread fl
On Tuesday, June 2, 2015 at 1:20:40 PM UTC-7, fl wrote:
> Hi,
> 
> I try to learn sorted(). With the tutorial example:
> 
> 
> 
> 
> >>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
> >>> ff
> [1, 2, 3, 4, 5]
> 
> 
> 
> I don't see what sorted does in this dictionary, i.e. the sequence of 
> 1..5 is unchanged. Could you explain it to me?
> 
> 
> Thanks,

Excuse me. After a small modification, it can see the effect.


>>> ff=sorted({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
>>> ff
[1, 2, 3, 4, 5]


I am still new to Python. How to get the sorted dictionary output:

{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}
-- 
https://mail.python.org/mailman/listinfo/python-list


Please help on this sorted function

2015-06-02 Thread fl
Hi,

I try to learn sorted(). With the tutorial example:




>>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
>>> ff
[1, 2, 3, 4, 5]



I don't see what sorted does in this dictionary, i.e. the sequence of 
1..5 is unchanged. Could you explain it to me?


Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Marko Rauhamaa
Alain Ketterlin :

> The close(2) manpage has the following warning on my Linux system:
>
> | Not checking the return value of close() is a common but
> | nevertheless serious programming error. It is quite possible that
> | errors on a previous write(2) operation are first reported at the
> | final close(). Not checking the return value when closing the file
> | may lead to silent loss of data. This can especially be observed
> | with NFS and with disk quota.
> | 
>
> (I haven't followed the thread, but if your problem is to make sure
> fds are closed on exec, you may be better off using the...
> close-on-exec flag. Or simply do the bookkeeping.)

The quoted man page passage is a bit untenable.

First, if close() fails, what's a poor program to do? Try again? How
do you get rid of an obnoxious file descriptor? How would close-on-exec
help? Would exec*() fail?

What if an implicit close() fails on _exit(), will _exit() fail then?
(The man page doesn't allow it.)

The need to close all open file descriptors comes between fork() and
exec*(). The kernel (module) does not see the close() system call unless
the reference count drops to zero. Normally, those function calls
between fork() and exec*() are therefore no-ops.

However, there's no guarantee of that. So the parent process might get
to call close() before the child that is about to call exec*(). Then,
the parent would not get the error that the man page talks about.
Instead, the error goes to the child, which has no reasonable way of
dealing with the situation.

I think having NFS et al postpone their I/O errors till close() is
shifting the blame to the victim.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Ian Kelly
On Tue, Jun 2, 2015 at 12:10 PM, Ned Batchelder  wrote:
> On Tuesday, June 2, 2015 at 1:59:37 PM UTC-4, BartC wrote:
>> Javascript primitives include Number and String.
>>
>> What does Python allow to be done with its Number (int, etc) and String
>> types that can't be done with their Javascript counterparts, that makes
>> /them/ objects?
>
> They have methods (not many, but a few):
>
 i, f = 101, 2.5
 i.bit_length()
> 20
 i.to_bytes(6, "big")
> b'\x00\x00\x00\x0fBA'
 f.as_integer_ratio()
> (5, 2)
 f.hex()
> '0x1.4p+1'

To add a wrinkle to this discussion, Javascript numbers also have methods:

js> (24).toExponential(3)
"2.400e+1"

I believe this is accomplished by implicitly boxing the number in the
Number class when a method or property is accessed. This can be seen
with:

js> (24).toSource()
"(new Number(24))"

Note that "24" and "new Number(24)" are not equivalent.

js> 24 === 24
true
js> 24 === new Number(24)
false
js> typeof(24)
"number"
js> typeof(new Number(24))
"object"

But this is a bit of an implementation detail. So what distinguishes
Javascript primitives from objects? Steven listed "identity" as a
third property of objects upthread; that seems applicable here.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain lambda function to me?

2015-06-02 Thread ast


"fl"  a écrit dans le message de 
news:323866d1-b117-4785-ae24-7d04c49bc...@googlegroups.com...

Hi,


def make_incrementor(n):

... return lambda x: x + n
...

f = make_incrementor(42)
f(0)

42

f(1)

43


make_incrementor is a fonction which return a function !
and the returned function just add n to its input

it is equivalent to:

def make_incrementor(n):

   def inc(x):
   return x+n

   return inc




The second lambda example is even more obscure to me:


pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Could you explain 'key=lambda pair: pair[1]' to me?


the sort is done on the values returned by the key function
key function "lambda pair: pair[1]" returns the second element of each pair ( , 
)

so the sort is done alphabetically on the strings 'one' 'two' 'three' 'four'


--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Jon Ribbens
On 2015-06-02, Dr. Bigcock  wrote:
> It doesn't really do anything.  No one uses integers as objects.
> (Any dissenters?)

Yes. *Everyone* uses integers as objects. Containers such as
lists and dictionaries and tuples etc contain objects. If
integers weren't objects then you wouldn't be able to put them
in containers (and you'd end up with Java).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain lambda function to me?

2015-06-02 Thread Chris Kaynor
On Tue, Jun 2, 2015 at 11:14 AM, fl  wrote:

> Hi,
>
> I see the description of lambda at the online tutorial, but I cannot
> understand it. '42' is transferred to the function. What 'x' value should
> be? I do not see it says that it is '0'. And, what is 'x'?
>

The lambda keyword is merely another way to define a function.

As a general (and somewhat simplified rule),
func = lambda <<1>>: <<2>>
is the same as
def func(<<1>>):
return <<2>>

The main difference is that lambda is an expression, while def is a
statement, which means you can use lambda is many places you cannot use
def, without adding extra lines of code.

>>> def make_incrementor(n):
> ... return lambda x: x + n
> ...
> >>> f = make_incrementor(42)
> >>> f(0)
> 42
> >>> f(1)
> 43
>

Following the above rule, you can convert make_incrementor to look like:

def make_incrementor(n):
def func(x):
return x+n
return func

That function, when called, will return a new function that takes one
argument, and adds it to the argument to make_incrementor.

n will be assigned what ever is passed into make_incrementor (42 in the
example code), and x will be what ever is passed into the returned function
(0 and 1 in the example).


> The second lambda example is even more obscure to me:
>
> >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
> >>> pairs.sort(key=lambda pair: pair[1])
> >>> pairs
> [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
>
>
> Could you explain 'key=lambda pair: pair[1]' to me?
>

In this case, you are passing a new "key" function into list.sort. Per the
documentation [1], the key function will be given each item in the input
list and should return the key to sort that item by. The lambda is defining
a function which takes one of those items (named pair inside the function),
and returns the second item (index 1) of it. list.sort then sorts the items
in the original list based on this key, whereby you get "four", "one",
"three", "two" sorted as strings, but the output will include the full
pairs.

This example could be rewritten as (again, following the general rule
mentioned at the top)"
>>> def keyFunc(pair):
>>> return pair[1]
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=keyFunc)
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

[1] https://docs.python.org/2/howto/sorting.html#key-functions


> Python grammar seems too succinct to me.
>
>
> Thanks,
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Could you explain lambda function to me?

2015-06-02 Thread fl
Hi,

I see the description of lambda at the online tutorial, but I cannot 
understand it. '42' is transferred to the function. What 'x' value should
be? I do not see it says that it is '0'. And, what is 'x'?








>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43


The second lambda example is even more obscure to me:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Could you explain 'key=lambda pair: pair[1]' to me?

Python grammar seems too succinct to me.


Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Laura Creighton
In a message of Tue, 02 Jun 2015 19:46:54 +0200, "ast" writes:
>
>
>"Laura Creighton"  a écrit dans le message de 
>news:mailman.64.1433255400.13271.python-l...@python.org...
>> You may be looking for dictionary dispatching.
>>
>> You can translate the key into a callable.
>>
>> def do_ping(self, arg):
>>return 'Ping, {0}!'.format(arg)
>>
>> def do_pong(self, arg):
>>return 'Pong, {0}!'.format(arg)
>>
>> dispatch = {
>>'ping': do_ping,
>>'pong': do_pong
>> }
>>
>> and then at some point do
>>
>>dispatch[command](arg)
>>
>> It is useful to know that tuples make perfectly good dictionary keys,
>> in case you need to store more state somewhere.
>>
>> Laura
>
>hello
>
>Why "self" is as parameter of functions do_ping and do_pong ?
>
>thx

yanked out of code I had lying around, without proper thought.
Sorry about that.

Laura

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Ned Batchelder
On Tuesday, June 2, 2015 at 1:59:37 PM UTC-4, BartC wrote:
> On 02/06/2015 18:00, Steven D'Aprano wrote:
> > On Tue, 2 Jun 2015 10:49 pm, BartC wrote:
> >
> >> On 02/06/2015 12:27, Steven D'Aprano wrote:
> 
> >>> In the programming language Java, *some* values are objects, and some
> >>> values are not objects.
> >>>
> >>> In the programming language Python, *all* values are objects, in the
> >>> general sense. That is what we mean by "Everything is an object".
> >>
> >> In a dynamically typed language such as Python, you need to be able to
> >> deal with values consistently whatever their type, simply because you
> >> can't tell what the types are from source code. (Not without a lot of
> >> work which Python doesn't attempt, although RPython might do so.) Example:
> >>
> >>print (a)
> >>
> >> a might be the int 42, or a it might be a million-element list. So both
> >> are wrapped up as 'objects'.
> >
> > Again, this is not relevant. Javascript is dynamically typed, but some
> > values are machine primitives and other values are objects. The interpreter
> > keeps track of this at runtime.
> 
> Javascript primitives include Number and String.
> 
> What does Python allow to be done with its Number (int, etc) and String 
> types that can't be done with their Javascript counterparts, that makes 
> /them/ objects?

They have methods (not many, but a few):

>>> i, f = 101, 2.5
>>> i.bit_length()
20
>>> i.to_bytes(6, "big")
b'\x00\x00\x00\x0fBA'
>>> f.as_integer_ratio()
(5, 2)
>>> f.hex()
'0x1.4p+1'

--Ned.

> 
> -- 
> Bartc

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Jon Ribbens
On 2015-06-02, BartC  wrote:
> On 02/06/2015 18:00, Steven D'Aprano wrote:
>> Again, this is not relevant. Javascript is dynamically typed, but some
>> values are machine primitives and other values are objects. The interpreter
>> keeps track of this at runtime.
>
> Javascript primitives include Number and String.
>
> What does Python allow to be done with its Number (int, etc) and String 
> types that can't be done with their Javascript counterparts, that makes 
> /them/ objects?

The fact that they are, er, objects? They are instances of classes,
they have methods that you can call, you can create subclasses, etc?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread random832


On Tue, Jun 2, 2015, at 13:59, BartC wrote:
> On 02/06/2015 18:00, Steven D'Aprano wrote:
> > Again, this is not relevant. Javascript is dynamically typed, but some
> > values are machine primitives and other values are objects. The interpreter
> > keeps track of this at runtime.
> 
> Javascript primitives include Number and String.
> 
> What does Python allow to be done with its Number (int, etc) and String 
> types that can't be done with their Javascript counterparts, that makes 
> /them/ objects?

That's not really a fair question, because the Javascript object model
is so different from the Python one. The point is that they are handled
_the same_ as all other objects, not that they have some specific
capability.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread BartC

On 02/06/2015 18:00, Steven D'Aprano wrote:

On Tue, 2 Jun 2015 10:49 pm, BartC wrote:


On 02/06/2015 12:27, Steven D'Aprano wrote:



In the programming language Java, *some* values are objects, and some
values are not objects.

In the programming language Python, *all* values are objects, in the
general sense. That is what we mean by "Everything is an object".


In a dynamically typed language such as Python, you need to be able to
deal with values consistently whatever their type, simply because you
can't tell what the types are from source code. (Not without a lot of
work which Python doesn't attempt, although RPython might do so.) Example:

   print (a)

a might be the int 42, or a it might be a million-element list. So both
are wrapped up as 'objects'.


Again, this is not relevant. Javascript is dynamically typed, but some
values are machine primitives and other values are objects. The interpreter
keeps track of this at runtime.


Javascript primitives include Number and String.

What does Python allow to be done with its Number (int, etc) and String 
types that can't be done with their Javascript counterparts, that makes 
/them/ objects?


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread ast


"Laura Creighton"  a écrit dans le message de 
news:mailman.64.1433255400.13271.python-l...@python.org...

You may be looking for dictionary dispatching.

You can translate the key into a callable.

def do_ping(self, arg):
   return 'Ping, {0}!'.format(arg)

def do_pong(self, arg):
   return 'Pong, {0}!'.format(arg)

dispatch = {
   'ping': do_ping,
   'pong': do_pong
}

and then at some point do

   dispatch[command](arg)

It is useful to know that tuples make perfectly good dictionary keys,
in case you need to store more state somewhere.

Laura


hello

Why "self" is as parameter of functions do_ping and do_pong ?

thx


--
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-06-02 Thread Marko Rauhamaa
Steven D'Aprano :

> On Fri, 29 May 2015 12:00 pm, Steven D'Aprano wrote:
>
> [...]
>> in a language where classes are 
>> themselves values, there is no reason why a class must be instantiated,
>> particularly if you're only using a single instance of the class. Anyone
>> ever come across a named design pattern that involves using classes
>> directly without instantiating them?
>> 
>> I'm basically looking for a less inelegant term for "instanceless class"
>> -- not so much a singleton as a zeroton.
>
> C# has these, and calls them static classes.

I guess Python has them, too, and calls them modules.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Parser needed.

2015-06-02 Thread Skybuck Flying



"MRAB"  wrote in message 
news:mailman.71.1433263397.13271.python-l...@python.org...


On 2015-06-02 05:45, Skybuck Flying wrote:

Example for python:

MyString = "Hello World"

print MyString.rfind("World")
if MyString.rfind("World"):
print "yes"
else:
print "no"

Pretty cool.



"
.rfind returns the index if found, -1 if not found.

"World".rfind("World") returns 0, which will be treated as false.

"foo".rfind("World") returns -1, which will be treated as true.
"

Yes I agree, that code is not very clean.

Hence I added:

print MyString.rfind("World")

Just to figure out if it indeed prints an index.

Index 0 might be of use too, so checking for true/false like I did above 
should not be done.


Consider it incorrect code.

However I didn't care at the time cause I was in a hurry... I knew it was 
dirty but this post correct that and warns people not to write code like I 
did... just in case ! ;)


And also to let you know I am full aware of the shady nature of this code ! 
;) =D


Bye,
 Skybuck :)







--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Steven D'Aprano
On Tue, 2 Jun 2015 10:49 pm, BartC wrote:

> On 02/06/2015 12:27, Steven D'Aprano wrote:
> 
>> "Object" has a general meaning in computer science and programming, it is
>> a compound data structure that is explicitly linked to a type which
>> provides functionality that operates on that data structure.
>>
>> In the programming language C, *no* values are objects. C has types
>> (int16, uint32, bool, and many more) but no objects.
> 
> The C Standard has hundreds of references to 'object'.

Are any of them objects in the sense of object oriented programming?

I'm pretty sure the answer to that is No. C is widely agreed to *not* be an
object oriented language, although obviously you can construct an OOP
system in C.

It is difficult to give a single, unconditional definition of "object" in
the object-oriented programming sense, because there are many subtle
variations. We can consume many hours in fruitless debates over an exact
formal definition of "object" in the sense of OOP, but I don't think that
is productive. But I think this should cover most of the common cases:


* An object-oriented programming language is one which provides objects 
  as a native data type;

* objects are structured entities which combine:

  - behaviour (methods)
  - state (data, value)
  - and identity (unique existence);

* the structure and behaviour of the object is inherited from a 
  class (blueprint or template), or a prototype (another object).


The important thing is that the language provides these as ready-to-use
features, complete with syntax and support from the compiler/interpreter. I
could write OOP-style code in C, or even assembly language, but only by
writing my own framework, then taking care to only write code within the
boundaries of that framework. Hence, C is not OOP: objects aren't built-in
to C, but have to be added.


> C objects are also linked to a type but it doesn't need to be explicit
> /in the run-time data/ because it's a static language. The compiler
> knows all the types because there are explicit annotations in the source
> code.

OOP can exist in both statically typed languages (such as Java, C++,
Objective C) and dynamically typed languages (such as Python, Javascript,
Ruby).


>> In the programming language Java, *some* values are objects, and some
>> values are not objects.
>>
>> In the programming language Python, *all* values are objects, in the
>> general sense. That is what we mean by "Everything is an object".
> 
> In a dynamically typed language such as Python, you need to be able to
> deal with values consistently whatever their type, simply because you
> can't tell what the types are from source code. (Not without a lot of
> work which Python doesn't attempt, although RPython might do so.) Example:
> 
>   print (a)
> 
> a might be the int 42, or a it might be a million-element list. So both
> are wrapped up as 'objects'.

Again, this is not relevant. Javascript is dynamically typed, but some
values are machine primitives and other values are objects. The interpreter
keeps track of this at runtime.

Java is similar, except it keeps track if the difference between boxed and
unboxed types at compile time.


> Java is statically typed which makes it possible to treat instance
> variables differently without needing to examine their types at runtime.
> If you define 'object' in a certain way (eg. as boxed, tagged data),
> then it follows that some values don't need to be objects.

I'm not sure what point you are trying to make here.



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should "self" be changed?

2015-06-02 Thread Steven D'Aprano
On Fri, 29 May 2015 12:00 pm, Steven D'Aprano wrote:

[...]
> in a language where classes are 
> themselves values, there is no reason why a class must be instantiated,
> particularly if you're only using a single instance of the class. Anyone
> ever come across a named design pattern that involves using classes
> directly without instantiating them?
> 
> I'm basically looking for a less inelegant term for "instanceless class"
> -- not so much a singleton as a zeroton.

C# has these, and calls them static classes.

https://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.100%29.aspx




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What use of string module?

2015-06-02 Thread Tim Chase
On 2015-06-02 04:37, Mark Lawrence wrote:
> > I read the online help about string. It lists string constants,
> > string formatting, template strings and string functions. After
> > reading these, I am still puzzled about how to use the string
> > module.
> 
> I suggest you don't bother, it's effectively dead having been
> replaced by string methods.

While most of the functions in the string module are obsoleted by the
methods on strings, I still find the constants useful to save myself
from my own inability to type, possibly omitting letters from the
alphabet or doubling them up.  I'd much rather just reference
string.printable than try to recreate it (or its kin) myself.

-tkc



-- 
https://mail.python.org/mailman/listinfo/python-list


Find in ipython3

2015-06-02 Thread Cecil Westerhof
I am thinking about using ipython3 instead of bash. When I want to
find a file I can do the following:
!find ~ -iname '*python*.pdf'
but is there a python way?

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Parser needed.

2015-06-02 Thread MRAB

On 2015-06-02 05:45, Skybuck Flying wrote:

Example for python:

MyString = "Hello World"

print MyString.rfind("World")
if MyString.rfind("World"):
print "yes"
else:
print "no"

Pretty cool.


.rfind returns the index if found, -1 if not found.

"World".rfind("World") returns 0, which will be treated as false.

"foo".rfind("World") returns -1, which will be treated as true.

--
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Jon Ribbens
On 2015-06-02, Marko Rauhamaa  wrote:
> Skip Montanaro :
>
>> On Tue, Jun 2, 2015 at 10:28 AM, Marko Rauhamaa  wrote:
>>>
>>> The only problem is that you don't know how high you need to go in
>>> general.
>>
>> Sure, but I didn't know anyway, so no matter what upper bound I choose
>> (or what function I choose/implement), it's just going to be a guess.
>> os.closerange just codifies the straightforward procedure.
>
> Under linux, the cleanest way seems to be going through the files under
> /proc/self/fd:
>
> def close_fds(leave_open=[0, 1, 2]):
> fds = os.listdir(b'/proc/self/fd')
> for fdn in fds:
> fd = int(fdn)
> if fd not in leave_open:
> os.close(fd)
>
> No need for a upper bound.

Or use the more generic code that I already posted in this thread:

  def closeall(min=0, max=4096, keep=()):
  """Close all open file descriptors except for the given exceptions.

  Any file descriptors below or equal to `min`, or in the set `keep`
  will not be closed. Any file descriptors above `max` *might* not be
  closed.
  """
  # First try /proc/self/pid
  try:
  for fd in os.listdir("/proc/self/fd"):
  try:
  fd = int(fd)
  except ValueError:
  continue
  if fd >= min and fd not in keep:
  os.close(int(fd))
  return
  except OSError as exc:
  if exc[0] != errno.ENOENT:
  raise
  # If /proc was not available, fall back to closing a lot of descriptors.
  for fd in range(min, max):
  if fd not in keep:
  try:
  os.close(fd)
  except OSError as exc:
  if exc[0] != errno.EBADF:
  raise

This function could use os.closerange(), but if the documentation is
correct and it ignores *all* errors and not just EBADF, then it
sounds like os.closerange() should not in fact ever be used for any
purpose.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Marko Rauhamaa
Skip Montanaro :

> On Tue, Jun 2, 2015 at 10:28 AM, Marko Rauhamaa  wrote:
>>
>> The only problem is that you don't know how high you need to go in
>> general.
>
> Sure, but I didn't know anyway, so no matter what upper bound I choose
> (or what function I choose/implement), it's just going to be a guess.
> os.closerange just codifies the straightforward procedure.

Under linux, the cleanest way seems to be going through the files under
/proc/self/fd:

def close_fds(leave_open=[0, 1, 2]):
fds = os.listdir(b'/proc/self/fd')
for fdn in fds:
fd = int(fdn)
if fd not in leave_open:
os.close(fd)

No need for a upper bound.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Terry Reedy

On 6/2/2015 6:36 AM, Eddilbert Macharia wrote:


you guys are just confusing me, you are going in loops,


Ignore the troll who is trying to confuse you by slandering the rest of 
us.  I have been using python for 18 years, I believe. Current Python 
has a loop at the core


>>> isinstance(type, object)
True
>>> isinstance(object, type)
True

For using python, you hardly need to know this. (It obviously was not 
true before 'object' was added in 2.2.)  The interpreter creates this 
loop on startup with code similar to the following, except that it does 
so with classes rather than lists.


>>> lob = []
>>> l0 = []
>>> l1 = [l0]
>>> l0.append(l1)
>>> l0 in l1
True
>>> l1 in l0
True

> and still i have understood ,what makes everything in python an object.

Guido's decision to make python be that way.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 8:38:42 PM UTC+5:30, Steven D'Aprano wrote:
> On Tue, 2 Jun 2015 09:40 pm, Rustom Mody wrote:
> 
> > On Tuesday, June 2, 2015 at 4:57:31 PM UTC+5:30, Steven D'Aprano wrote:
> >> On Tue, 2 Jun 2015 08:36 pm, Eddilbert Macharia wrote:
> [...]
> >> > *** The instance of class type is a data type an instance of class
> >> > type. right ?
> >>  type(type)
> >> > 
> >> 
> >> type has many instances, not just one.
> > 
> > Not sure what you are trying to emphasize by the 'not just one'
> 
> The OP says "THE [emphasis added] instance of class type" -- type has more
> than one instance.
> 
> 

Ok

> > In particular the issubclass relation is transitive
> > Whereas the isinstance is not
> 
> Why is that relevant?

One way of construing the emphasized plural was what I pointed out as not the 
case
∀x • isinstance(x,t)
-- true or t = object but not t = type
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Framework / CMS for Banking

2015-06-02 Thread Laura Creighton
In a message of Tue, 02 Jun 2015 21:09:48 +0530, Swapnil writes:
>
>
>Respected: Thanks. Would you mind if , i ask you more detail Q’s on the 
>framework. If not then any resources where i can i ask more Q’s ?
>
>Best
>Dr. Swapnil Bhadade

You can ask more questions here.  I just remembered that there was
a Europython talk on the very question you asked.  You might try
emailing the talk's author directly.

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Alain Ketterlin
Skip Montanaro  writes:

> Reviving (and concluding) a thread I started a couple weeks ago, I asked:
>
>> The basic fork/exec dance is not a problem, but how do I discover
>> all the open file descriptors in the new child process to make sure
>> they get closed? Do I simply start at fd 3 and call os.close() on
>> everything up to some largish fd number?
>
> I wanted this again today (for different reasons than before).
> Googling for "python close all file descriptors" returned the os
> module docs as the first hit, and lo and behold, what do I see
> documented? os.closerange (new in 2.6):
>
> os.closerange(fd_low, fd_high)
> Close all file descriptors from fd_low (inclusive) to fd_high
> (exclusive), ignoring errors.

The close(2) manpage has the following warning on my Linux system:

| Not checking the return value of close() is a common  but  nevertheless
| serious  programming error.  It is quite possible that errors on a pre‐
| vious write(2) operation are first reported at the final close().   Not
| checking the return value when closing the file may lead to silent loss
| of data.  This can especially be observed with NFS and with disk quota.
| 

(I haven't followed the thread, but if your problem is to make sure fds
are closed on exec, you may be better off using the... close-on-exec
flag. Or simply do the bookkeeping.)

-- Alain.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Framework / CMS for Banking

2015-06-02 Thread Swapnil

Respected: Thanks. Would you mind if , i ask you more detail Q’s on the 
framework. If not then any resources where i can i ask more Q’s ?

Best
Dr. Swapnil Bhadade
M.B.B.S
M.S
Yindu (India)
swapnilrbhadad...@gmail.com.
………..
Please acknowledge receipt of this email.


The information in this e-mail is confidential and may be legally privileged. 
It is intended solely for the addressee. Access to this e-mail by anyone else 
is unauthorized. If you have received this communication in error, please 
address with the subject heading "Received in error," send to the original 
sender , then delete the e-mail and destroy any copies of it. If you are not 
the intended recipient, any disclosure, copying, distribution or any action 
taken or omitted to be taken in reliance on it, is prohibited and may be 
unlawful.



Please consider the environment before printing this email.
……...




> On 02-Jun-2015, at 19:35, Laura Creighton  wrote:
> 
> In a message of Tue, 02 Jun 2015 05:41:31 -0700, Swapnil Bhadade writes:
>> I am want to know which are the best CMS / framework for building web 
>> banking / Financial / lending services 
>> Best
>> -- 
>> https://mail.python.org/mailman/listinfo/python-list
> 
> See this video.
> https://ep2013.europython.eu/conference/talks/python-in-banks
> 
> Laura

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Skip Montanaro
On Tue, Jun 2, 2015 at 10:28 AM, Marko Rauhamaa  wrote:
>
> The only problem is that you don't know how high you need to go in
> general.

Sure, but I didn't know anyway, so no matter what upper bound I choose
(or what function I choose/implement), it's just going to be a guess.
os.closerange just codifies the straightforward procedure.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Marko Rauhamaa
Skip Montanaro :

> os.closerange(fd_low, fd_high)
> Close all file descriptors from fd_low (inclusive) to fd_high
> (exclusive), ignoring errors.
>
> Guido's time machine strikes again...

The only problem is that you don't know how high you need to go in
general.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Jean-Michel Pichavant
- Original Message -
> From: "acdr" 
> To: "Jean-Michel Pichavant" 
> Cc: python-list@python.org
> Sent: Tuesday, 2 June, 2015 4:00:12 PM
> Subject: Re: for...else
> 
> The first solution in your e-mail (with a Cleanup exception) is
> definitely very close, functionally, to what I want to accomplish. In
> effect, it's the same structure as my original suggestion of
> "for...then...else", except now it'd be "try: for...else...except".
> That's workable. I can even cheat and rename the Cleanup class to
> "Break" for clarity.
> 
> I'm guessing that there is not much support for functionality like
> this to be built in, in a much less verbose manner, like the
> "for...else" functionality? :P

By the way please don't top post in this list.

You're right the first solution is not that helpfull. I quite dislike try 
blocks. But I dislike "for else" even more. While "if else"  is a correct 
english construct and means something, "for else " is not (correct me if I'm 
wrong).

"for else" works perfectly, I just can never remember on which condition the 
else block is processed.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access the low digits of a list

2015-06-02 Thread Steven D'Aprano
On Tue, 2 Jun 2015 10:23 pm, fl wrote:

> I don't know whether there is a way to know the length of lines[3].

The same way as to know the length of anything else:

len(x)  # the length of x
len("hello")  # the length of "hello"
len(lines[3])  # the length of lines[3]

> Then, 
> I can use a -1 step to get the last two digits. Or, you may have much
> better ways to do that. Python is really too versatile I feel.

Last two digits of a string:

mystring = "123456"
mystring[-2:]


-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Ian Kelly
On Mon, Jun 1, 2015 at 4:59 PM, BartC  wrote:
> I'm developing a new language along the lines of Python, perhaps a brief
> description of how things are done there might help. Or just give a
> different perspective.
>
> Objects in this language are tagged: there's a code attached to each
> indicating what kind of data is stored. These codes are integers, or
> enumerations, for example:
>
>  Int =1
>  String = 2
>  List =   3
>  Class =  4
>
> And the following are examples of object instances with their tags:
>
> a is (Int,42)
> b is (String, "ABCXYZ")
> c is (List,   [10,20,30,40])
> d is (Class,  2 or )
>
> The last one might be tricky to grasp: it's really just a number, but one
> that represents a class or type (or tag). If printed, it could display
>  rather than just 2. (And when used to do something with the class,
> the 2 might be an index into a set of tables.)
>
> d is not /the/ class itself, but just a reference to it (this is pseudo-code
> not Python):
>
> print (b) =>  ABCXYZ
> print (typeof(b)) =>  String <2>
>
> print (d) =>  String <2>
> print (typeof(d)) =>  Class  <4>
> print (typeof(typeof(d))) =>  Class  <4>
>
> In my own language, the connection between class and type is hazy (I've only
> just added classes so it needs to be hazy until I understand them more).
>
> 'Type' includes everything, including all the built-in types such as the
> tags above, but also user-defined classes. In fact classes are the mechanism
> used to define new types. But with both designated by an integer within the
> same band (eg. built-int types 1 to 20, user-defined classes 21 and up), it
> is easier not to have a strong distinction ... at the moment.
>
> I haven't a root class yet that is the base of all the others. I don't think
> it's necessary internally to make things work. But it might be a useful
> concept in the language. Calling it 'object' however might give rise to
> confusion as 'object' is informally used to refer to instances. (I've never
> used OO but have picked up some of the jargon!)
>
> (This is almost certainly not how Python does things. Although the Python
> language doesn't go into details as to its implementation provided the
> behaviour is correct.)

It sounds quite similar to me. In CPython at least, every object has a
direct pointer to its type rather than an array index (which is
essentially just an offset from a pointer).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Steven D'Aprano
On Tue, 2 Jun 2015 09:40 pm, Rustom Mody wrote:

> On Tuesday, June 2, 2015 at 4:57:31 PM UTC+5:30, Steven D'Aprano wrote:
>> On Tue, 2 Jun 2015 08:36 pm, Eddilbert Macharia wrote:
[...]
>> > *** The instance of class type is a data type an instance of class
>> > type. right ?
>>  type(type)
>> > 
>> 
>> type has many instances, not just one.
> 
> Not sure what you are trying to emphasize by the 'not just one'

The OP says "THE [emphasis added] instance of class type" -- type has more
than one instance.


> In particular the issubclass relation is transitive
> Whereas the isinstance is not

Why is that relevant?


-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python.exe has stopped working

2015-06-02 Thread Alexis Dubois
On Tuesday, June 2, 2015 at 4:13:27 PM UTC+2, Laura Creighton wrote:
> In a message of Tue, 02 Jun 2015 06:09:34 -0700, Alexis Dubois writes:
> >Hello !
> >
> >I have this kind of message every time I quit my PyQt4 app whatever the 
> >method to quit is: a quit action menu, the windows "red cross", by quit(), 
> >close(), destroy(), deletelater(), ...
> >
> >"python.exe has stopped working"
> >->Check online for a solution
> >->Close the program
> >
> >I need to specify that the app is working nice, just have this message when 
> >quit.
> >Do you have an idea to help me understand this issue?
> >
> >Thanks in advance
> >Best regards
> >Alexis
> >-- 
> >https://mail.python.org/mailman/listinfo/python-list
> 
> You can override closeEvent
> 
> def closeEvent(self, event):
> QtGui.qApp.quit()
> event.ignore()
> 
> This just shuts it up, you may have more complicated things you want to do.
> 
> Laura

Thanks Laura,

Unfortunately, my closeEvent is already override as this:

def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit HWL?", QtGui.QMessageBox.Yes | 
QtGui.QMessageBox.No, QtGui.QMessageBox.No)

if reply == QtGui.QMessageBox.Yes:
app.quit()
else:
event.ignore()

Replacing app.quit() by QtGui.qApp.quit() doesn't change anything.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Laura Creighton
You may be looking for dictionary dispatching.

You can translate the key into a callable.

def do_ping(self, arg):
return 'Ping, {0}!'.format(arg)

def do_pong(self, arg):
return 'Pong, {0}!'.format(arg)

dispatch = {
'ping': do_ping,
'pong': do_pong
}

and then at some point do

dispatch[command](arg)

It is useful to know that tuples make perfectly good dictionary keys,
in case you need to store more state somewhere.

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access the low digits of a list

2015-06-02 Thread Ian Kelly
On Tue, Jun 2, 2015 at 6:35 AM, Rustom Mody  wrote:
> For that matter even this works
> But I am not sure whats happening or that I like it
>
 [x[-2:]  for x in lines]
> ['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']

x[-2:] selects all items in the sequence with index i such that len(x)
- 2 <= i < len(x). For a sequence of length 2 or less, that's the
entire sequence.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python.exe has stopped working

2015-06-02 Thread Laura Creighton
In a message of Tue, 02 Jun 2015 06:09:34 -0700, Alexis Dubois writes:
>Hello !
>
>I have this kind of message every time I quit my PyQt4 app whatever the method 
>to quit is: a quit action menu, the windows "red cross", by quit(), close(), 
>destroy(), deletelater(), ...
>
>"python.exe has stopped working"
>->Check online for a solution
>->Close the program
>
>I need to specify that the app is working nice, just have this message when 
>quit.
>Do you have an idea to help me understand this issue?
>
>Thanks in advance
>Best regards
>Alexis
>-- 
>https://mail.python.org/mailman/listinfo/python-list

You can override closeEvent

def closeEvent(self, event):
QtGui.qApp.quit()
event.ignore()

This just shuts it up, you may have more complicated things you want to do.

Laura



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Framework / CMS for Banking

2015-06-02 Thread Laura Creighton
In a message of Tue, 02 Jun 2015 05:41:31 -0700, Swapnil Bhadade writes:
> I am want to know which are the best CMS / framework for building web banking 
> / Financial / lending services 
>Best
>-- 
>https://mail.python.org/mailman/listinfo/python-list

See this video.
https://ep2013.europython.eu/conference/talks/python-in-banks

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread acdr
The first solution in your e-mail (with a Cleanup exception) is
definitely very close, functionally, to what I want to accomplish. In
effect, it's the same structure as my original suggestion of
"for...then...else", except now it'd be "try: for...else...except".
That's workable. I can even cheat and rename the Cleanup class to
"Break" for clarity.

I'm guessing that there is not much support for functionality like
this to be built in, in a much less verbose manner, like the
"for...else" functionality? :P

On 6/2/15, Jean-Michel Pichavant  wrote:
> - Original Message -
>> From: "acdr" 
>> To: "Jean-Michel Pichavant" 
>> Cc: python-list@python.org
>> Sent: Tuesday, 2 June, 2015 2:52:21 PM
>> Subject: Re: for...else
>>
>> That would work for my example, but it would only really work if all
>> the calculations are in a nice function.
>
> You cannot blame me for considering the example you provided ;)
>
> What about this:
>
> class Cleanup(Exception): pass
>
> try:
>   for x in it:
> if c1():
>   raise Cleanup()
> c2()
> if c3():
>   raise Cleanup()
> except Cleanup:
>   #do the cleanup
>pass
>
> If you can make c1 c3 raise themselves Cleanup, it's even better.
>
> Now if you're able to write a cleanup function that can handle the case when
> there's nothing to clean, everything becomes crystal clear:
>
> from contextlib import contextmanager
>
> @contextmanager
> def cleanup():
>   yield
>   # here do the cleaning
>   print 'I am cleaning'
>
> def do_the_job():
>   if c1() : return
>   c2()
>   if c3() : return
>
> with cleanup():
>   do_the_job()
>
> JM
>
>
> -- IMPORTANT NOTICE:
>
> The contents of this email and any attachments are confidential and may also
> be privileged. If you are not the intended recipient, please notify the
> sender immediately and do not disclose the contents to any other person, use
> it for any purpose, or store or copy the information in any medium. Thank
> you.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fork/exec & close file descriptors

2015-06-02 Thread Skip Montanaro
Reviving (and concluding) a thread I started a couple weeks ago, I asked:

> The basic fork/exec dance is not a problem, but how do I discover
> all the open file descriptors in the new child process to make sure
> they get closed? Do I simply start at fd 3 and call os.close() on
> everything up to some largish fd number?

I wanted this again today (for different reasons than before).
Googling for "python close all file descriptors" returned the os
module docs as the first hit, and lo and behold, what do I see
documented? os.closerange (new in 2.6):

os.closerange(fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high
(exclusive), ignoring errors.

Guido's time machine strikes again...

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Jean-Michel Pichavant
- Original Message -
> From: "acdr" 
> To: "Jean-Michel Pichavant" 
> Cc: python-list@python.org
> Sent: Tuesday, 2 June, 2015 2:52:21 PM
> Subject: Re: for...else
> 
> That would work for my example, but it would only really work if all
> the calculations are in a nice function. 

You cannot blame me for considering the example you provided ;)

What about this:

class Cleanup(Exception): pass

try:
  for x in it:
if c1():
  raise Cleanup()
c2()
if c3():
  raise Cleanup()
except Cleanup:
  #do the cleanup
   pass

If you can make c1 c3 raise themselves Cleanup, it's even better.

Now if you're able to write a cleanup function that can handle the case when 
there's nothing to clean, everything becomes crystal clear:

from contextlib import contextmanager

@contextmanager
def cleanup():
  yield
  # here do the cleaning
  print 'I am cleaning'

def do_the_job():
  if c1() : return
  c2()
  if c3() : return

with cleanup():
  do_the_job()

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Parser needed.

2015-06-02 Thread Grant Edwards
On 2015-06-02, Skybuck Flying  wrote:

>
> {
> 
> 
>{
>
>}
> }

IOW, it's almost, but not quite, JSON.

-- 
Grant Edwards   grant.b.edwardsYow! My vaseline is
  at   RUNNING...
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Marko Rauhamaa
BartC :

> If you define 'object' in a certain way (eg. as boxed, tagged data),
> then it follows that some values don't need to be objects.

The word "object" really barely carries any meaning -- that's the point.
It's a Latin-based synonym of the Germanic "thing."

To say that everything is an object in Python simply means that the same
set of concepts applies to all data. The main distinguishing feature
between Python objects is mutability.

The utmost abstraction of everything into an object is the pinnacle of
understanding. The question is, should a beginning Python programmer
start the climb from the summit or from the root of the mountain. IOW,
does it help to start the Python journey by learning that numbers are
objects, given that the language gives lots of special treatment to
numbers (as well as strings, lists and functions, for example)?

I would imagine that the gentlest route to Python programming starts
without talking much about objects at all. Leave the discussion about
numbers as objects till after, say, multiple inheritance has been
covered. Then, things like strings as objects and regular expression
match objects can be brought in naturally, and expressions like

   ','.join(person.name
for person in persons
if person.is_underage())

no longer defy comprehension.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Python.exe has stopped working

2015-06-02 Thread Alexis Dubois
Hello !

I have this kind of message every time I quit my PyQt4 app whatever the method 
to quit is: a quit action menu, the windows "red cross", by quit(), close(), 
destroy(), deletelater(), ...

"python.exe has stopped working"
->Check online for a solution
->Close the program

I need to specify that the app is working nice, just have this message when 
quit.
Do you have an idea to help me understand this issue?

Thanks in advance
Best regards
Alexis
-- 
https://mail.python.org/mailman/listinfo/python-list



Re: for...else

2015-06-02 Thread acdr
That would work for my example, but it would only really work if all
the calculations are in a nice function. If I just have a block of
code, then I can't use it as easily. (E.g. replace
"complicated_calculation_2()" by multiple lines of code, which I don't
want to shove into a separate function.)

On 6/2/15, Jean-Michel Pichavant  wrote:
> - Original Message -
>> From: "acdr" 
>> To: python-list@python.org
>> Sent: Tuesday, 2 June, 2015 1:26:42 PM
>> Subject: for...else
>>
>> Hi,
>>
>> Currently, in various places in my code, I have the equivalent of:
>>
>> for x in it:
>> if complicated_calculation_1():
>> cleanup()
>> break
>> complicated_calculation_2()
>> if complicated_calculation_3():
>> cleanup()
>> break
>
> Hi
>
> With the following layout, adding calculation steps is just a matter of
> adding a line
>
> for x ion it:
>   for calc, cbk in [
> (complicated_calculation_1, cleanup),
> (complicated_calculation_2, None),
> (complicated_calculation_3, cleanup),
>   ]:
> if calc() and cbk:
>   cbk()
>   break
>
> It might give you ideas.
>
> JM
>
>
> -- IMPORTANT NOTICE:
>
> The contents of this email and any attachments are confidential and may also
> be privileged. If you are not the intended recipient, please notify the
> sender immediately and do not disclose the contents to any other person, use
> it for any purpose, or store or copy the information in any medium. Thank
> you.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread BartC

On 02/06/2015 12:27, Steven D'Aprano wrote:


"Object" has a general meaning in computer science and programming, it is a
compound data structure that is explicitly linked to a type which provides
functionality that operates on that data structure.

In the programming language C, *no* values are objects. C has types (int16,
uint32, bool, and many more) but no objects.


The C Standard has hundreds of references to 'object'.

C objects are also linked to a type but it doesn't need to be explicit 
/in the run-time data/ because it's a static language. The compiler 
knows all the types because there are explicit annotations in the source 
code.



In the programming language Java, *some* values are objects, and some values
are not objects.

In the programming language Python, *all* values are objects, in the general
sense. That is what we mean by "Everything is an object".


In a dynamically typed language such as Python, you need to be able to 
deal with values consistently whatever their type, simply because you 
can't tell what the types are from source code. (Not without a lot of 
work which Python doesn't attempt, although RPython might do so.) Example:


 print (a)

a might be the int 42, or a it might be a million-element list. So both 
are wrapped up as 'objects'.


Java is statically typed which makes it possible to treat instance 
variables differently without needing to examine their types at runtime. 
If you define 'object' in a certain way (eg. as boxed, tagged data), 
then it follows that some values don't need to be objects.


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Framework / CMS for Banking

2015-06-02 Thread Swapnil Bhadade
 I am want to know which are the best CMS / framework for building web banking 
/ Financial / lending services 
Best
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access the low digits of a list

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 5:53:34 PM UTC+5:30, fl wrote:
> Hi,
> 
> I have a list:
> 
> 
> 
> 
> 
> 
> >>> lines
> ['12', '42', '49', '156', '225', '36', '49', '164', '11181', '3100']
> 
> 
> 
> I want to access the last two digits. That is:
> 
> ['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
> 
> 
> When I try to use lines[3][0] is '1'
> lines[3][1] is '5'
> lines[3][2] is '6'
> 
> 
> I don't know whether there is a way to know the length of lines[3]. Then, I
> can use a -1 step to get the last two digits. Or, you may have much better 
> ways to do that. Python is really too versatile I feel.

len(lines[3])  ??

You can do this: [Hope I am not doing your homework!]

>>> [(x[-2:] if len(x) > 2 else x)  for x in lines]
['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
>>> 

For that matter even this works
But I am not sure whats happening or that I like it

>>> [x[-2:]  for x in lines]
['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Jean-Michel Pichavant
- Original Message -
> From: "acdr" 
> To: python-list@python.org
> Sent: Tuesday, 2 June, 2015 1:26:42 PM
> Subject: for...else
> 
> Hi,
> 
> Currently, in various places in my code, I have the equivalent of:
> 
> for x in it:
> if complicated_calculation_1():
> cleanup()
> break
> complicated_calculation_2()
> if complicated_calculation_3():
> cleanup()
> break

Hi

With the following layout, adding calculation steps is just a matter of adding 
a line

for x ion it:
  for calc, cbk in [
(complicated_calculation_1, cleanup),
(complicated_calculation_2, None),
(complicated_calculation_3, cleanup),
  ]:
if calc() and cbk:
  cbk()
  break
  
It might give you ideas.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access the low digits of a list

2015-06-02 Thread Frank Stutzman
fl  wrote:

---snip
 lines
> ['12', '42', '49', '156', '225', '36', '49', '164', '11181', '3100']
> 
> 
> 
> I want to access the last two digits. That is:
> 
> ['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
> 
> 
> When I try to use lines[3][0] is '1'
> lines[3][1] is '5'
> lines[3][2] is '6'

Is there something wrong with using:
   lines[3][-2:]
   

-- 
Frank Stutzman

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access the low digits of a list

2015-06-02 Thread Joel Goldstick
On Tue, Jun 2, 2015 at 8:23 AM, fl  wrote:
> Hi,
>
> I have a list:
>
>
>
>
>
>
 lines
> ['12', '42', '49', '156', '225', '36', '49', '164', '11181', '3100']
>
>
>
> I want to access the last two digits. That is:
>
> ['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']
>
>
> When I try to use lines[3][0] is '1'
> lines[3][1] is '5'
> lines[3][2] is '6'
>
>
> I don't know whether there is a way to know the length of lines[3]. Then, I
> can use a -1 step to get the last two digits. Or, you may have much better
> ways to do that. Python is really too versatile I feel.
>
> Thanks,
> --
> https://mail.python.org/mailman/listinfo/python-list

You should read about slices

lines[3][-2:]  will give the last two characters in the 3rd group
(starting from 0)

The notation means to start with 2 from the end, and proceed to the end


-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Peter Otten
acdr wrote:

> Hi,
> 
> Currently, in various places in my code, I have the equivalent of:
> 
> for x in it:
> if complicated_calculation_1():
> cleanup()
> break
> complicated_calculation_2()
> if complicated_calculation_3():
> cleanup()
> break
> 
> Obviously, I'm repeating myself by having two separate calls to
> cleanup(). I can't really see a nicer way to do this. (Though I see
> plenty of non-nice ways to do this, such as adding "broken = True" in
> front of every "break", and then after the loop is done, have an "if
> broken" section.) Other solutions that I'm not particularly fond of
> can be found on stackexchange, where someone else is trying to do the
> same thing:
> http://stackoverflow.com/questions/3296044/opposite-of-python-for-else

Perhaps you like of these:

for x in it:
if not complicated_calculation_1():
complicated_calculation_2()
if not complicated_calculation_3():
continue
cleanup()
break

def f():
for x in it:
if complicated_calculation_1():
break
complicated_calculation_2()
if complicated_calculation_3():
break
else:
return
cleanup()

> I'm wondering if there is a demand for expanding the "for...else"
> functionality to be expanded also have a block of code that only gets
> called if the loop is broken out of. I.e.:
> 
> for x in it:
> ...
> then:
> # "break" was called
> ...
> else:
> # "break was not called
> ...

You may not like using a flag, but it's a really obvious approach and the 
situations where it's necessary are not very common. Apart from indentation-
based blocks Python is very middle-of-the-road, so I'd ask if there is an 
existing language that has such a feature, and if yes, is it used 
frequently? I suspect that there are many Python programmers that have never 
even used (for...else).

Python the language is already becoming too complicated for my taste; I 
would rather not add more constructs where there is no significant 
advantage. 


-- 
https://mail.python.org/mailman/listinfo/python-list


How to access the low digits of a list

2015-06-02 Thread fl
Hi,

I have a list:






>>> lines
['12', '42', '49', '156', '225', '36', '49', '164', '11181', '3100']



I want to access the last two digits. That is:

['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']


When I try to use lines[3][0] is '1'
lines[3][1] is '5'
lines[3][2] is '6'


I don't know whether there is a way to know the length of lines[3]. Then, I
can use a -1 step to get the last two digits. Or, you may have much better 
ways to do that. Python is really too versatile I feel.

Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Knowledge Requirements for Machine Learning (SKLearn)

2015-06-02 Thread chrismeek4542
Thank you both. Just what i was looking for
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for...else

2015-06-02 Thread Todd
I think there is essentially zero chance of that.  My understanding is that
Guido regrets having "else" to begin with.

But this should work

broken = True
for x in it:
if complicated_calculation_1():
break
complicated_calculation_2()
if complicated_calculation_3():
break
else:
broken = False
if broken:
cleanup()


On Tue, Jun 2, 2015 at 1:26 PM, acdr  wrote:

> Hi,
>
> Currently, in various places in my code, I have the equivalent of:
>
> for x in it:
> if complicated_calculation_1():
> cleanup()
> break
> complicated_calculation_2()
> if complicated_calculation_3():
> cleanup()
> break
>
> Obviously, I'm repeating myself by having two separate calls to
> cleanup(). I can't really see a nicer way to do this. (Though I see
> plenty of non-nice ways to do this, such as adding "broken = True" in
> front of every "break", and then after the loop is done, have an "if
> broken" section.) Other solutions that I'm not particularly fond of
> can be found on stackexchange, where someone else is trying to do the
> same thing:
> http://stackoverflow.com/questions/3296044/opposite-of-python-for-else
>
> I'm wondering if there is a demand for expanding the "for...else"
> functionality to be expanded also have a block of code that only gets
> called if the loop is broken out of. I.e.:
>
> for x in it:
> ...
> then:
> # "break" was called
> ...
> else:
> # "break was not called
> ...
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 4:57:31 PM UTC+5:30, Steven D'Aprano wrote:
> On Tue, 2 Jun 2015 08:36 pm, Eddilbert Macharia wrote:
> 
> > you guys are just confusing me, you are going in loops, and still i have
> > understood ,what makes everything in python an object. hey is where i'm at
> > : *** type in python refers to data types e.g. int, str, boolean e.t.c.
> > right ?
> 
> Yes. Also classes you create with the "class" keyword:
> 
> class K(object):
> ...
> 
> K is now a "type", just like int, str, list, object, etc.
> 
> 
> > *** The interpreter creates two classes type and object when setting up a
> > python environment. right ?
> 
> Many more than just two: it also creates list, str, dict, etc. But *first*
> it has to create type and object. So you are correct.
> 
> 
> > *** The creator (metaclass) of all data types (i.e. int,str) in python is
> > the class type. right ?
> 
> Correct.
> 
> [Aside: I'm only talking about Python 3 here. In Python 2 there is also a
> second hierarchy of classes, called "classic classes" or "old-style
> classes", which are *not* subclasses of type. But let's just ignore them,
> because they are gone in the most recent versions of Python.]
> 
> 
>  isinstance(int,type)
> > True
> > 
> > *** The instance of class type is a data type an instance of class type.
> > right ?
>  type(type)
> > 
> 
> type has many instances, not just one.

Not sure what you are trying to emphasize by the 'not just one'
In particular the issubclass relation is transitive
Whereas the isinstance is not

>>> isinstance(2,int)
True
>>> isinstance(int,type)
True
>>> isinstance(2,type)
False
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Steven D'Aprano
On Tue, 2 Jun 2015 08:36 pm, Eddilbert Macharia wrote:

> you guys are just confusing me, you are going in loops, and still i have
> understood ,what makes everything in python an object. hey is where i'm at
> : *** type in python refers to data types e.g. int, str, boolean e.t.c.
> right ?

Yes. Also classes you create with the "class" keyword:

class K(object):
...

K is now a "type", just like int, str, list, object, etc.


> *** The interpreter creates two classes type and object when setting up a
> python environment. right ?

Many more than just two: it also creates list, str, dict, etc. But *first*
it has to create type and object. So you are correct.


> *** The creator (metaclass) of all data types (i.e. int,str) in python is
> the class type. right ?

Correct.

[Aside: I'm only talking about Python 3 here. In Python 2 there is also a
second hierarchy of classes, called "classic classes" or "old-style
classes", which are *not* subclasses of type. But let's just ignore them,
because they are gone in the most recent versions of Python.]


 isinstance(int,type)
> True
> 
> *** The instance of class type is a data type an instance of class type.
> right ?
 type(type)
> 

type has many instances, not just one.

Instances of int are individual ints, like 0, 1, 2, 3, ...

Instances of type are individual types, like int, dict, str, list, ...

But one of those many instances of type is, yes, type itself! So *one* of
the instances of type is type, which is also an instance of itself:

 isinstance(type,type)
> True

Correct. This makes type special. Most types are *not* instances of
themselves:

py> isinstance(int, int)
False


> *** Class type gets some of its behavior from class object through
> inheritance.right ?
> 
 issubclass(type,object)
> True

Correct.


> *** instance of class object is type, in the sense it created using class
> type which inherits from class object.right ?
> 
 isinstance(object,type)
> True
 isinstance(object,object)
> True
> 
> so is it right to say, everything in python is an object because they
> are instance of the class type which inherits from class object ?

No! That's not what we mean when we say "everything is an object".

Eddilbert, have you programmed in any other languages? It would help you
understand if you have.

"Object" has a general meaning in computer science and programming, it is a
compound data structure that is explicitly linked to a type which provides
functionality that operates on that data structure.

In the programming language C, *no* values are objects. C has types (int16,
uint32, bool, and many more) but no objects.

In the programming language Java, *some* values are objects, and some values
are not objects.

In the programming language Python, *all* values are objects, in the general
sense. That is what we mean by "Everything is an object".

Let's go back in time about 15 years or so. We're now using Python 1.5. In
Python 1.5, there is no built-in object, and type is just a function, not a
class:

>>> import sys
>>> print sys.version
1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)]
>>> object
Traceback (innermost last):
  File "", line 1, in ?
NameError: object
>>> type



In Python 1.5, classes you create do not inherit from object, because object
does not exist! BUT even in Python 1.5, it is true that everything is an
object.

Remember, "object" can refer to two things:

- *specifically* the class called "object";

- the *general concept* of objects, from object oriented programming.


In Python 1.5:

- everything is an object [the general concept]

- nothing is an instance of the class called "object"


In Python 2:

- everything is an object [the general concept]

- some things, but not all things, are instances of the class
  called "object"


In Python 3:

- everything is an object [the general concept]

- everything is an instance of the class called "object"




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


for...else

2015-06-02 Thread acdr
Hi,

Currently, in various places in my code, I have the equivalent of:

for x in it:
if complicated_calculation_1():
cleanup()
break
complicated_calculation_2()
if complicated_calculation_3():
cleanup()
break

Obviously, I'm repeating myself by having two separate calls to
cleanup(). I can't really see a nicer way to do this. (Though I see
plenty of non-nice ways to do this, such as adding "broken = True" in
front of every "break", and then after the loop is done, have an "if
broken" section.) Other solutions that I'm not particularly fond of
can be found on stackexchange, where someone else is trying to do the
same thing:
http://stackoverflow.com/questions/3296044/opposite-of-python-for-else

I'm wondering if there is a demand for expanding the "for...else"
functionality to be expanded also have a block of code that only gets
called if the loop is broken out of. I.e.:

for x in it:
...
then:
# "break" was called
...
else:
# "break was not called
...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 4:16:02 PM UTC+5:30, BartC wrote:
> On 01/06/2015 23:59, BartC wrote:
> 
> >> In the new class style, type and class sort of mean the same thing.
> >
> > I'm developing a new language along the lines of Python,
> 
> (After reading some of the rest of the sub-thread, I'm glad I reined in 
> some of the proposed changes to my existing language to make it more 
> Python-like.
> 
> If my simple, no-nonsense approach can avoid discussions about 
> philosophy, religion and meta-physics (or whatever the hell the 
> sub-thread was about) then that must be a good thing!)

What is good that each one can only decide in his own private space.
What is historical is public and studying that history would show that
these questions are central to the existence of our field,
[Mark's views nowithstanding]
http://blog.languager.org/2015/03/cs-history-0.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Mark Lawrence

On 02/06/2015 11:36, Eddilbert Macharia wrote:


you guys are just confusing me, you are going in loops, and still i have 
understood ,what makes everything in python an object.


After 14 or more years writing Python I can't really answer that and 
quite frankly it doesn't worry me as I can quite happily write working 
code, what with practicality beating purity and all that.  Does it worry 
you that much?


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread BartC

On 01/06/2015 23:59, BartC wrote:


In the new class style, type and class sort of mean the same thing.


I'm developing a new language along the lines of Python,


(After reading some of the rest of the sub-thread, I'm glad I reined in 
some of the proposed changes to my existing language to make it more 
Python-like.


If my simple, no-nonsense approach can avoid discussions about 
philosophy, religion and meta-physics (or whatever the hell the 
sub-thread was about) then that must be a good thing!)


--
Bartc

--
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Eddilbert Macharia
On Sunday, May 31, 2015 at 5:34:20 PM UTC+3, Eddilbert Macharia wrote:
> Hello All ,
> 
> I'm wrecking my head trying to understand. where the class object comes into 
> play . 
> 
> Is it only meant to act as base class and does it mean there is an actual 
> class called object in python which all the objects created using the class 
> type inherit ?
> 
> i'm assuming the metaclass if simplified would look something like this :
> 
> type('dict', (object,),{})
> 
> And when we use the class type as a metaclass are we using the instance 
> version of the class type or are we actually using the type class itself ?
> 
> Also when we say everything is an object in python, are we referring to the 
> fact that everything is an instance of the class type or does it have to with 
> the object class inherited ? 
> 
> As can be attested by using type() function as below :
> 
> >>> type(int)
> 
> >>> type(list)
> 
> >>> type(dict)
> 
> >>> type(type)
> 
> >>> type(object)
> 
> 
> From my understanding this means all of this are instances of the class type. 
> which means the class type was used to create this instances.
> 
> Now if i look at the __bases__ of all this objects i get :
> 
> >>> type.__base__
> 
> >>> type.__bases__
> (,)
> >>> dict.__bases__
> (,)
> >>> list.__bases__
> (,)
> >>> int.__bases__
> (,)
> >>> object.__bases__
> ()
> 
> This tells me that all of this objects inherit from the class object which 
> has nothing to do with them being instances.

you guys are just confusing me, you are going in loops, and still i have 
understood ,what makes everything in python an object.
hey is where i'm at :
*** type in python refers to data types e.g. int, str, boolean e.t.c. right ?

*** The interpreter creates two classes type and object when setting up a 
python environment. right ?

*** The creator (metaclass) of all data types (i.e. int,str) in python is the 
class type. right ?

>>> isinstance(int,type)
True

*** The instance of class type is a data type an instance of class type. right ?
>>> type(type)

>>> isinstance(type,type)
True


*** Class type gets some of its behavior from class object through 
inheritance.right ?

>>> issubclass(type,object)
True

*** instance of class object is type, in the sense it created using class type 
which inherits from class object.right ?

>>> isinstance(object,type)
True
>>> isinstance(object,object)
True

so is it right to say, everything in python is an object because they are 
instance of the class type which inherits from class object ?

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Knowledge Requirements for Machine Learning (SKLearn)

2015-06-02 Thread Laura Creighton
https://www.udacity.com/course/intro-to-machine-learning--ud120

Free online course using Python.

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Knowledge Requirements for Machine Learning (SKLearn)

2015-06-02 Thread Fabien

On 06/02/2015 11:16 AM, chrismeek4...@gmail.com wrote:

I would like to get into Machine learning.


An Introduction to Statistical Learning:
http://www-bcf.usc.edu/~gareth/ISL/

and corresponding MOOC.

SKLearn and Statsmodels mailing lists:
http://dir.gmane.org/gmane.comp.python.scikit-learn
http://dir.gmane.org/gmane.comp.python.pystatsmodels

Cheers,

Fabien

--
https://mail.python.org/mailman/listinfo/python-list


Re: What use of string module?

2015-06-02 Thread Laura Creighton
In a message of Mon, 01 Jun 2015 19:14:18 -0700, fl writes:
>Hi,
>
>I read the online help about string. It lists string constants, string 
>formatting, template strings and string functions. After reading these,
>I am still puzzled about how to use the string module. 
>
>Could you show me a few example about this module?
>
>Thanks

A long time ago, strings didn't have the methods they had now.
So the string module was created, so that people could all have
a common way to do some really common things that people like
to do with strings.  Now the strings have object methods to
do the same thing, so you don't really want to use it.

It's there for backwards compatibility.  You don't want all the
code that exists out there and uses it to all stop working one
day because we now have a better way to do it. :)

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Marko Rauhamaa
Chris Angelico :

> On Tue, Jun 2, 2015 at 5:44 PM, Rustom Mody  wrote:
>> 1 ∈ all these
>> Are the '∈'s here same?  Similar?
>
> Yes, they are. Every one of them is asserting (or asking, depending on
> your point of view) whether or not the instance to its left is a
> member of the set to its right. The sets on the right are all
> different, but the set membership operation is identical.

That is the risk of taking classes into Python. People start to obsess
about membership and ontological relationships. I think you should use
the type() function only for troubleshooting and isinstance() virtually
never.

I think objects should be understood only through their operational
semantics, ie, their methods. It doesn't matter what an object is; what
matters is what it does. Don't test it, just call it.

Yeah, I'm preaching to the choir:

   Alex Martelli made an early (2000) use of the term in a message to
   the comp.lang.python newsgroup:

   In other words, don't check whether it IS-a duck: check whether
   it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on
   exactly what subset of duck-like behaviour you need to play your
   language-games with.

   http://en.wikipedia.org/wiki/Duck_typing>


Marko

PS I have written code that violates my stated rule. For example, an
argument could be a string or a list of strings for convenience.
However, this kind of testing should not be performed on anything
created with the "class" keyword. IOW, some types *are* more primitive
than others -- in our minds and in practical use.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 2:08:08 PM UTC+5:30, Chris Angelico wrote:
> On Tue, Jun 2, 2015 at 5:44 PM, Rustom Mody wrote:
> >> Plates and spoons and knives and forks are objects.
> >> Cars and trucks and ships and planes are objects.
> >> Books and shoes and maps and compasses are objects.
> >> Buildings are objects.
> >> And blueprints of buildings are objects too.
> >
> > You are using 'are' as if they are all the same 'are'. Are they?
> > Consider the type int.
> > It is supposed to model mathematical integers.
> > ie 1 ∈ int (in some sense)
> >
> > Consider the generator
> > def int2():
> >   i = 0
> >   yield i
> >   while True:
> > yield i
> > yield -i
> >
> > 1 ∈ int2 [Not to mention 1 ∈ int2()]
> >
> > Consider range(10) (in python2 and 3)
> > And finally [1,2,3,4]
> >
> > 1 ∈ all these
> > Are the '∈'s here same?  Similar?
> 
> Yes, they are. Every one of them is asserting (or asking, depending on
> your point of view) whether or not the instance to its left is a
> member of the set to its right. The sets on the right are all
> different, but the set membership operation is identical.
> 
> But even more so: The original collection of statements ("are
> objects") all used the same RHS. In exactly the same senses, all of
> those examples were testing for the same "objectness". (Although you
> could argue that Steven's examples were talking about subclass
> relationships rather than instance relationships, but really, an
> instanceof relationship is a special case of subclass, where the class
> on the left is defined by some form of object identity. Stating "All
> books are objects" is a subclass relationship; stating "This book is
> an object" is an instanceof relationship; both assertions use the same
> meaning of "object(s)".)
> 
> All shoes are objects.
> All ships are objects.
> All lumps of sealing-wax are objects.
> All cabbages are objects.
> All kings are objects. (Some kings are also subjects, but not many.)
> 
> I can pick up a shoe, I can look at it, I can verify that it has
> certain attributes common to all objects (location, mass, etc).
> Superman can do the same with a ship (they're a bit big for me to pick
> up). The actions you can perform on all objects are the attributes of
> objects in general. Some subclasses of object may provide additional
> actions (you can tip a king, for instance), but you can still do all
> of these actions, so they're all the same type of object.
> 
> Note that not one iota of this has anything to do with Python's
> documentation, its rules, its behaviour, or anything. Python follows
> the natural expectations of our universe. The standard actions that
> can be performed on Python objects are slightly different from the
> standard actions that can be performed in Dungeons and Dragons, and
> different again from the standard actions of the world we live in, but
> they are no less applicable to all objects in that hierarchy:
> 
> * You can bind a name to an object (any object).
> * You can pass an object as a function parameter.
> * You can return an object from a function.
> * You can reference objects in other objects' attributes.
> * You can distinguish one object from another (that is, objects have
> unique identities).
> 
> (In CPython, you can recognize an object by its GC header - an object
> invariably has a reference count and so on. This is not a fundamental
> attribute of objects, but it's a way to recognize them.)
> 
> Not everything that Python uses is an object. Syntax is not, itself,
> manipulable; you can represent a syntax tree with either source code
> (as a string) or an AST object, but syntax itself is not something you
> can grasp. You can't assign "foo = def" in Python. But anything that
> you can work with, in any way, is an object - and is an instance of
> (some subclass of) the type 'object'. So, yes: They ARE all the same
> meaning of "are" and "objects".

Lets take this practically.


>>> isinstance(1,int)
True
>>> 1 in [1,2,3]
True

>>> def int2():
...   i = 0
...   while True:
...yield i
...i += 1

>>> 1 in int2()
True
>>> 

>>> 1 in range(10)
True

4 True-returning python expressions.  5 if you consider that range in python 2 
and 3 are quite different.

Do you consider the computational processes evoked (in the CPython sources) by
these 4 statements to be the same?

[Hint: What does
>>> "shoes" in int2()
return?

And try to take care to distinguish computational from ontological answer
]
-- 
https://mail.python.org/mailman/listinfo/python-list


Knowledge Requirements for Machine Learning (SKLearn)

2015-06-02 Thread chrismeek4542
I would like to get into Machine learning. The problem I have is that my Math 
skills are sadly lacking. I went through SKlearn docs but it is beyond me. 
Could anyone recommended some resources to get up to speed with the subject?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Chris Angelico
On Tue, Jun 2, 2015 at 5:44 PM, Rustom Mody  wrote:
>> Plates and spoons and knives and forks are objects.
>> Cars and trucks and ships and planes are objects.
>> Books and shoes and maps and compasses are objects.
>> Buildings are objects.
>> And blueprints of buildings are objects too.
>
> You are using 'are' as if they are all the same 'are'. Are they?
> Consider the type int.
> It is supposed to model mathematical integers.
> ie 1 ∈ int (in some sense)
>
> Consider the generator
> def int2():
>   i = 0
>   yield i
>   while True:
> yield i
> yield -i
>
> 1 ∈ int2 [Not to mention 1 ∈ int2()]
>
> Consider range(10) (in python2 and 3)
> And finally [1,2,3,4]
>
> 1 ∈ all these
> Are the '∈'s here same?  Similar?

Yes, they are. Every one of them is asserting (or asking, depending on
your point of view) whether or not the instance to its left is a
member of the set to its right. The sets on the right are all
different, but the set membership operation is identical.

But even more so: The original collection of statements ("are
objects") all used the same RHS. In exactly the same senses, all of
those examples were testing for the same "objectness". (Although you
could argue that Steven's examples were talking about subclass
relationships rather than instance relationships, but really, an
instanceof relationship is a special case of subclass, where the class
on the left is defined by some form of object identity. Stating "All
books are objects" is a subclass relationship; stating "This book is
an object" is an instanceof relationship; both assertions use the same
meaning of "object(s)".)

All shoes are objects.
All ships are objects.
All lumps of sealing-wax are objects.
All cabbages are objects.
All kings are objects. (Some kings are also subjects, but not many.)

I can pick up a shoe, I can look at it, I can verify that it has
certain attributes common to all objects (location, mass, etc).
Superman can do the same with a ship (they're a bit big for me to pick
up). The actions you can perform on all objects are the attributes of
objects in general. Some subclasses of object may provide additional
actions (you can tip a king, for instance), but you can still do all
of these actions, so they're all the same type of object.

Note that not one iota of this has anything to do with Python's
documentation, its rules, its behaviour, or anything. Python follows
the natural expectations of our universe. The standard actions that
can be performed on Python objects are slightly different from the
standard actions that can be performed in Dungeons and Dragons, and
different again from the standard actions of the world we live in, but
they are no less applicable to all objects in that hierarchy:

* You can bind a name to an object (any object).
* You can pass an object as a function parameter.
* You can return an object from a function.
* You can reference objects in other objects' attributes.
* You can distinguish one object from another (that is, objects have
unique identities).

(In CPython, you can recognize an object by its GC header - an object
invariably has a reference count and so on. This is not a fundamental
attribute of objects, but it's a way to recognize them.)

Not everything that Python uses is an object. Syntax is not, itself,
manipulable; you can represent a syntax tree with either source code
(as a string) or an AST object, but syntax itself is not something you
can grasp. You can't assign "foo = def" in Python. But anything that
you can work with, in any way, is an object - and is an instance of
(some subclass of) the type 'object'. So, yes: They ARE all the same
meaning of "are" and "objects".

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Rustom Mody
On Tuesday, June 2, 2015 at 12:42:31 PM UTC+5:30, Steven D'Aprano wrote:
> On Tuesday 02 June 2015 10:24, TheDoctor wrote:
> 
> > A type is not an object in the same way an instantiated type is an object
> > -- anymore than a blueprint for a building is the building itself.
> 
> Nobody says that blueprints are *buildings*. But buildings are not the only 
> kind of object that exists.
> 
> Plates and spoons and knives and forks are objects.
> Cars and trucks and ships and planes are objects.
> Books and shoes and maps and compasses are objects.
> Buildings are objects.
> And blueprints of buildings are objects too.

You are using 'are' as if they are all the same 'are'. Are they?
Consider the type int.
It is supposed to model mathematical integers.
ie 1 ∈ int (in some sense)

Consider the generator
def int2():
  i = 0
  yield i
  while True:
yield i
yield -i

1 ∈ int2 [Not to mention 1 ∈ int2()]

Consider range(10) (in python2 and 3)
And finally [1,2,3,4]

1 ∈ all these
Are the '∈'s here same?  Similar?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2015-06-02 Thread Chris Angelico
On Tue, Jun 2, 2015 at 5:19 PM, Steven D'Aprano
 wrote:
> but that's not what my second example says. Look closely, and consider that
> sometimes we write "Mark's hat" and sometimes "the hat of Mark".

... and sometimes "the hat Mark's talking through", which appears to
put "hat" and "Mark's" the other way around, but is no less true.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2015-06-02 Thread Steven D'Aprano
On Tuesday 02 June 2015 07:45, TheDoctor wrote:

> On Wednesday, September 11, 2013 at 6:40:22 PM UTC-5, Steven D'Aprano
> wrote:
>> On Wed, 11 Sep 2013 14:30:54 -0700, Mark Janssen wrote:
>> 
>> > 1) It tried to make Object the parent of every class.
>> 
>> Tried, and succeeded.
> 
> Oh?  How about:
> 
> class superdict(dict):
> """I'm going to extend the dict type to include extra methods."""
> 
> class mixin():
>"""Here we go."""
> 
> What is the parent of mixin?

Why don't you try for yourself and see?


py> class mixin():
... """Here we go."""
... 
py> mixin.__bases__
(,)
py> mixin.__base__

py> mixin.__mro__
(, )





-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What use of string module?

2015-06-02 Thread Steven D'Aprano
On Tuesday 02 June 2015 12:14, fl wrote:

> Hi,
> 
> I read the online help about string. It lists string constants, string
> formatting, template strings and string functions. After reading these,
> I am still puzzled about how to use the string module.
> 
> Could you show me a few example about this module?


import string

c = "d"
if c in string.ascii_lowercase:
print "character is an ASCII lower case letter"



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2015-06-02 Thread Steven D'Aprano
On Tuesday 02 June 2015 10:10, TheDoctor wrote:

> On Friday, September 13, 2013 at 12:08:04 AM UTC-5, Steven D'Aprano wrote:

Mark, you are digging up a conversation from nearly two years ago. 
Seriously?


>> It makes no difference whether I write:
>> 
>> atoms -> stars -> galaxies
>> 
>> or
>> 
>> galaxies <- stars <- atoms
>> 
>> nor does it make any difference if I write the chain starting at the top
>> and pointing down, or at the bottom and pointing up.
> 
> Yes it does.  Ford IS-A Car, but Car IS-A Ford?  No.  Try reordering that
> one.

Try again. Look at the direction of the arrows. Nobody denies that there is 
a difference between:

atoms -> stars -> galaxies

galaxies -> stars -> atoms

but that's not what my second example says. Look closely, and consider that 
sometimes we write "Mark's hat" and sometimes "the hat of Mark".


> I see we've missed each other with our limitations to ASCII text, in ways
> that would have never happened had these conversations occurred in person.
>  Re-reading my texts, I see that I can easily confuse myself.

Yes, I see that.


-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Everything is an object in python - object class and type class

2015-06-02 Thread Steven D'Aprano
On Tuesday 02 June 2015 10:24, TheDoctor wrote:

> A type is not an object in the same way an instantiated type is an object
> -- anymore than a blueprint for a building is the building itself.

Nobody says that blueprints are *buildings*. But buildings are not the only 
kind of object that exists.

Plates and spoons and knives and forks are objects.
Cars and trucks and ships and planes are objects.
Books and shoes and maps and compasses are objects.
Buildings are objects.
And blueprints of buildings are objects too.


> The reason this confusion appears is for the exact reason I said on an
> earlier thread:  Python does not define classes in it's grammar

Of course it does. Otherwise "class K: pass" would give you a syntax error.


> -- so it
> can't account for the difference between an [instantiated] object and it's
> definition/type.

Of course it can and does. Python has a rich set of tools for introspecting 
values and determining whether they are instances or classes, what they are 
an instance of, and viewing the differences between the type and the class, 
starting with the humble human-readable string representation:

py> type(23)


and going on isinstance, issubclass, vars(), dir(), the inspect module, the 
dis module, and more.

The simplest test to tell whether something is an instance (an object) is:

isinstance(the_thing, object)

and that returns True *always*. The next test is to check whether it is a 
class (a type):

isinstance(the_thing, type)

which returns True only for classes and types. So, classes *are* objects, as 
well as being classes -- just as dogs are mammals, as well as being dogs.



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >