Re: Python education survey

2011-12-25 Thread Monte Milanuk
Not a teacher here, but I'm curious why Komodo Edit never seems to get 
any love in the IDE debates... a free version for personal/non-profit 
use, pro versions for those that need the extra features, seems to work 
fairly well but then again I'm probably not the best judge...


Thanks,

Monte


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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Devin Jeanpierre
> Um -- if you don't want a and c being passed in, why put them in the
> function signature?

He wants both or neither to be passed in.

-- Devin

On Sun, Dec 25, 2011 at 11:27 PM, Ethan Furman  wrote:
> GZ wrote:
>>
>> Hi,
>>
>> I run into a weird problem. I have a piece of code that looks like the
>> following:
>>
>> f(, a=None, c=None):
>>    assert  (a==None)==(c==None)
>
>
>
> Um -- if you don't want a and c being passed in, why put them in the
> function signature?
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Ethan Furman

Nobody wrote:

nothing should compare
equal to None except for None itself, so "x is None" and "x == None"
shouldn't produce different results unless there's a bug in the comparison
method.



Why wouldn't you want other types that can compare equal to None?  It 
could be useful for a Null type to == None.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Ethan Furman

GZ wrote:

Hi,

I run into a weird problem. I have a piece of code that looks like the
following:

f(, a=None, c=None):
assert  (a==None)==(c==None)



Um -- if you don't want a and c being passed in, why put them in the 
function signature?


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 3:17 PM, Roy Smith  wrote:
> Of course it is.  Those things constitute doc bugs which need to get
> fixed.  The fact that the specification is flawed does not change the
> fact that it *is* the specification.

Also, the specification is what can be trusted across multiple
implementations of Python - the source can't. I don't intend to get
the source code to five Pythons to ascertain whether getrandbits() is
provided in the default random.Random() of each of them. Now, in this
particular instance, it IS stated in the docs - just down in the
individual function descriptions, which I hadn't read - so I almost
certainly CAN trust that across all platforms. But in the general
case, I would not want to make firm statements on the basis of
implementation details.

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


Re: Random string of digits?

2011-12-25 Thread Roy Smith
In article <4ef7e337$0$29973$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> And I'm afraid that you have missed my point. The above comment from the 
> source is from a docstring: it *is* public, official documentation. See 
> help(random.Random).

When you wrote, "the source explicitly tells you..." the natural 
assumption I made was "something in the source that's not part of the 
documentation" (i.e. some comment).

> > The documentation is the specification of how something behaves.  
> > If the documentation doesn't say it, you can't rely on it.

> A nice platitude, but not true. Documentation is often incomplete or even 
> inaccurate.

Of course it is.  Those things constitute doc bugs which need to get 
fixed.  The fact that the specification is flawed does not change the 
fact that it *is* the specification.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backslash Escapes

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:04 PM, Felipe O  wrote:
> Hi all,
> Whenever I take any input (raw_input, of course!) or I read from a
> file, etc., any backslashes get escaped automatically. Is there any
> elegant way of parsing the backslashes as though they were written in
> a python string... I guess the alternative is to make a dictionary of all the 
> escapes I
> want to support, but that sounds tedious and error-prone.

The question really is: Are you looking to support some backslash
escapes, or are you looking to imitate Python? If the former, I
recommend making a specific list of what you support; every language
has its own, usually including some obscurities, and if all you need
is a few basics like \n, \t, \\, etc, then you probably don't want to
support \123 and \u1234 notations for arbitrary insertion of
characters. But if you actually want to imitate a Python string
literal, eval is almost certainly the easiest way; and if you want a
safer version:

http://docs.python.org/library/ast.html#ast.literal_eval

I'm not sure how well suited this is for parsing a string for its
escapes, but if you're looking to imitate Python, it may be easier to
tell people that the value must be enclosed in quotes - thus making it
an expression.

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


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 2:00 PM, Steven D'Aprano
 wrote:
> The implementation of getrandbits is not documented at all. You would
> have to read the C source of the _random module to find out how the
> default pseudo-random number generator produces random bits. But note the
> leading underscore: _random is a private implementation detail.
>
> However the existence and use of random.Random.getrandbits is public,
> documented, and guaranteed.

It's that last line where I find disagreement between documentation
and source code.

"""Class Random can also be subclassed if you want to use a different
basic generator of your own devising: in that case, override the
random(), seed(), getstate(), and setstate() methods. Optionally, a
new generator can supply a getrandbits() method — this allows
randrange() to produce selections over an arbitrarily large range."""

My reading of this is that, if I were to write my own generator, I
could provide that method and gain perfection. It's not until you dig
somewhat that you find out that the default generator actually does
provide getrandbits, meaning that the default randrange can actually
be used for arbitrarily large ranges. Yes, it IS documented, but in
separate places and somewhat as an afterthought; in the 2.x
documentation it's shown as "new in 2.4", which explains this.

Unfortunately my brain isn't really running on all cylinders at the
moment and I can't come up with a better wording, but is there some
way this could be stated up in the same top paragraph that explains
about 53-bit precision and 2**19937-1 period? That's where I got my
original information from; I didn't go down to the individual function
definitions, which is the only place that it's stated that the
Mersenne Twister does include getrandbits (and which assumes that
you've read the top section that states that Mersenne Twister is the
default implementation).

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


Re: Python education survey

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 4:44 AM, Rick Johnson
 wrote:
> Why install an IDE when IDLE is already there? Oh, yes, IDLE SUCKS. I
> know that already. But this revelation begs the question... Why has
> this community allowed IDLE to rot? Why has guido NOT started a public
> discussion on the matter?

Conversely, why write an IDE into IDLE when perfectly-good IDEs
already exist? I don't use IDLE for development per se; it's for
interactive Python execution, but not editing of source files.

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


Re: Random string of digits?

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 12:41:29 -0500, Roy Smith wrote:

> On Mon, 26 Dec 2011 03:11:56 +1100, Chris Angelico wrote:
>> > I prefer not to rely on the source. That tells me what happens, not
>> > what's guaranteed to happen.
> 
> Steven D'Aprano  wrote:
>> In this case, the source explicitly tells you that the API includes
>> support for arbitrary large ranges if you include a getrandbits()
>> method:
>> 
>>  Optionally, implement a getrandbits() method so that randrange()
>>  can cover arbitrarily large ranges.
>> 
>> I call that a pretty strong guarantee.
> 
> I think you mis-understood Chris's point.

And I'm afraid that you have missed my point. The above comment from the 
source is from a docstring: it *is* public, official documentation. See 
help(random.Random).


> The documentation is the
> specification of how something behaves.  If the documentation doesn't
> say it, you can't rely on it.

A nice platitude, but not true. Documentation is often incomplete or even 
inaccurate. We rely on many things that aren't documented anywhere. For 
example, we can rely on the fact that 

x = 3917
print x+1

will print 3918, even though that specific fact isn't documented 
anywhere. Nevertheless, we can absolutely bank on it -- if it happened to 
do something else, we would report it as a bug and not expect to be told 
"implementation detail, will not fix". We make a number of undocumented 
assumptions:

* we assume that when the documentation talks about "adding" two 
  numbers, it means the standard mathematical definition of addition 
  and not some other meaning;

* we assume that the result of such addition must be *correct*, 
  without that assumption being guaranteed anywhere;

* we assume that addition of two ints will return an int, as opposed
  to some other numerically equal value such as a float or Fraction;

* we assume that not only will it be an int, but it will be *exactly*
  an int, and not a subclass of int;

and no doubt there are others.

And by the way, in case you think I'm being ridiculously pedantic, 
consider the first assumption listed above: the standard mathematical 
definition of addition. That assumption is violated for floats.

py> 0.7 + 0.1 == 0.8
False


It is rather amusing the trust we put in documentation, when 
documentation can be changed just as easily as code. Just because the 
Fine Manual says that x+1 performs addition today, doesn't mean that it 
will continue to say the same thing tomorrow. So if you trust the 
language designers not to arbitrarily change the documentation, why not 
trust them not to arbitrarily change the code?

Hint: as far as I can tell, nowhere does Python promise that printing 
3918 will show those exact digits, but it's a pretty safe bet that Python 
won't suddenly change to displaying integers in balanced-ternary notation 
instead of decimal.



> The user should never have to read the
> source to know how to use a function, or what they can depend on.

Well, that's one school of thought. Another school of thought is that 
documentation and comments lie, and the only thing that you can trust is 
the code itself.

At the end of the day, the only thing that matters is the mindset of the 
developer(s) of the software. You must try to get into their head and 
determine whether they are the sort of people whose API promises can be 
believed.


> Now,
> I'm not saying that reading the source isn't useful for a deeper
> understanding, but it should be understood that any insights you glean
> from doing that are strictly implementation details.

I couldn't care less about the specific details of *how* getrandbits is 
used to put together an arbitrarily large random number. That "how" is 
what people mean when they talk about "mere implementation details".

But the fact that getrandbits is used by randrange (as opposed to how it 
is used) is not a mere implementation detail, but a public part of the 
interface.


> If you're saying that there are guarantees made by the implementation of
> getrandbits() which are not documented, then one of two things are true:

The implementation of getrandbits is not documented at all. You would 
have to read the C source of the _random module to find out how the 
default pseudo-random number generator produces random bits. But note the 
leading underscore: _random is a private implementation detail.

However the existence and use of random.Random.getrandbits is public, 
documented, and guaranteed.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Ian Kelly
On Sun, Dec 25, 2011 at 2:38 AM, Nobody  wrote:
> On Sat, 24 Dec 2011 23:09:50 -0800, GZ wrote:
>
>> I run into a weird problem. I have a piece of code that looks like the
>> following:
>>
>> f(, a=None, c=None):
>>     assert  (a==None)==(c==None)
>>
>>
>> The problem is that == is not implemented sometimes for values in a
>> and c, causing an exception NotImplementedError.
>
> I have no idea how that can happen. If a.__eq__(None) returns
> NotImplemented, the interpreter should flip the test and perform the
> equivalent of None.__eq__(a), which will return False.

Maybe the class has a misbehaved __eq__ that raises
NotImplementedError directly instead of returning NotImplemented.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backslash Escapes

2011-12-25 Thread Devin Jeanpierre
> Whenever I take any input (raw_input, of course!) or I read from a
> file, etc., any backslashes get escaped automatically.

They don't get escaped, they get... treated as the bytes that they
are. If you want them to mean what they do in Python, use the
'string_escape' codec.

>>> x = r'nyan\nyan'
>>> print x
nyan\nyan
>>> print x.decode('string_escape')
nyan
yan

-- Devin

On Sun, Dec 25, 2011 at 8:04 PM, Felipe O  wrote:
> Hi all,
> Whenever I take any input (raw_input, of course!) or I read from a
> file, etc., any backslashes get escaped automatically. Is there any
> elegant way of parsing the backslashes as though they were written in
> a python string. The best I have so far right now goes like this:
>
> def parse_backslash_escapes(input_string):

>    parts = input_string.split("'''")  # That's ' " " " ' without the spaces
>    '"""'.join(eval + p + '"""') for p in parts)
>
> I'm not entirely convinced that it's safe on two accounts.
> + Is that eval statement safe? The input could be coming from an
> unfriendly source.
> + Are there any obscure backslash escapes or other tricks I should be aware 
> of?
>
> I guess the alternative is to make a dictionary of all the escapes I
> want to support, but that sounds tedious and error-prone.
>
> Thanks,
>
> Felipe
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Backslash Escapes

2011-12-25 Thread MRAB

On 26/12/2011 01:04, Felipe O wrote:

Hi all,
Whenever I take any input (raw_input, of course!) or I read from a
file, etc., any backslashes get escaped automatically. Is there any
elegant way of parsing the backslashes as though they were written in
a python string. The best I have so far right now goes like this:

def parse_backslash_escapes(input_string):
 parts = input_string.split("'''")  # That's ' " " " ' without the spaces
 '"""'.join(eval + p + '"""') for p in parts)

I'm not entirely convinced that it's safe on two accounts.
+ Is that eval statement safe? The input could be coming from an
unfriendly source.
+ Are there any obscure backslash escapes or other tricks I should be aware of?

I guess the alternative is to make a dictionary of all the escapes I
want to support, but that sounds tedious and error-prone.


Try input_string.decode("string-escape") if input_string is a
bytestring or input_string.decode("unicode-escape") it's a Unicode
string.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How safe is this way of getting a default that allows None?

2011-12-25 Thread Tim Chase

On 12/25/11 18:49, Dan Stromberg wrote:

How safe is this?  I like the idea.

UNSPECIFIED = object()

def fn(x, y=UNSPECIFIED):
if y is UNSPECIFIED:
   print x, 'default'
else:
   print x, y


safe?  It's idiomatic :)

-tkc


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


Backslash Escapes

2011-12-25 Thread Felipe O
Hi all,
Whenever I take any input (raw_input, of course!) or I read from a
file, etc., any backslashes get escaped automatically. Is there any
elegant way of parsing the backslashes as though they were written in
a python string. The best I have so far right now goes like this:

def parse_backslash_escapes(input_string):
parts = input_string.split("'''")  # That's ' " " " ' without the spaces
'"""'.join(eval + p + '"""') for p in parts)

I'm not entirely convinced that it's safe on two accounts.
+ Is that eval statement safe? The input could be coming from an
unfriendly source.
+ Are there any obscure backslash escapes or other tricks I should be aware of?

I guess the alternative is to make a dictionary of all the escapes I
want to support, but that sounds tedious and error-prone.

Thanks,

Felipe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Devin Jeanpierre
> Which of course leads to a SillyPEP for a new keyword, "are", which
> would allow you to write:
>
 a and c are None
>
> instead of the much more verbose
>
 a is None and c is None

How about:

>>> a is b is None

;)

-- Devin

On Sun, Dec 25, 2011 at 7:27 PM, Roy Smith  wrote:
> In article ,
>  Devin Jeanpierre  wrote:
>
>> The issue here is that "== None" is being used instead of "is None",
>> but I believe that's been covered. Your response doesn't include it,
>> so maybe it's worth restating.
>
> Which of course leads to a SillyPEP for a new keyword, "are", which
> would allow you to write:
>
 a and c are None
>
> instead of the much more verbose
>
 a is None and c is None
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 15:45:10 -0800, Larry Hudson wrote:

> On 12/24/2011 11:09 PM, GZ wrote:
>> Hi,
>>
>> I run into a weird problem. I have a piece of code that looks like the
>> following:
>>
>> f(, a=None, c=None):
>>  assert  (a==None)==(c==None)
>>
> <...>
> 
> At first glance this looked like it should be a simple boolean "and",
> but then I realized that when a and c are both unequal to None, the
> result would also be True.  This implies the logical approach would be
> exclusive-or (^).  Try this expression:
> 
>   not ((a==None) ^ (c==None))

^ is *bitwise* xor, not boolean xor. Python doesn't offer boolean xor 
directly, although != comes close.


> OTOH, if what you really want is simply to check that both are None (my
> first impression), then it's simply:
> 
>   (a==None) and (c==None)

Replace == with 'is'.

> Most of the replies you're getting here seem unnecessarily complicated.

== is a more complicated operator than the 'is' operator. That's why the 
is operator is to be preferred when testing for None -- it is guaranteed 
to do the right thing, while == is not.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


How safe is this way of getting a default that allows None?

2011-12-25 Thread Dan Stromberg
How safe is this?  I like the idea.

#!/usr/bin/python

UNSPECIFIED = object()

def fn(x, y=UNSPECIFIED):
   if y is UNSPECIFIED:
  print x, 'default'
   else:
  print x, y

fn(0, 1)
fn(0, None)
fn(0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Christian Heimes
Am 25.12.2011 15:04, schrieb Chris Angelico:
> I think there are certain types that are actually not implemented as
> classes, and hence cannot be subclassed. This is almost certainly an
> implementation detail though; my testing was done in Py3.2 (on Windows
> fwiw).

Some extension types are not subclass-able on purpose. The feature isn't
available to heap types.
http://docs.python.org/c-api/typeobj.html#Py_TPFLAGS_BASETYPE Most
people have never noticed the deliberate limitation because only a few
special types are sub-classable.

Christian

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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Roy Smith
In article ,
 Devin Jeanpierre  wrote:

> The issue here is that "== None" is being used instead of "is None",
> but I believe that's been covered. Your response doesn't include it,
> so maybe it's worth restating.

Which of course leads to a SillyPEP for a new keyword, "are", which 
would allow you to write:

>>> a and c are None

instead of the much more verbose

>>> a is None and c is None
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Devin Jeanpierre
> At first glance this looked like it should be a simple boolean "and", but
> then I realized that when a and c are both unequal to None, the result would
> also be True.  This implies the logical approach would be exclusive-or (^).

Among booleans, "!=" is exclusive or and "==" is its negation. I don't
see the point of complicating the formula to use ^.

(related: <= is implication. Which is sad, because the arrow points
the wrong way!)

The issue here is that "== None" is being used instead of "is None",
but I believe that's been covered. Your response doesn't include it,
so maybe it's worth restating.

-- Devin

On Sun, Dec 25, 2011 at 6:45 PM, Larry Hudson  wrote:
> On 12/24/2011 11:09 PM, GZ wrote:
>>
>> Hi,
>>
>> I run into a weird problem. I have a piece of code that looks like the
>> following:
>>
>> f(, a=None, c=None):
>>     assert  (a==None)==(c==None)
>>
> <...>
>
> At first glance this looked like it should be a simple boolean "and", but
> then I realized that when a and c are both unequal to None, the result would
> also be True.  This implies the logical approach would be exclusive-or (^).
>  Try this expression:
>
>     not ((a==None) ^ (c==None))
>
> OTOH, if what you really want is simply to check that both are None (my
> first impression), then it's simply:
>
>     (a==None) and (c==None)
>
> Most of the replies you're getting here seem unnecessarily complicated.
>
>> Thanks,
>> gz
>
>
>    -=- Larry -=-
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Larry Hudson

On 12/24/2011 11:09 PM, GZ wrote:

Hi,

I run into a weird problem. I have a piece of code that looks like the
following:

f(, a=None, c=None):
 assert  (a==None)==(c==None)


<...>

At first glance this looked like it should be a simple boolean "and", but then I realized that 
when a and c are both unequal to None, the result would also be True.  This implies the logical 
approach would be exclusive-or (^).  Try this expression:


 not ((a==None) ^ (c==None))

OTOH, if what you really want is simply to check that both are None (my first impression), then 
it's simply:


 (a==None) and (c==None)

Most of the replies you're getting here seem unnecessarily complicated.


Thanks,
gz


-=- Larry -=-
--
http://mail.python.org/mailman/listinfo/python-list


RSA and Cryptography in PYTHON

2011-12-25 Thread 88888 Dihedral
Long integer is really excellent in Python. 

Encoding RSA 2048bits  in a simple and elegant way in Python
is almost trivial. 

How about the nontrivial decoding part ? 


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


Re: Random string of digits?

2011-12-25 Thread 88888 Dihedral
Roy Smith於 2011年12月26日星期一UTC+8上午1時41分29秒寫道:
> On Mon, 26 Dec 2011 03:11:56 +1100, Chris Angelico wrote:
> > > I prefer not to rely on the source. That tells me what happens, not
> > > what's guaranteed to happen. 
> 
> Steven D'Aprano  wrote:
> > In this case, the source explicitly tells you that the API includes 
> > support for arbitrary large ranges if you include a getrandbits() method:
> > 
> >  Optionally, implement a getrandbits() method so that randrange()
> >  can cover arbitrarily large ranges.
> > 
> > I call that a pretty strong guarantee.
> 
> I think you mis-understood Chris's point.  The documentation is the 
> specification of how something behaves.  If the documentation doesn't 
> say it, you can't rely on it.  The user should never have to read the 
> source to know how to use a function, or what they can depend on.  Now, 
> I'm not saying that reading the source isn't useful for a deeper 
> understanding, but it should be understood that any insights you glean 
> from doing that are strictly implementation details.
> 
> If you're saying that there are guarantees made by the implementation of 
> getrandbits() which are not documented, then one of two things are true:
> 
> 1) It is intended that users can depend on that behavior, in which case 
> it's a bug in the docs, and the docs should be updated.
> 
> or
> 
> 2) It is not intended that users can depend on that behavior, in which 
> case they would be foolish to do so.

Random bit generations for RSA2048 encoding  and cryptography applications 
in python is simple and elegant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plot seems weird

2011-12-25 Thread Yigit Turgut
On Dec 25, 7:06 pm, Rick Johnson  wrote:
> On Dec 25, 9:33 am, Yigit Turgut  wrote:
> > Hi all,
>
> > I have a text file as following;
>
> > 0.200047        0.00
> > 0.200053        0.16
> > 0.200059        0.00
> > 0.200065        0.08
> > 0.200072        0.00
> > 0.200078        0.16
>
> > And I am trying to plot it with ;
>
> > filenames = sys.argv[1:]
> > if len(filenames) == 0:
> >     filenames = [sys.stdin]
> > for filename in filenames:
> >     t,y1 = numpy.genfromtxt(filename, unpack=True)
> >     pyplot.plot(t,y1)
> >     pyplot.show()
>
> > But graph seems weird, not as it supposed to be. Any ideas ?
>
> Interesting. Of course "weird" leaves a LOT to be desired. On a scale
> of 1-10, how "weird" is the result?

I apply a 1Khz test signal just to see if things run smoothly, but I
see spikes at lower and higher ends (logic 0,1) where I should see a
clean rectangle pwm signal. By the look of it I say weirdness is
around 3/10.

>
> But seriously. Have you tried debugging yet? If not, test these
> points:
Yes I double checked it, there seems to be nothing wrong in debug.

>  * What is the value of "filenames" BEFORE the loop?

Filename is argument 1 of the startup action.

>  * What is the value of "t" and "y1" for each iteration?

I test with both low and mid frequency signals (50Hz - 1Khz), same
inconsistency.

>
> Also observe this wonderful phenomenon:
>
> py> [] or [1,2,3]
> [1, 2, 3]
> py> [] or None or '' or () or {} or [1,2,3] or "1,2,3"
> [1, 2, 3]

Beautiful. I convert my arrays to string before writing to file.
Original post contains a fragment of the whole file. Data is
fluctuating, not a linear behavior.

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


Re: Python education survey

2011-12-25 Thread Rick Johnson
On Dec 19, 9:51 pm, Raymond Hettinger 
wrote:
> Do you use IDLE when teaching Python?
> If not, what is the tool of choice?

I believe IDLE has the potential to be a very useful teaching tool and
even in it's current abysmal state, i find it to be quite useful.

> Students may not be experienced with the command-line and may be
> running Windows, Linux, or Macs.  Ideally, the tool or IDE will be
> easy to install and configure (startup directory, path, associated
> with a particular version of Python etc).

Why install an IDE when IDLE is already there? Oh, yes, IDLE SUCKS. I
know that already. But this revelation begs the question... Why has
this community allowed IDLE to rot? Why has guido NOT started a public
discussion on the matter?

> Though an Emacs user myself, I've been teaching with IDLE because it's
> free; it runs on multiple OSes, it has tooltips and code colorization
> and easy indent/dedent/comment/uncomment commands, it has tab
> completion; it allows easy editing at the interactive prompt; it has
> an easy run-script command (F5); it has direct access to source code
> (File OpenModule) and a class browser (Cntl+B).

Yes, IDLE has all the basic tools anyone would need. Some people
complain about a debugger, but i never use a debugger anyway. I feel
debuggers just wreaken your debugging skills.

> On the downside, some python distros aren't built with the requisite
> Tcl/Tk support;

And who's fault is that?

> some distros like the Mac OS ship with a broken Tcl/Tk
> so users have to install a fix to that as well; and IDLE sometimes
> just freezes for no reason.

And who's fault is that?

>  [IDLE] also doesn't have an easy way to
> specify the startup directory.

Are you kidding me? That could be fixed so easily!

> If your goal is to quickly get new users up and running in Python,
> what IDE or editor do you recommend?

IDLE, of course. But NOT in its current state.

Why would myself (or anyone) go to the trouble of downloading third
party IDEs when IDLE is just waiting there for us to use? I for one,
like to use tools that have open source code.  And what is a better
Python IDE than a Python IDE written in PYTHON? I ask ya?

Also, what is the purpose of this thread Raymond? Are you (and others)
considering removing IDLE from the source distro?

You know. Many folks in this community have known for a long time how
much i love IDLE, but at the same time how much i loath it's atrocious
code base. I also know for a fact, that many "movers and shakers"
within this community simultaneously use IDLE, and want to see IDLE
code improved. However. None of these fine folks have taken the time
to contact me privately so we can discuss such an evolution. Why is
that? It boggles the mind really.



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


Re: Random string of digits?

2011-12-25 Thread Joshua Landau
On 25 December 2011 17:32, Serhiy Storchaka  wrote:

> 25.12.11 15:48, Steven D'Aprano написав(ла):
>
>  On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:
>>
>>> I want to create a string of 20 random digits (I'm OK with leading
>>> zeros).  The best I came up with is:
>>> ''.join(str(random.randint(0, 9)) for i in range(20))
>>> Is there something better?
>>>
>> '%20d' % random.randint(0, 10**20-1)
>>
>
> '%020d' % random.randrange(10**20)


Do the docs not advise .format now?

"{:20}".format(random.randrange(10**20))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Roy Smith
On Mon, 26 Dec 2011 03:11:56 +1100, Chris Angelico wrote:
> > I prefer not to rely on the source. That tells me what happens, not
> > what's guaranteed to happen. 

Steven D'Aprano  wrote:
> In this case, the source explicitly tells you that the API includes 
> support for arbitrary large ranges if you include a getrandbits() method:
> 
>  Optionally, implement a getrandbits() method so that randrange()
>  can cover arbitrarily large ranges.
> 
> I call that a pretty strong guarantee.

I think you mis-understood Chris's point.  The documentation is the 
specification of how something behaves.  If the documentation doesn't 
say it, you can't rely on it.  The user should never have to read the 
source to know how to use a function, or what they can depend on.  Now, 
I'm not saying that reading the source isn't useful for a deeper 
understanding, but it should be understood that any insights you glean 
from doing that are strictly implementation details.

If you're saying that there are guarantees made by the implementation of 
getrandbits() which are not documented, then one of two things are true:

1) It is intended that users can depend on that behavior, in which case 
it's a bug in the docs, and the docs should be updated.

or

2) It is not intended that users can depend on that behavior, in which 
case they would be foolish to do so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Serhiy Storchaka

25.12.11 15:48, Steven D'Aprano написав(ла):

On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:

I want to create a string of 20 random digits (I'm OK with leading
zeros).  The best I came up with is:
''.join(str(random.randint(0, 9)) for i in range(20))
Is there something better?

'%20d' % random.randint(0, 10**20-1)


'%020d' % random.randrange(10**20)

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


Re: Random string of digits?

2011-12-25 Thread Steven D'Aprano
On Mon, 26 Dec 2011 03:11:56 +1100, Chris Angelico wrote:

> On Mon, Dec 26, 2011 at 2:46 AM, Steven D'Aprano
>  wrote:
>> Use the Source, Luke, er, Chris :)
>>
>> If I've read the source correctly, randint() will generate sufficient
>> bits of randomness to ensure that the entire int is random.
>>
>> http://hg.python.org/cpython/file/default/Lib/random.py
> 
> I prefer not to rely on the source. That tells me what happens, not
> what's guaranteed to happen. 

In this case, the source explicitly tells you that the API includes 
support for arbitrary large ranges if you include a getrandbits() method:

 Optionally, implement a getrandbits() method so that randrange()
 can cover arbitrarily large ranges.

I call that a pretty strong guarantee.


> However... bit of poking around can't hurt.
> That file doesn't actually justify anything, because random.Random()
> does not define getrandbits() - that, it seems, comes from _random();
> turns out that getrandbits is actually doing pretty much the same thing
> I suggested:
> 
> http://hg.python.org/cpython/file/745f9fd9856d/Modules/
_randommodule.c#l371
> 
> Need a 64-bit random number? Take two 32-bit numbers and concatenate.
> So, it's going to be easier and clearer to just take the simple option,
> since it's actually doing the same thing underneath anyway.

Um, I'm not sure what you consider "the simple option" in this context. I 
would hope you mean to use the high level API of randint:

# need a random number with exactly 20 decimal digits
random.randint(10**20, 10**21-1)

rather than manually assembling a 20 digit number from smaller pieces.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Lie Ryan

On 12/26/2011 01:13 AM, Roy Smith wrote:

In article,
  Chris Angelico  wrote:


On Mon, Dec 26, 2011 at 12:17 AM, Roy Smith  wrote:

Just for fun, I tried playing around with subclassing NoneType and
writing an __eq__ for my subclass.  Turns out, you can't do that:

Traceback (most recent call last):
  File "./none.py", line 5, in
class Nihil(NoneType):
TypeError: Error when calling the metaclass bases
type 'NoneType' is not an acceptable base type


Yes; unfortunately quite a few Python built-in classes can't be
subclassed. It's an unfortunate fact of implementation, I think,
rather than a deliberate rule.

But then, what would you ever need to subclass None for, other than
toys and testing?


You might be to differentiate between temporary and permanent failures.
Let's say you have a WidgetPool, containing Widgets of various classes.

class WidgetPool:
def get_widget(class_name):
   """Return a Widget of a given class.  If there are no such
   Widgets available, returns None."""
   [...]

You might want to return a None subclass to signify, "No such Widgets
are currently available, but they might be if you try again in a little
while", as opposed to "No such Widgets will ever be available".

If you were designing the interface from scratch, you would probably
represent that with an exception hierarchy.  However, if this was an old
interface that you were modifying, this might be a way to return a
richer failure indication for new clients without breaking backwards
compatibility for existing code.

Of course, the existing code would probably be using "is None" tests,
and break anyway.  But at least that's a plausible scenario for None
subclasses.


That scenario doesn't actually need subclassing if you duck type.


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


Re: Plot seems weird

2011-12-25 Thread Rick Johnson
On Dec 25, 9:33 am, Yigit Turgut  wrote:
> Hi all,
>
> I have a text file as following;
>
> 0.200047        0.00
> 0.200053        0.16
> 0.200059        0.00
> 0.200065        0.08
> 0.200072        0.00
> 0.200078        0.16
>
> And I am trying to plot it with ;
>
> filenames = sys.argv[1:]
> if len(filenames) == 0:
>     filenames = [sys.stdin]
> for filename in filenames:
>     t,y1 = numpy.genfromtxt(filename, unpack=True)
>     pyplot.plot(t,y1)
>     pyplot.show()
>
> But graph seems weird, not as it supposed to be. Any ideas ?


Interesting. Of course "weird" leaves a LOT to be desired. On a scale
of 1-10, how "weird" is the result?

But seriously. Have you tried debugging yet? If not, test these
points:

 * What is the value of "filenames" BEFORE the loop?
 * What is the value of "t" and "y1" for each iteration?

Also observe this wonderful phenomenon:

py> [] or [1,2,3]
[1, 2, 3]
py> [] or None or '' or () or {} or [1,2,3] or "1,2,3"
[1, 2, 3]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 07:38:17 -0800, Eelco wrote:

> On Dec 25, 2:12 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>> On Sat, 24 Dec 2011 06:39:39 -0800, Eelco wrote:
>> > On Dec 20, 4:30 am, alex23  wrote:
>> >> On Dec 19, 8:15 pm, Eelco  wrote:
>>
>> >> > What does that have to do with collection packing/unpacking?
>>
>> >> It's mocking your insistance that collection unpacking is a type
>> >> constraint.
>>
>> > This is really going to be the last time I waste any words on this:
>>
>> If only that were true, but after sending this post, you immediately
>> followed up with FIVE more posts on this subject in less than half an
>> hour.
> 
> Did I waste any more words on collection packing and type constraints?
> No, I did not. (though I am about to, and am willing to do so for every
> question that seems genuinely aimed at engaging me on the matter)
> 
> Did I intend to say that I was going to let a single troll shut down my
> entire topic? No, I did not.

Ah, well whatever you *intended* wasn't clear from your comment. At least 
not clear to *me*.


[...]
> Yes, indeed it would be abuse of language to call this a type
> constraint, since the fact that y is a list is indeed an outcome of
> whatever happens to pop out at the right hand side. One could redefine
> the identifier list to return any kind of object.

So far, we agree on this.

> How is 'head, *tail = sequence' or semantically entirely equivalently,
> 'head, tail::list = sequence' any different then? Of course after
> interpretation/compilation, what it boils down to is that we are
> constructing a list and binding it to the identifier tail, but that is
> not how it is formulated in python as a language 

I'm afraid it is.

Here's the definition of assignment in Python 3:
http://docs.python.org/py3k/reference/simple_stmts.html#assignment-
statements


> (all talk of types is
> meaningless after compilation; machine code is untyped).

What does machine code have to do with Python?


> We dont have
> something of the form 'tail = list_tail(sequence)'.

I'm afraid we do. See the definition of assignment again.


> Rather, we annotate
> the identifier 'tail' with an attribute that unquestionably destinates
> it to become a list*. It is no longer that 'tail' will just take
> anything that pops out of the expression on the right hand side; 

Of course it will. Python is a dynamically typed language. It doesn't 
suddenly develop static types to ensure that 'tail' becomes a list; 
'tail' is bound to a list because that's what the assignment statement 
provides.


> rather,
> the semantics of what will go on at right hand side is coerced by the
> constraint placed on 'tail'.

But it isn't a constraint placed on 'tail'. It is a consequence of the 
definition of assignment in Python 3. 'tail' becomes bound to a list 
because that is what the assignment statement is defined to do in that 
circumstance, not because the identifier (symbol) 'tail' is constrained 
to only accept lists. 'tail' may not even exist before hand, so talking 
about constraints on 'tail' is an abuse of language, AS YOU AGREED ABOVE.


[...]
> *(I call that a 'type constraint', because that is what it literally is;


No. It is literally a name binding of a dynamically typed, unconstrained 
name to an object which happens to be a list.


> if you can make a case that this term has acquired a different meaning
> in practice, and that there is another term in common use for this kind
> of construct; please enlighten me. Until that time, im going to ask you
> to take 'type constraint' by its literal meaning; a coercion of the type
> of a symbol,

But THERE IS NO COERCION OF THE TYPE OF THE SYMBOL.

I am sorry for shouting, but you seem oblivious to the simple fact that 
Python is not statically typed, and the symbol 'tail' is NOT coerced to a 
specific type. 'tail' may not even exist before the assignment is made; 
if it does exist, it could be *any type at all* -- and after the 
assignment takes place, there are no restrictions on subsequent 
assignments. 

'head, *tail = sequence' is no more a type constraint than 'x = 1' is.

Whatever the virtues of your proposal, you are doing it incalculable harm 
by your insistence on this incorrect model of Python's behaviour. 


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 2:38 AM, Eelco  wrote:
> Until that time, im going
> to ask you to take 'type constraint' by its literal meaning; a
> coercion of the type of a symbol, rather than whatever particular
> meaning it has acquired for you (it might help if you explained that).
> Im not sure if it was you that brought that up, but let me reiterate
> that I dont mean a 'type cast', which is a runtime concept. A 'type
> constraint' is purely a linguistic construct that will be 'compiled
> out')

The dictionary definition of constraint is "a limitation or
restriction", and you're right that it can be "compiled out". In fact,
that is probably the best definition. Assuming everything is written
correctly, you should be able to eliminate all constraints and the
code will still function correctly*; but having the constrains means
that certain illegal operations will throw errors.

Here's two examples of tuple unpacking, one with a type constraint,
the other without:

a, b = ('hello', [1,2,3] )
a, b::list = ('hello', [1,2,3] )

The constraint on the second line means that, if the second element is
not a list, the interpreter should throw an error. It does NOT mean to
completely change the meaning of the statement to _make_ the last
argument into a list. That is not the job of a constraint.

ChrisA

* In databasing, it's not uncommon to have code depend on error
responses for correct operation; for instance, one implementation of
UPSERT is to attempt an INSERT, and if it fails due to a unique key
constraint, do the UPDATE instead. The same is also done in Python -
eg using an exception to terminate a loop - but in the context of this
discussion, assume that errors indicate errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 06:55:28 -0800, Eelco wrote:

> Anyway,  braces are used at
> least an order of magnitude more than collection packing/ unpacking in
> typical code.

That's a wild and unjustified claim. Here's a quick and dirty test, using 
the standard library as an example of typical idiomatic code:

[steve@orac ~]$ cd /usr/lib/python2.6
[steve@orac python2.6]$ grep "[*]args" *.py | wc -l
270
[steve@orac python2.6]$ grep "{" *.py | wc -l
550

Doesn't look like a factor of 10 difference to me.


And from one of my projects:

[steve@orac src]$ grep "[*]args" *.py | wc -l
267
[steve@orac src]$ grep "{" *.py | wc -l
8



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 2:46 AM, Steven D'Aprano
 wrote:
> Use the Source, Luke, er, Chris :)
>
> If I've read the source correctly, randint() will generate sufficient
> bits of randomness to ensure that the entire int is random.
>
> http://hg.python.org/cpython/file/default/Lib/random.py

I prefer not to rely on the source. That tells me what happens, not
what's guaranteed to happen. However... bit of poking around can't
hurt. That file doesn't actually justify anything, because
random.Random() does not define getrandbits() - that, it seems, comes
from _random(); turns out that getrandbits is actually doing pretty
much the same thing I suggested:

http://hg.python.org/cpython/file/745f9fd9856d/Modules/_randommodule.c#l371

Need a 64-bit random number? Take two 32-bit numbers and concatenate.
So, it's going to be easier and clearer to just take the simple
option, since it's actually doing the same thing underneath anyway.

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Eelco
On Dec 25, 2:13 pm, Steven D'Aprano  wrote:
> On Sat, 24 Dec 2011 06:47:21 -0800, Eelco wrote:
> > I would like to be able to write something like:
>
> > a, middle::tuple, b = ::sequence
>
> > Where I would like the extra :: before the sequence to explicitly signal
> > collection unpacking on the rhs, to maintain the symmetry with
> > collection unpacking within a function call.
>
> The :: on the right-hand side is redundant, because the left-hand side
> already explicitly signals collection unpacking of the RHS. Requiring ::
> on the RHS above is as unnecessary as it would be here:

Yes, it is redundant; hence the word 'extra' in my post.

Explicit and implicit are not well-defined terms, but I would say that
at the moment the signal is implicit, in the sense that one cannot see
what is going on by considering the rhs in isolation. Normally in
python, an assignment just binds the rhs to the identifiers on the
lhs, but in case of collection (un)packing, this rule that holds
almost all of the time is broken, and the assignment statement implies
a far more complicated construct, with a far more subtle meaning, and
non-constant time complexity.

Thats not a terrible thing, but a little extra explicitness there
would not hurt, and like I argued many times before, it is a nice
unification with the situation where the unpacking can not be
implicit, like inside a function call rather than assignment.


>     n = len(::sequence)

Now you are just discrediting yourself in terms of having any idea
what you are talking about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Plot seems weird

2011-12-25 Thread Yigit Turgut
Hi all,

I have a text file as following;

0.2000470.00
0.2000530.16
0.2000590.00
0.2000650.08
0.2000720.00
0.2000780.16

And I am trying to plot it with ;

filenames = sys.argv[1:]
if len(filenames) == 0:
filenames = [sys.stdin]
for filename in filenames:
t,y1 = numpy.genfromtxt(filename, unpack=True)
pyplot.plot(t,y1)
pyplot.show()

But graph seems weird, not as it supposed to be. Any ideas ?


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


Re: Random string of digits?

2011-12-25 Thread Steven D'Aprano
On Mon, 26 Dec 2011 00:54:40 +1100, Chris Angelico wrote:

> On Mon, Dec 26, 2011 at 12:48 AM, Steven D'Aprano
>  wrote:
>> On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:
>>
>>> I want to create a string of 20 random digits (I'm OK with leading
>>> zeros).  The best I came up with is:
>>>
>>> ''.join(str(random.randint(0, 9)) for i in range(20))
>>>
>>> Is there something better?
>>
>> '%20d' % random.randint(0, 10**20-1)
> 
> I should mention that this sort of thing is absolutely acceptable in
> situations where you don't actually need that level of randomness;

Use the Source, Luke, er, Chris :)

If I've read the source correctly, randint() will generate sufficient 
bits of randomness to ensure that the entire int is random.

http://hg.python.org/cpython/file/default/Lib/random.py



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Eelco
On Dec 25, 1:50 pm, Steven D'Aprano  wrote:
> On Sat, 24 Dec 2011 06:45:01 -0800, Eelco wrote:
> > Can you give an example of a construct in python where two whitespace
> > delimited identifiers are legal?
>
> Not apart from the trivial case of two identifiers separated by newlines.
>
> What's your point?

My point is as I originally stated it: that this construct, of two
identifiers seperated by non-newline whitespace, as in 'list tail'
does not occur anywhere else in python, so introducing that syntax,
while i suppose technically possible, would be a break with existing
expectations. Normally speaking, if two identifiers interact, they are
explicitly 'joined' by an infixed operator of some sort, as in 3*4,
rather than * 3 4. That seems a sensible rule to me, and I see no
compelling reason to depart from it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Eelco
On Dec 25, 2:12 pm, Steven D'Aprano  wrote:
> On Sat, 24 Dec 2011 06:39:39 -0800, Eelco wrote:
> > On Dec 20, 4:30 am, alex23  wrote:
> >> On Dec 19, 8:15 pm, Eelco  wrote:
>
> >> > What does that have to do with collection packing/unpacking?
>
> >> It's mocking your insistance that collection unpacking is a type
> >> constraint.
>
> > This is really going to be the last time I waste any words on this:
>
> If only that were true, but after sending this post, you immediately
> followed up with FIVE more posts on this subject in less than half an
> hour.

Did I waste any more words on collection packing and type constraints?
No, I did not. (though I am about to, and am willing to do so for
every question that seems genuinely aimed at engaging me on the
matter)

Did I intend to say that I was going to let a single troll shut down
my entire topic? No, I did not.

> > In case of python, collection PACKING (not unpacking) is signaled by a
> > construct that can be viewed as a type constraint.
>
> Only by doing sufficient violence to the concept of type constraint that
> it could mean *anything*.
>
> Earlier, I insisted that a constraint is a rule that applies to input,
> not output. I haven't seen anyone, including yourself, dispute that.
>
> Normally we would say that in the statement:
>
>     y = list(x)
>
> there is a constraint on x, namely that it is some sort of iterable
> object (otherwise an exception will be raised), but it would be an abuse
> of language to say that there is a type constraint on y. y ends up being
> a list, true, but that isn't a constraint on y, it is an outcome.
>
> In normal usage, "constraint" refers to pre-conditions, not post-
> conditions. There are no pre-conditions on y in the above. It may not
> even exist. Contrast it with this example:
>
>     y += list(x)
>
> where there are constraints on y: it must exist, and it must be a list,
> or something which can be added to a list.

Yes, indeed it would be abuse of language to call this a type
constraint, since the fact that y is a list is indeed an outcome of
whatever happens to pop out at the right hand side. One could redefine
the identifier list to return any kind of object.

How is 'head, *tail = sequence' or semantically entirely equivalently,
'head, tail::list = sequence' any different then? Of course after
interpretation/compilation, what it boils down to is that we are
constructing a list and binding it to the identifier tail, but that is
not how it is formulated in python as a language (all talk of types is
meaningless after compilation; machine code is untyped). We dont have
something of the form 'tail = list_tail(sequence)'. Rather, we
annotate the identifier 'tail' with an attribute that unquestionably
destinates it to become a list*. It is no longer that 'tail' will just
take anything that pops out of the expression on the right hand side;
rather, the semantics of what will go on at right hand side is coerced
by the constraint placed on 'tail'.

But again, if you dont wish to view this as a type constraint, I wont
lose any sleep over that. In that case this line of argument was
simply never directed at you. It was directed at people who would
reasonably argue that 'tail::tuple is a type constraint and thats
unpythonic / type constraints have been considered and rejected'. If
you dont think it looks like a type constraint: fine. The simpler
argument is that whatever it is, its just a more verbose and flexible
variant of a construct that python already has.

*(I call that a 'type constraint', because that is what it literally
is; if you can make a case that this term has acquired a different
meaning in practice, and that there is another term in common use for
this kind of construct; please enlighten me. Until that time, im going
to ask you to take 'type constraint' by its literal meaning; a
coercion of the type of a symbol, rather than whatever particular
meaning it has acquired for you (it might help if you explained that).
Im not sure if it was you that brought that up, but let me reiterate
that I dont mean a 'type cast', which is a runtime concept. A 'type
constraint' is purely a linguistic construct that will be 'compiled
out')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Steven D'Aprano
On Mon, 26 Dec 2011 01:51:30 +1100, Chris Angelico wrote:

> On Mon, Dec 26, 2011 at 1:21 AM, Roy Smith  wrote:
>> It turns out, I don't really need 20 digits.  If I can count on
>>
> "%020d" % random.randint(0,999)
>>
>> to give me 15-ish digits, that's good enough for my needs and I'll
>> probably go with that.  Thanks.
> 
> I'd say you can. The information about the Mersenne Twister underlying
> the module's functions isn't marked as "CPython Implementation Note", so
> I would expect that every Python implementation will provide a minimum
> of 53-bit precision. (It does have the feeling of an implementation
> detail though; is there a guarantee that two Pythons will generate the
> same sequence of numbers from the same seed?)

Yes.

http://docs.python.org/dev/library/random.html#notes-on-reproducibility

I think that's a new guarantee. Previously, the answer was only yes-ish: 
in theory, no guarantee was made, but in practice, you could normally 
rely on it. For example, when the Mersenne Twister became the default 
random number generator, the old generator, Wichman-Hill, was moved into 
its own module whrandom (deprecated in 2.4; now gone) for those who 
needed backwards compatibility.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Peter Otten
Chris Angelico wrote:

> On Mon, Dec 26, 2011 at 12:30 AM, Roy Smith  wrote:
>> I want to create a string of 20 random digits (I'm OK with leading
>> zeros).  The best I came up with is:
>>
>> ''.join(str(random.randint(0, 9)) for i in range(20))
>>
>> Is there something better?
> 
> The simple option is:
> random.randint(0,)
> or
> "%020d"%random.randint(0,)
> (the latter gives you a string, padded with leading zeroes). But I'm
> assuming that you discarded that option due to lack of entropy (ie you
> can't trust randint() over that huge a range).
> 
> The way I'd do it would be in chunks. The simple option is one chunk;
> your original technique is twenty. We can go somewhere in between.
> First thing to do though: ascertain how far randint() is properly
> random. The Python 2 docs [1] say that the underlying random()
> function uses 53-bit floats, so you can probably rely on about that
> much randomness; for argument's sake, let's say it's safe for up to
> 10,000 but no further (although 53 bits give you about 15 decimal
> digits).
> 
> ''.join('%04d'%random.randint(0,) for i in range(5))
> 
> For your actual task, I'd be inclined to take ten digits, twice, and
> not bother with join():
> 
> '%010d%010d'%(random.randint(0,99),random.randint(0,99))
> 
> Looks a little ugly, but it works! And only two random number calls
> (which can be expensive).

Judging from a quick look into the code (method Random._randbelow()) I'd say 
you don't need to do that unless you override Random.random() and not 
Random.getrandbits(). Even if you roll your own random() you'll get a 
warning when you run into the limit:

>>> import random
>>> random.randrange(10**20)
27709407700486201379L
>>> class R(random.Random):
... def random(self): return 4 # *
...
>>> R().randrange(10**20)
/usr/lib/python2.6/random.py:253: UserWarning: Underlying random() generator 
does not supply
enough bits to choose from a population range this large
  _warn("Underlying random() generator does not supply \n"
4L

(*) According to the literature 4 is the best random number, 9 being the 
runner-up: 
http://www.googlefight.com/index.php?lang=en_GB&word1=random+number+dilbert&word2=random+number+xkcd

A quick sanity check:

>>> from collections import Counter
>>> import random
>>> Counter(str(random.randrange(10**1)))
Counter({'9': 1060, '6': 1039, '3': 1036, '8': 1007, '7': 997, '4': 977, 
'1': 976, '5': 976, '2': 970, '0': 962})


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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Arnaud Delobelle
On Dec 25, 2011 2:55 PM, "Eelco"  wrote:
>
> On Dec 25, 2:01 am, Rick Johnson  wrote:
> > On Dec 24, 6:24 pm, alex23  wrote:
> >
> > > That you're a condescending douchebag with nothing of value to
> > > contribute?
> >
> > > Crystal.
> >
> > Take it from me Eelco. Once Alex drops into your thread and starts
> > name calling, it's over my friend.
>
> Yes, he has quite worn out my patience; whats over is our (attempts
> at) two sided communication, but I hope to continue the constructive
> lines of argument in this thread.

The real kiss of death is when you find yourself on the same side of the
"argument" as ranting Rick.

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Eelco
On Dec 25, 1:45 pm, Steven D'Aprano  wrote:
> On Sat, 24 Dec 2011 06:54:07 -0800, Eelco wrote:
> > Context dependence is not something to be avoided at all costs, but all
> > else being equal, less is certainly more. The general concept of
> > grouping thing together which parenthesis is an extremely pervasive one
> > in programming, and thus deserves its own set of context-dependent
> > rules. Packing and unpacking collections is far, far more rare,
>
> Not in Python, where it is a very common idiom.

I know we are talking about python; it was me that put that in the
title, after all. I know python makes more use of this than some
languages (and less than others; I wouldnt suggest such a verbose
syntax for a functional language for instance). Anyway,  braces are
used at least an order of magnitude more than collection packing/
unpacking in typical code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Eelco
On Dec 25, 2:01 am, Rick Johnson  wrote:
> On Dec 24, 6:24 pm, alex23  wrote:
>
> > That you're a condescending douchebag with nothing of value to
> > contribute?
>
> > Crystal.
>
> Take it from me Eelco. Once Alex drops into your thread and starts
> name calling, it's over my friend.

Yes, he has quite worn out my patience; whats over is our (attempts
at) two sided communication, but I hope to continue the constructive
lines of argument in this thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 1:21 AM, Roy Smith  wrote:
> It turns out, I don't really need 20 digits.  If I can count on
>
 "%020d" % random.randint(0,999)
>
> to give me 15-ish digits, that's good enough for my needs and I'll
> probably go with that.  Thanks.

I'd say you can. The information about the Mersenne Twister underlying
the module's functions isn't marked as "CPython Implementation Note",
so I would expect that every Python implementation will provide a
minimum of 53-bit precision. (It does have the feeling of an
implementation detail though; is there a guarantee that two Pythons
will generate the same sequence of numbers from the same seed?)

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


Re: Random string of digits?

2011-12-25 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> "%020d"%random.randint(0,)
> (the latter gives you a string, padded with leading zeroes). But I'm
> assuming that you discarded that option due to lack of entropy (ie you
> can't trust randint() over that huge a range).

Actually, the only entropy involved here is the ever increasing amount 
of it between my ears.  It never occurred to me to try that :-)

> For your actual task, I'd be inclined to take ten digits, twice, and
> not bother with join():
> 
> '%010d%010d'%(random.randint(0,99),random.randint(0,99))
> 
> Looks a little ugly, but it works! And only two random number calls
> (which can be expensive).

Hmmm.  In my case, I was looking more to optimize clarity of code, not 
speed.  This is being used during account creation on a web site, so it 
doesn't get run very often.

It turns out, I don't really need 20 digits.  If I can count on

>>> "%020d" % random.randint(0,999)

to give me 15-ish digits, that's good enough for my needs and I'll 
probably go with that.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 1:13 AM, Roy Smith  wrote:
> If you were designing the interface from scratch, you would probably
> represent that with an exception hierarchy

Or possibly with "returns a False value", giving the option of None
for none available, False for none will ever be available. Of course,
you then have to guarantee that your live return values will always
boolify as True.

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


ckjdlkfnl,ndf,nfd,fndfnkdnk mmdlssdlndnll; k; as; lkds sjdsljdlskjdsl; kdslksdl; ddlk

2011-12-25 Thread D. Mohan M. Dayalan
http;//123maza.com/48/moon670/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> On Mon, Dec 26, 2011 at 12:17 AM, Roy Smith  wrote:
> > Just for fun, I tried playing around with subclassing NoneType and
> > writing an __eq__ for my subclass.  Turns out, you can't do that:
> >
> > Traceback (most recent call last):
> >  File "./none.py", line 5, in 
> >    class Nihil(NoneType):
> > TypeError: Error when calling the metaclass bases
> >    type 'NoneType' is not an acceptable base type
> 
> Yes; unfortunately quite a few Python built-in classes can't be
> subclassed. It's an unfortunate fact of implementation, I think,
> rather than a deliberate rule.
> 
> But then, what would you ever need to subclass None for, other than
> toys and testing?

You might be to differentiate between temporary and permanent failures.  
Let's say you have a WidgetPool, containing Widgets of various classes.

class WidgetPool:
   def get_widget(class_name):
  """Return a Widget of a given class.  If there are no such
  Widgets available, returns None."""
  [...]

You might want to return a None subclass to signify, "No such Widgets 
are currently available, but they might be if you try again in a little 
while", as opposed to "No such Widgets will ever be available".

If you were designing the interface from scratch, you would probably 
represent that with an exception hierarchy.  However, if this was an old 
interface that you were modifying, this might be a way to return a 
richer failure indication for new clients without breaking backwards 
compatibility for existing code.

Of course, the existing code would probably be using "is None" tests, 
and break anyway.  But at least that's a plausible scenario for None 
subclasses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:46 AM, Steven D'Aprano
 wrote:
> class DrawableLine(Line):
>    intersection_kind = DrawablePoint

Ha! That works. I was sure there'd be some simple way to do it!

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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:48 AM, Steven D'Aprano
 wrote:
> I can't think of any other un-subclassable classes other than NoneType.
> Which ones are you thinking of?

I don't remember, but it was mentioned in a thread a little while ago.
Experimentation shows that 'bool' is one of them, though. This may
shed some light:

>>> class Foo(type(iter)):
pass

Traceback (most recent call last):
  File "", line 1, in 
class Foo(type(iter)):
TypeError: type 'builtin_function_or_method' is not an acceptable base type

I think there are certain types that are actually not implemented as
classes, and hence cannot be subclassed. This is almost certainly an
implementation detail though; my testing was done in Py3.2 (on Windows
fwiw).

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


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:48 AM, Steven D'Aprano
 wrote:
> On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:
>
>> I want to create a string of 20 random digits (I'm OK with leading
>> zeros).  The best I came up with is:
>>
>> ''.join(str(random.randint(0, 9)) for i in range(20))
>>
>> Is there something better?
>
> '%20d' % random.randint(0, 10**20-1)

I should mention that this sort of thing is absolutely acceptable in
situations where you don't actually need that level of randomness; if
you want to assign 20-digit numbers to each of ten million objects,
you can happily use something that's only really random to fifteen. I
use this technique with base 36 numbers to generate arbitrary
alphanumeric strings to use as message tags, for instance; fill out a
specified field size, even though not every combination will actually
be used.

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


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:50 AM, Chris Angelico  wrote:
> The Python 2 docs [1]

Forgot to provide link.

Python 2: http://docs.python.org/library/random.html
And same in Python 3: http://docs.python.org/py3k/library/random.html

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


Re: Random string of digits?

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:30 AM, Roy Smith  wrote:
> I want to create a string of 20 random digits (I'm OK with leading
> zeros).  The best I came up with is:
>
> ''.join(str(random.randint(0, 9)) for i in range(20))
>
> Is there something better?

The simple option is:
random.randint(0,)
or
"%020d"%random.randint(0,)
(the latter gives you a string, padded with leading zeroes). But I'm
assuming that you discarded that option due to lack of entropy (ie you
can't trust randint() over that huge a range).

The way I'd do it would be in chunks. The simple option is one chunk;
your original technique is twenty. We can go somewhere in between.
First thing to do though: ascertain how far randint() is properly
random. The Python 2 docs [1] say that the underlying random()
function uses 53-bit floats, so you can probably rely on about that
much randomness; for argument's sake, let's say it's safe for up to
10,000 but no further (although 53 bits give you about 15 decimal
digits).

''.join('%04d'%random.randint(0,) for i in range(5))

For your actual task, I'd be inclined to take ten digits, twice, and
not bother with join():

'%010d%010d'%(random.randint(0,99),random.randint(0,99))

Looks a little ugly, but it works! And only two random number calls
(which can be expensive).

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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Steven D'Aprano
On Mon, 26 Dec 2011 00:35:46 +1100, Chris Angelico wrote:

[...]
>> TypeError: Error when calling the metaclass bases
>>    type 'NoneType' is not an acceptable base type
> 
> Yes; unfortunately quite a few Python built-in classes can't be
> subclassed.


I can't think of any other un-subclassable classes other than NoneType. 
Which ones are you thinking of?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random string of digits?

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 08:30:46 -0500, Roy Smith wrote:

> I want to create a string of 20 random digits (I'm OK with leading
> zeros).  The best I came up with is:
> 
> ''.join(str(random.randint(0, 9)) for i in range(20))
> 
> Is there something better?

'%20d' % random.randint(0, 10**20-1)


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-25 Thread Steven D'Aprano
On Mon, 26 Dec 2011 00:37:22 +1100, Chris Angelico wrote:

> On Mon, Dec 26, 2011 at 12:27 AM, Steven D'Aprano
>  wrote:
>> There's nothing in the above that assumes that other has the same type
>> as self. It's just that the type of other is ignored, and the type of
>> self always wins. I find that a nice, clear rule: x.intersection(y)
>> always returns a point with the same type as x.
> 
> The intersection of DrawableLine and DrawableLine is DrawablePoint.
> That's not the same type as either of the inputs. Same if you seek the
> intersection of two planes, which is a line - or two spheres, which is a
> circle (with possible failure if they don't intersect).

class Line:
intersection_kind = Point
def intersection(self, other):
blah()
return self.intersection_kind(a, b)

class DrawableLine(Line):
intersection_kind = DrawablePoint




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:27 AM, Steven D'Aprano
 wrote:
> There's nothing in the above that assumes that other has the same type as
> self. It's just that the type of other is ignored, and the type of self
> always wins. I find that a nice, clear rule: x.intersection(y) always
> returns a point with the same type as x.

The intersection of DrawableLine and DrawableLine is DrawablePoint.
That's not the same type as either of the inputs. Same if you seek the
intersection of two planes, which is a line - or two spheres, which is
a circle (with possible failure if they don't intersect).

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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Chris Angelico
On Mon, Dec 26, 2011 at 12:17 AM, Roy Smith  wrote:
> Just for fun, I tried playing around with subclassing NoneType and
> writing an __eq__ for my subclass.  Turns out, you can't do that:
>
> Traceback (most recent call last):
>  File "./none.py", line 5, in 
>    class Nihil(NoneType):
> TypeError: Error when calling the metaclass bases
>    type 'NoneType' is not an acceptable base type

Yes; unfortunately quite a few Python built-in classes can't be
subclassed. It's an unfortunate fact of implementation, I think,
rather than a deliberate rule.

But then, what would you ever need to subclass None for, other than
toys and testing?

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


Random string of digits?

2011-12-25 Thread Roy Smith
I want to create a string of 20 random digits (I'm OK with leading 
zeros).  The best I came up with is:

''.join(str(random.randint(0, 9)) for i in range(20))

Is there something better?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-25 Thread Steven D'Aprano
On Sun, 25 Dec 2011 23:32:41 +1100, Chris Angelico wrote:

> On Sun, Dec 25, 2011 at 11:10 PM, Steven D'Aprano
>  wrote:
>> class Point:  # An abstract class.
>>    def intersect(self, other):
>>        blah; blah; blah
>>        return Point(x, y)  # No, wrong, bad!!! Don't do this.
>>
>> Instead:
>>
>>        return self.__class__(x, y)  # Better.
> 
> This would work if you were dealing with the intersection of two points,
> but how do you use that sort of trick for different classes?

There's nothing in the above that assumes that other has the same type as 
self. It's just that the type of other is ignored, and the type of self 
always wins. I find that a nice, clear rule: x.intersection(y) always 
returns a point with the same type as x.

If you want a more complicated rule, you have to code it yourself:


def intersection(self, other):
if issubclass(type(other), type(self)):
kind = type(other)
elif issubclass(type(self), type(other)):
kind = AbstractPoint
elif other.__class__ is UserPoint:
kind = UserPoint
elif today is Tuesday:
kind = BelgiumPoint
else:
kind = self.__class__
return kind(x, y)


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Roy Smith
In article ,
 Lie Ryan  wrote:

> Now, whether doing something like that is advisable or not, that's a 
> different question; however nothing in python states that you couldn't 
> have something that compare equal to None whether there is a bug or not 
> in the comparison method.

Just for fun, I tried playing around with subclassing NoneType and 
writing an __eq__ for my subclass.  Turns out, you can't do that:

Traceback (most recent call last):
  File "./none.py", line 5, in 
class Nihil(NoneType):
TypeError: Error when calling the metaclass bases
type 'NoneType' is not an acceptable base type
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 19:41:55 +0100, Thomas Rachel wrote:

>> The only times you need the brackets around a tuple is to control the
>> precedence of operations, or for an empty tuple.
> 
> IBTD:
> 
> a=((a, b) for a, b, c in some_iter)
> b=[(1, c) for ]
> 
> Without the round brackets, it is a syntax error.

Correction noted.

Nevertheless, the parentheses don't create the tuple, the comma operator 
does.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 06:47:21 -0800, Eelco wrote:

> I would like to be able to write something like:
> 
> a, middle::tuple, b = ::sequence
> 
> Where I would like the extra :: before the sequence to explicitly signal
> collection unpacking on the rhs, to maintain the symmetry with
> collection unpacking within a function call.

The :: on the right-hand side is redundant, because the left-hand side 
already explicitly signals collection unpacking of the RHS. Requiring :: 
on the RHS above is as unnecessary as it would be here:

n = len(::sequence)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 06:39:39 -0800, Eelco wrote:

> On Dec 20, 4:30 am, alex23  wrote:
>> On Dec 19, 8:15 pm, Eelco  wrote:
>>
>> > What does that have to do with collection packing/unpacking?
>>
>> It's mocking your insistance that collection unpacking is a type
>> constraint.
> 
> This is really going to be the last time I waste any words on this:

If only that were true, but after sending this post, you immediately 
followed up with FIVE more posts on this subject in less than half an 
hour.


> The sentence 'collection unpacking is a type constraint' is entirely
> nonsensical. 

How true. Given that you have now acknowledged this fact, can you please 
stop insisting that collection unpacking is a type constraint?


> A type constraint is a linguistical construct that can be
> applied in many ways; typically, to narrow down the semantics of use of
> the symbol to which the type constraint is applied.

Traceback (most recent call last):
RuntimeError: maximum recursion depth exceeded


> In case of python, collection PACKING (not unpacking) is signaled by a
> construct that can be viewed as a type constraint.

Only by doing sufficient violence to the concept of type constraint that 
it could mean *anything*.

Earlier, I insisted that a constraint is a rule that applies to input, 
not output. I haven't seen anyone, including yourself, dispute that.

Normally we would say that in the statement:

y = list(x)

there is a constraint on x, namely that it is some sort of iterable 
object (otherwise an exception will be raised), but it would be an abuse 
of language to say that there is a type constraint on y. y ends up being 
a list, true, but that isn't a constraint on y, it is an outcome.

In normal usage, "constraint" refers to pre-conditions, not post-
conditions. There are no pre-conditions on y in the above. It may not 
even exist. Contrast it with this example:

y += list(x)

where there are constraints on y: it must exist, and it must be a list, 
or something which can be added to a list.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 06:45:01 -0800, Eelco wrote:

> Can you give an example of a construct in python where two whitespace
> delimited identifiers are legal?

Not apart from the trivial case of two identifiers separated by newlines.

What's your point?


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help - obtaining the type of the object using tp_name

2011-12-25 Thread Yaşar Arabacı
I am not sure if I understood your question correctly, but I would advice  
checking this: http://docs.python.org/c-api/object.html#PyObject_Type


Sun, 25 Dec 2011 13:28:55 +0200 tarihinde Mrinalini Kulkarni  
 şöyle yazmış:



 Hello,

 I have embedded python into a vc++ app. I need to obtain type of the  
 variable defined in the python script, in my c++ code.


 PyObject *pMyObject; -> assume points to a variable defined in the  
 python script


 Now I want to do something like this

 const char * typeName;

 typeName = pMyObject->ob_type->tp_name

 Is this possible ? I tried doing this but it crashes.

 What is the alternative way for getting the name of the type from  
 python. Is there a function available for this purpose such that I can  
 obtain the address of that function using GetProcAddress and then use  
it  for determining the type. (I am required to link to python  
dynamically)


 thanks,
 MK



--
Opera'nın e-posta istemcisi ile gönderildi: http://www.opera.com/mail
--
http://mail.python.org/mailman/listinfo/python-list


Re: help - obtaining the type of the object using tp_name

2011-12-25 Thread Yaşar Arabacı
And by the way, I would advice asking these kinds of questions in
#python-dev IRC channel (Freenode). I believe you can get much better help
about your problems regarding C-api there.

2011/12/25 Mrinalini Kulkarni 

> Hello,
>
> I have embedded python into a vc++ app. I need to obtain type of the
> variable defined in the python script, in my c++ code.
>
> PyObject *pMyObject; -> assume points to a variable defined in the python
> script
>
> Now I want to do something like this
>
> const char * typeName;
>
> typeName = pMyObject->ob_type->tp_name
>
> Is this possible ? I tried doing this but it crashes.
>
> What is the alternative way for getting the name of the type from python.
> Is there a function available for this purpose such that I can obtain the
> address of that function using GetProcAddress and then use it for
> determining the type. (I am required to link to python dynamically)
>
> thanks,
> MK
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 06:54:07 -0800, Eelco wrote:

> Context dependence is not something to be avoided at all costs, but all
> else being equal, less is certainly more. The general concept of
> grouping thing together which parenthesis is an extremely pervasive one
> in programming, and thus deserves its own set of context-dependent
> rules. Packing and unpacking collections is far, far more rare, 

Not in Python, where it is a very common idiom.


> and thus
> a form that requires you to write more but remember less is certainly
> relatively favorable.

Not in Python, where iteration is a fundamental idiom and packing/
unpacking is a basic syntax construct precisely because the designer of 
the language expects it to be common and encourages its use. There are 
built-in functions designed to be used with unpacking operations, e.g. 
enumerate and zip:

for i, obj in enumerate(sequence): ...
for a, b in zip(obj, range(100)): ...


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-25 Thread Chris Angelico
On Sun, Dec 25, 2011 at 11:10 PM, Steven D'Aprano
 wrote:
> class Point:  # An abstract class.
>    def intersect(self, other):
>        blah; blah; blah
>        return Point(x, y)  # No, wrong, bad!!! Don't do this.
>
> Instead:
>
>        return self.__class__(x, y)  # Better.

This would work if you were dealing with the intersection of two
points, but how do you use that sort of trick for different classes?

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


Re: Adding an interface to existing classes

2011-12-25 Thread Steven D'Aprano
On Sat, 24 Dec 2011 17:24:14 -0800, Rick Johnson wrote:

>> class DrawablePoint( geometry.Point ):
>>     class draw( self, ... ):
>>         ...
> 
> "DrawablePoint"? I suppose there is an "ImaginaryPoint" somewhere in
> this API? Geez

No, but there's an abstract Point, which presumably refers to the 
geometric concept (hence the module, geometry) without concerning itself 
with such things as pixels, raster and vector output devices, screen 
resolutions, and all the other stuff which is needed for drawing points 
but not needed for working with points.


[...]
>> I see a problem with this, though. The intersection of two lines is
>> (usually) an object of type Point. Since DrawableLine inherits from
>> Line,
> 
> Why the hell is "Drawable" inheriting from Line? I would think that a
> "Line" would be "Drawable" object and NOT vice-versa? Am i wrong?

Probably. I think there's a case for Drawable to be an abstract mixin 
class, so that DrawableLine inherits from both Line and Drawable.


>> this means that unless I redefine the "intersect" method in
>> DrawableLine, the intersection of two DrawableLines will be a Point
>> object, not a DrawablePoint.

Not if you define intersect in Point correctly in the first place.

class Point:  # An abstract class.
def intersect(self, other):
blah; blah; blah
return Point(x, y)  # No, wrong, bad!!! Don't do this.

Instead:

return self.__class__(x, y)  # Better.


> Spencer, i would re-think this entire project from the beginning. You
> are trying to make an object out of everything. You don't need to make
> an object of EVERYTHING.

Very true.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


help - obtaining the type of the object using tp_name

2011-12-25 Thread Mrinalini Kulkarni

Hello,

I have embedded python into a vc++ app. I need to obtain type of the 
variable defined in the python script, in my c++ code.


PyObject *pMyObject; -> assume points to a variable defined in the 
python script


Now I want to do something like this

const char * typeName;

typeName = pMyObject->ob_type->tp_name

Is this possible ? I tried doing this but it crashes.

What is the alternative way for getting the name of the type from 
python. Is there a function available for this purpose such that I can 
obtain the address of that function using GetProcAddress and then use it 
for determining the type. (I am required to link to python dynamically)


thanks,
MK
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test None for an object that does not implement ==

2011-12-25 Thread Lie Ryan

On 12/25/2011 08:38 PM, Nobody wrote:


nothing should compare equal to None except for None itself, so "x is None"

> and "x == None" shouldn't produce different results unless there's a
> bug in the comparison method.

not necessarily, for example:

import random
class OddClass:
def __eq__(self, other):
return [True, False][random.randint(0, 1)]

x = OddClass()
print x == None
print x == None
print x == None
print x == None
print x == None


Now, whether doing something like that is advisable or not, that's a 
different question; however nothing in python states that you couldn't 
have something that compare equal to None whether there is a bug or not 
in the comparison method.


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


Re: Test None for an object that does not implement ==

2011-12-25 Thread Nobody
On Sat, 24 Dec 2011 23:09:50 -0800, GZ wrote:

> I run into a weird problem. I have a piece of code that looks like the
> following:
> 
> f(, a=None, c=None):
> assert  (a==None)==(c==None)
> 
> 
> The problem is that == is not implemented sometimes for values in a
> and c, causing an exception NotImplementedError.

I have no idea how that can happen. If a.__eq__(None) returns
NotImplemented, the interpreter should flip the test and perform the
equivalent of None.__eq__(a), which will return False.

> So how do I reliably test if a value is None or not?

As Paul says, use "is" to check whether a value _is_ None. Checking for
equality is almost certainly the wrong thing to do; nothing should compare
equal to None except for None itself, so "x is None" and "x == None"
shouldn't produce different results unless there's a bug in the comparison
method.

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