Re: Can global variable be passed into Python function?

2014-03-10 Thread Albert van der Horst
In article 87sir2et1d@elektro.pacujo.net,
Marko Rauhamaa  ma...@pacujo.net wrote:
Mark Lawrence breamore...@yahoo.co.uk:

 http://c2.com/cgi/wiki?SwitchStatementsSmell

Your brief summary, please, Mark?

Anyway, the first 1000 lines or so that I managed to read from that page
stated a valid principle, which however doesn't invalidate the existence
of a switch statement.

A colleague of mine taught me decades back that the whole point of OO
was the avoidance of if and switch statements. So if your code has an if
or switch statement, chances are you are doing something wrong.

I agree.

However, like all other maxims, that principle, too, has exceptions. Two
recurring examples are parsers/decoders and state machines. Sure, you
can implement states beautifully with objects/classes (and I do do that
when performance is not an issue), but having experimented with
different implementation techniques (in C, C++ and Java), I have
concluded that switch statements are often unbeatable in performance and
clarity.

I can't see why parsers decoders are any different.
The Pentium assembler in my ciforth's ``forth.lab'' library has not
a single if statement and I reckon it is a superior design.
(State is kept in an ai blackboard fashion in bitmaps.)
Forth has of course a built in look it up, then execute it,
which could be regarded as a giant switch.


And I sometimes run into convoluted factory (anti)patterns whose sole
purpose is to avoid straightforward switch statements in a decoder.


Marko
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: Can global variable be passed into Python function?

2014-03-10 Thread Marko Rauhamaa
alb...@spenarnc.xs4all.nl (Albert van der Horst):

 I can't see why parsers decoders are any different. The Pentium
 assembler in my ciforth's ``forth.lab'' library has not a single if
 statement and I reckon it is a superior design. (State is kept in an
 ai blackboard fashion in bitmaps.) Forth has of course a built in
 look it up, then execute it, which could be regarded as a giant
 switch.

Isn't this the idea of using Python dicts as hand-compiled switch
statements?


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


Re: [OT] Can global variable be passed into Python function?

2014-03-03 Thread Grant Edwards
On 2014-03-02, Chris Angelico ros...@gmail.com wrote:
 On Mon, Mar 3, 2014 at 3:55 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 02/03/2014 16:45, Grant Edwards wrote:


 That's irrelevent.  The actual location of the memory containing the
 struct object (static, stack, heap, shared) doesn't matter.  The
 address of the first field in a struture object _is_ the address of
 the structure object.


 You say struture, I'll say structure, let's call the whole thing off :)

:)

 Note that, technically, Grant is correct as long as you grant (heh)
 that a structure may have an invisible member, the virtual function
 table pointer. C++ only (I don't believe C has virtual functions -
 but it may have grown them in one of the newer standards), so in C,
 all members are public.

Yes. I was talking about C, not C++.  I made that quite clear in
portions of my post that have been elided.  In C there is no such
thing as a virtual table pointer.

-- 
Grant Edwards   grant.b.edwardsYow! We have DIFFERENT
  at   amounts of HAIR --
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] Can global variable be passed into Python function?

2014-03-03 Thread Chris Angelico
On Tue, Mar 4, 2014 at 1:18 AM, Grant Edwards invalid@invalid.invalid wrote:
 Note that, technically, Grant is correct as long as you grant (heh)
 that a structure may have an invisible member, the virtual function
 table pointer. C++ only (I don't believe C has virtual functions -
 but it may have grown them in one of the newer standards), so in C,
 all members are public.

 Yes. I was talking about C, not C++.  I made that quite clear in
 portions of my post that have been elided.  In C there is no such
 thing as a virtual table pointer.

I wasn't certain of the newer C standards. C's been gaining all sorts
of features, not all of which are necessary, and it's entirely
possible based on my current knowledge that C specifies #include
antigravity ...

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Grant Edwards invalid@invalid.invalid:

 any decent compiler should be able to generate the same code for a
 switch statement and for an equivalent chained if/else.

It's not so easy to be decent, especially when it comes to a language as
dynamic as Python.


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Roy Smith r...@panix.com:

 Python already has a switch statement.  It's just spelled funny...

 [...]

 try:
raise value
 except Case1:
print did case 1
 except (Case2, Case3):
print did either case 2 or 3
 else:
print did default

Not bad! Definitely worth considering.

 No fall-through, however.

Fall-trough is an unfortunate C syntax accident, not a feature worth
emulating.


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Ben Finney ben+pyt...@benfinney.id.au:

 The unreliability is “will objects defined elsewhere have a different
 identity?”

That question is not interesting in my context, and has no bearing on
the correctness of the program.


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Steven D'Aprano
On Sat, 01 Mar 2014 19:29:41 +0200, Marko Rauhamaa wrote:

 Michael Torrie torr...@gmail.com:
 
 No, '==' works fine no matter what objects you assign to your state
 variables.
 
 Well, it doesn't since
 
 a = float(nan)
 a is a
True
 a == a
False

No, that is working correctly, so the comment that equals works fine is 
correct: returning False is the correct thing to do if one or both of the 
objects are a NAN. NANs are supposed to compare unequal to everything, 
including themselves.

The is operator and the == operator do not have the same purpose and they 
do not do the same thing. is should not be considered an improved == 
without the quirks, this is not PHP and we're not comparing == and ===. 
The argument here is not about which operator performs the check we want, 
but over what check we want: do we want an identity test or an equality 
test?



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 On Sat, 01 Mar 2014 19:29:41 +0200, Marko Rauhamaa wrote:
 Michael Torrie torr...@gmail.com:
 No, '==' works fine no matter what objects you assign to your state
 variables.
 
 Well, it doesn't since
 
 a = float(nan)
 a is a
True
 a == a
False

 No, that is working correctly, so the comment that equals works fine
 is correct: returning False is the correct thing to do if one or both
 of the objects are a NAN. NANs are supposed to compare unequal to
 everything, including themselves.

Nobody is saying there's a bug in the implementation of ==. I'm just
saying == cannot be taken as a universal superset of is. Therefore
a program cannot blindly use == to test for identity.

That's why == is a bit fishy. It immediately raises the question: what
does it mean for a == b, especially since the exact implementation of a
and b are intended to be opaque.

Example:

The os module defines the constants os.SEEK_SET, os.SEEK_CUR and
os.SEEK_END that can be used as arguments for os.lseek(). Must those
constants be used, or can a regular integer be used instead? The
documentation clearly states that integers can be used:

   SEEK_SET or 0 to set the position relative to the beginning of the
   file; SEEK_CUR or 1 to set it relative to the current position;
   SEEK_END or 2 to set it relative to the end of the file.

However, on the same reference page, os.posix_fadvise() is defined. We
read:

   advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
   POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or
   POSIX_FADV_DONTNEED

and:

os.POSIX_FADV_NORMAL
os.POSIX_FADV_SEQUENTIAL
os.POSIX_FADV_RANDOM
os.POSIX_FADV_NOREUSE
os.POSIX_FADV_WILLNEED
os.POSIX_FADV_DONTNEED

Flags that can be used in advice in posix_fadvise()

Now, what kinds of object are those constants? We are not supposed to
know or care. We could peek into the implementation, but it would be a
grave mistake to trust the implementation choices in the application.

So in my application code I might set:

   favd_flag = os.POSIX_FADV_RANDOM

in some other part of my code I might want to see how flag was set.
Should I use == or is to test it?

If I take the API documentation on its face value, I *must* use == for
os.SEEK*:

if seek_flag == os.SEEK_END:
...

and I *must* use is for os.POSIX_FAVD_*:

if fsavd_flag is os.POSIX_FADV_RANDOM:
...

Since, for all I know, os.POSIX_FAVD_RANDOM might return a random value
for __eq__().


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Marko Rauhamaa ma...@pacujo.net:

 If I take the API documentation on its face value, [...]
 I *must* use is for os.POSIX_FAVD_*:

 if fsavd_flag is os.POSIX_FADV_RANDOM:
 ...

However, since a documentation flaw is more than likely, it is even more
prudent to avoid both == and is and create a set of shadow constants
in the application code:

  if self.fsavd_flag is self.FAVD_RANDOM:
  os.posix_fadvice(fd, offset, len, os.POSIX_FAVD_RANDOM):


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Sun, Mar 2, 2014 at 8:35 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 However, on the same reference page, os.posix_fadvise() is defined. We
 read:

advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or
POSIX_FADV_DONTNEED

 Now, what kinds of object are those constants? We are not supposed to
 know or care. We could peek into the implementation, but it would be a
 grave mistake to trust the implementation choices in the application.

 So in my application code I might set:

favd_flag = os.POSIX_FADV_RANDOM

 in some other part of my code I might want to see how flag was set.
 Should I use == or is to test it?

In the absence of any advice to the contrary, I would use == to test.
The flags are most likely to be, in order:

* An enumeration, in a sufficiently new Python
* Integers
* Strings
* Arbitrary object()s

All of the above will compare correctly with ==, and if someone stuffs
in an object that compares equal to more than one of them, they're
likely to have problems at the far end. If identity is really crucial,
I would expect there to be a comment in the docs.

And there's another thing you can do to test.

 import os
 type(os.POSIX_FADV_RANDOM)
class 'int'

So use ==. If it's later changed and you have to instead use 'is', you
can change your code.

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 And there's another thing you can do to test.

 import os
 type(os.POSIX_FADV_RANDOM)
 class 'int'

Is that what you do in your programs?

 So use ==. If it's later changed and you have to instead use 'is', you
 can change your code.

Quite a robust API, huh?

Anyway, you recognize that the API definer is within their rights to
require 'is' semantics for the constants. IOW, the application must use
the given constant objects and nothing that happens to be == to them.

Consequently, the implementer is within their rights to define:

   def __eq__():
   return True


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Steven D'Aprano
On Sun, 02 Mar 2014 11:35:43 +0200, Marko Rauhamaa wrote:

 Nobody is saying there's a bug in the implementation of ==. I'm just
 saying == cannot be taken as a universal superset of is. Therefore a
 program cannot blindly use == to test for identity.

Um, yes? Nor can you use  to test for identity, or +, or %, or any 
other operator other than is. Why do you think it is a problem that == 
doesn't test for identity? It's not supposed to test for identity.

Why do you want to test for identity? I think I've asked five times now, 
why you care whether a state value has one instance or a thousand 
instances, and you haven't even attempted an answer.



 That's why == is a bit fishy. It immediately raises the question: what
 does it mean for a == b, especially since the exact implementation of a
 and b are intended to be opaque.

It means that a equals b. For ints, it means that they have the same 
numeric value. The same applies for floats. For strings, it means that 
they contain the same code points in the same order. And so on. For all 
built-in types, equality is well-defined. For custom types you create 
yourself, the onus is on you to ensure that equality is meaningful and 
well-defined.


 Example:
 
 The os module defines the constants os.SEEK_SET, os.SEEK_CUR and
 os.SEEK_END that can be used as arguments for os.lseek(). Must those
 constants be used, or can a regular integer be used instead? The
 documentation clearly states that integers can be used:
 
SEEK_SET or 0 to set the position relative to the beginning of the
file; SEEK_CUR or 1 to set it relative to the current position;
SEEK_END or 2 to set it relative to the end of the file.
 
 However, on the same reference page, os.posix_fadvise() is defined. We
 read:
 
advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or
POSIX_FADV_DONTNEED
 
 and:
 
 os.POSIX_FADV_NORMAL
 os.POSIX_FADV_SEQUENTIAL
 os.POSIX_FADV_RANDOM
 os.POSIX_FADV_NOREUSE
 os.POSIX_FADV_WILLNEED
 os.POSIX_FADV_DONTNEED
 
 Flags that can be used in advice in posix_fadvise()
 
 Now, what kinds of object are those constants? We are not supposed to
 know or care.

Incorrect. We are supposed to know and care.

os.posix is exactly the sort of library I mentioned earlier when I said 
sometimes you're constrained by compatibility with some other system. In 
this case, the os module is explicitly designed to be compatible with the 
POSIX interface, which is defined to use certain integer values as flags. 
This is not an implementation choice which implementers can change at 
will, it is part of the interface.

The specific *values* possibly may be allowed to vary from platform to 
platform, and since this is C even the definition of int may be 
platform specific, but not that fact that they are ints. Hence the value 
of POSIX_FADV_RANDOM could, theoretically, be different under Linux and 
FreeBSD (say). It probably isn't, but it could be. If you hard-code the 
magic number 1 in your code, you're risking the (tiny) chance of it 
failing on some obscure POSIX system. But that doesn't imply that we must 
test for object identity. There could be a million different instances, 
all with the value POSIX_FADV_RANDOM.

Python does not guarantee that there is only a single 1 instance. If you 
want to test whether a value is os.POSIX_FADV_RANDOM, the right way is to 
compare that value for equality with os.POSIX_FADV_RANDOM, not identity.


 We could peek into the implementation, but it would be a
 grave mistake to trust the implementation choices in the application.
 So in my application code I might set:
 
favd_flag = os.POSIX_FADV_RANDOM

A much better choice than hard-coding the magic value 1. But that choice 
has absolutely nothing to do with whether 1 is a singleton or not.


 in some other part of my code I might want to see how flag was set.
 Should I use == or is to test it?

Equals, of course. There is absolutely no question about that. To even 
*think* that you should test it with is means that you have completely 
misunderstood what you are doing here. Why are you relying on an 
implementation detail that CPython happens to cache and reuse small 
integers like 1? What happens if you run your code under an 
implementation of Python that doesn't cache small ints? Or if your 
platform happens to set POSIX_FADV_RANDOM to a non-cached value like 
8531201?

Python does not promise that POSIX_FADV_RANDOM will be a singleton value. 
Using is is unsafe.


 If I take the API documentation on its face value, I *must* use == for
 os.SEEK*:

Correct.


 if seek_flag == os.SEEK_END:
 ...
 
 and I *must* use is for os.POSIX_FAVD_*:

Incorrect.


 if fsavd_flag is os.POSIX_FADV_RANDOM:
 ...
 
 Since, for all I know, os.POSIX_FAVD_RANDOM might return a random value
 for __eq__().

For all *you* know, perhaps, but since os.posix_fadvise is a thin wrapper 

Re: Can global variable be passed into Python function?

2014-03-02 Thread Ben Finney
Marko Rauhamaa ma...@pacujo.net writes:

 Ben Finney ben+pyt...@benfinney.id.au:

  The unreliability is “will objects defined elsewhere have a different
  identity?”

 That question is not interesting in my context, and has no bearing on
 the correctness of the program.

You keep vacillating between two positions: pick one for the context.

Either you care about object identity in this context, and the above
observation is relevant.

Or, you don't care about object identity in this context, and you should
avoid ‘is’ and use ‘==’.

But you cannot have both.

-- 
 \“You know I could rent you out as a decoy for duck hunters?” |
  `\ —Groucho Marx |
_o__)  |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 On Sun, 02 Mar 2014 11:35:43 +0200, Marko Rauhamaa wrote:
 Now, what kinds of object are those constants? We are not supposed to
 know or care.

 Incorrect. We are supposed to know and care.

Then, the documentation is seriously flawed. It gives no hint whatsoever
on the nature of those objects.

 os.posix is exactly the sort of library I mentioned earlier when I
 said sometimes you're constrained by compatibility with some other
 system. In this case, the os module is explicitly designed to be
 compatible with the POSIX interface, which is defined to use certain
 integer values as flags. This is not an implementation choice which
 implementers can change at will, it is part of the interface.

The values of those Python constants don't need to have any relationship
with those of the underlying operating system.

 Python does not guarantee that there is only a single 1 instance.

Nobody has ever argued such a thing. I certainly haven't.

However, nothing in the API spec gives you the right to call the
function with an integer.

 If you want to test whether a value is os.POSIX_FADV_RANDOM, the right
 way is to compare that value for equality with os.POSIX_FADV_RANDOM,
 not identity.

That might well be true but is not explicitly or implicitly specified in
the documentation. (The os.SEEK_* constants are explicitly defined.)

 Since, for all I know, os.POSIX_FAVD_RANDOM might return a random value
 for __eq__().

 For all *you* know, perhaps, but since os.posix_fadvise is a thin
 wrapper around the POSIX C function fadvise, and that is documented as
 expecting ints for the advice parameter, that cannot be the case.

A pretty serious documentation flaw, then. Misleading even.

I take it from the documentation that you *must* use the given constant
objects and not some improvised integers.

 That the os module is a thin wrapper around os- specific services may
 not be explicitly stated, but it is nevertheless true.

The example was given for illustration purposes; any criticism against
the accuracy of the documentation is a sideshow.


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Mark Lawrence

On 02/03/2014 10:59, Ben Finney wrote:

Marko Rauhamaa ma...@pacujo.net writes:


Ben Finney ben+pyt...@benfinney.id.au:


The unreliability is “will objects defined elsewhere have a different
identity?”


That question is not interesting in my context, and has no bearing on
the correctness of the program.


You keep vacillating between two positions: pick one for the context.

Either you care about object identity in this context, and the above
observation is relevant.

Or, you don't care about object identity in this context, and you should
avoid ‘is’ and use ‘==’.

But you cannot have both.



Unless you're a troll.

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Mark Lawrence

On 02/03/2014 09:35, Marko Rauhamaa wrote:

Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:


On Sat, 01 Mar 2014 19:29:41 +0200, Marko Rauhamaa wrote:

Michael Torrie torr...@gmail.com:

No, '==' works fine no matter what objects you assign to your state
variables.


Well, it doesn't since

 a = float(nan)
 a is a
True
 a == a
False


No, that is working correctly, so the comment that equals works fine
is correct: returning False is the correct thing to do if one or both
of the objects are a NAN. NANs are supposed to compare unequal to
everything, including themselves.


Nobody is saying there's a bug in the implementation of ==. I'm just
saying == cannot be taken as a universal superset of is. Therefore
a program cannot blindly use == to test for identity.

That's why == is a bit fishy. It immediately raises the question: what
does it mean for a == b, especially since the exact implementation of a
and b are intended to be opaque.

Example:

The os module defines the constants os.SEEK_SET, os.SEEK_CUR and
os.SEEK_END that can be used as arguments for os.lseek(). Must those
constants be used, or can a regular integer be used instead? The
documentation clearly states that integers can be used:

SEEK_SET or 0 to set the position relative to the beginning of the
file; SEEK_CUR or 1 to set it relative to the current position;
SEEK_END or 2 to set it relative to the end of the file.

However, on the same reference page, os.posix_fadvise() is defined. We
read:

advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or
POSIX_FADV_DONTNEED

and:

 os.POSIX_FADV_NORMAL
 os.POSIX_FADV_SEQUENTIAL
 os.POSIX_FADV_RANDOM
 os.POSIX_FADV_NOREUSE
 os.POSIX_FADV_WILLNEED
 os.POSIX_FADV_DONTNEED

 Flags that can be used in advice in posix_fadvise()

Now, what kinds of object are those constants? We are not supposed to
know or care. We could peek into the implementation, but it would be a
grave mistake to trust the implementation choices in the application.

So in my application code I might set:

favd_flag = os.POSIX_FADV_RANDOM

in some other part of my code I might want to see how flag was set.
Should I use == or is to test it?

If I take the API documentation on its face value, I *must* use == for
os.SEEK*:

 if seek_flag == os.SEEK_END:
 ...

and I *must* use is for os.POSIX_FAVD_*:

 if fsavd_flag is os.POSIX_FADV_RANDOM:
 ...

Since, for all I know, os.POSIX_FAVD_RANDOM might return a random value
for __eq__().


Marko



Will you please be kind enough to stop writing this drivel.  You've been 
told repeatedly that you don't know what you're talking about, so have 
the decency to just belt up.  Now try testing these words for identity.


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Dave Angel
 Chris Angelico ros...@gmail.com Wrote in message:
 On Sun, Mar 2, 2014 at 3:02 PM, Dave Angel da...@davea.name wrote:
 The quote you make from the C standard doesn't mention malloc,  so
  you're arguing different things. It's not the compiler that casts
  the malloc return value to the struct type.

 C++ does implicitly convert the result,  and the return value of
  new already has the struct type. But the runtime stores at least
  two kinds of overhead on occasion,  the array size, and the
  vtable. So the malloc address can not be assumed to match the
  struct beginning.  (Not even considering that one can override
 
 Whatever pointer malloc returns is the beginning of the *usable*
 space. Any overhead for array size etc has to be before that; a
 virtual function table pointer would be inside that space, but that's
 very much compiler-dependent.
 

Sure,  for some definition of usable.  Overhead such as block
 size, freelist pointer etc., are obviously outside of the
 returned block.  But the array size that's specified in a call to
 new [], and the vptr, are definitely inside the malloc'ed block,
 and may be before the struct data.

-- 
DaveA

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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Mon, Mar 3, 2014 at 12:22 AM, Dave Angel da...@davea.name wrote:
 Sure,  for some definition of usable.  Overhead such as block
  size, freelist pointer etc., are obviously outside of the
  returned block.  But the array size that's specified in a call to
  new [], and the vptr, are definitely inside the malloc'ed block,
  and may be before the struct data.

Hmm. Last I was working with it, the array size to new[] was outside
the block, just as the block size to malloc(). The vptr is part of any
struct/class with virtual functions, and effectively acts as a hidden
class member, so you get one of those inside the block, and it's
included in sizeof.

//Allocated Space: The Final Frontier!
#include stdio.h //cout sucks :)

class Foo
{
int x;
int y;
int z;
};

class Bar
{
int x;
int y;
int z;
virtual int get_x() {return x;}
};

int main()
{
printf(sizeof(int) = %u\n,sizeof(int));
printf(sizeof(int*) = %u\n,sizeof(int*));
printf(sizeof(Foo) = %u\n,sizeof(Foo));
printf(sizeof(Bar) = %u\n,sizeof(Bar));
Foo *foo = new Foo[10];
printf(foo = %p/%p = %u\n,foo,foo+10,(char *)(foo+10)-(char *)foo);
Bar *bar = new Bar[10];
printf(bar = %p/%p = %u\n,bar,bar+10,(char *)(bar+10)-(char *)bar);
return 0;
}


rosuav@sikorsky:~$ g++ frontier.cpp  ./a.out
sizeof(int) = 4
sizeof(int*) = 8
sizeof(Foo) = 12
sizeof(Bar) = 24
foo = 0xf38010/0xf38088 = 120
bar = 0xf38090/0xf38180 = 240



The rules of structs are that they be contiguous, that they be laid
out sequentially, and that any padding needed between structures is at
the end of the previous one (which is why three of 4 bytes makes 12
bytes, but three of 4 bytes plus 8 bytes makes 24 - the eight-byte
pointer has to be aligned on a multiple of eight bytes, so having a
20-byte structure that starts with an 8-byte pointer is a no-no). The
allocated block of memory is, by definition, the same as the pointer
to its first element. As it happens, the pointer bar is not synonymous
with bar-x, bar-y, or bar-z, which means the vptr is at the
beginning of bar, which makes sense; but the compiler's not obliged to
do that, and in some cases may choose not to - for instance, if bar
(with a virtual function) inherited from foo (with none), it might be
convenient to allow a pointer-cast to not change the value of the
pointer. (g++ 4.7.2 still puts the vptr at the beginning of bar in
that case, but other compilers or other versions may differ.)

Array size is outside the block, presumably before it, as foo[0] is
by definition identical to foo, and there's no room inside the
structure for any spare data. Virtual function table is inside the
block because it's a hidden member of the object (like __class__ in
Python, only better hidden).

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Marko Rauhamaa ma...@pacujo.net:

 Roy Smith r...@panix.com:

 Python already has a switch statement.  It's just spelled funny...

 [...]

 try:
raise value
 except Case1:
print did case 1
 except (Case2, Case3):
print did either case 2 or 3
 else:
print did default

 Not bad! Definitely worth considering.

I wrote a simple test that switched between 26 enums using three
techniques and measured execution times (2,600,000 switching
operations). I also measured the time with no switching and subtracted
that time from the test times.

Results of the competition (performed with python3.2.3):

1. DICT DISPATCH TABLE (0.2 µs/switch)

2. IF-ELSE CHAIN (850% slower than DICT DISPATCH TABLE)

3. TRY-EXCEPT (3500% slower than DICT DISPATCH TABLE)


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Roy Smith
In article 87fvn08vux@elektro.pacujo.net,
 Marko Rauhamaa ma...@pacujo.net wrote:

 Marko Rauhamaa ma...@pacujo.net:
 
  Roy Smith r...@panix.com:
 
  Python already has a switch statement.  It's just spelled funny...
 
  [...]
 
  try:
 raise value
  except Case1:
 print did case 1
  except (Case2, Case3):
 print did either case 2 or 3
  else:
 print did default
 
  Not bad! Definitely worth considering.
 
 [...]
 3. TRY-EXCEPT (3500% slower than DICT DISPATCH TABLE)

I'm glad to hear that.  I hope nobody took me seriously when I suggested 
this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Roy Smith r...@panix.com:

 In article 87fvn08vux@elektro.pacujo.net,
  Marko Rauhamaa ma...@pacujo.net wrote:
 3. TRY-EXCEPT (3500% slower than DICT DISPATCH TABLE)

 I'm glad to hear that. I hope nobody took me seriously when I
 suggested this.

I actually have employed the idea before in a related but slightly
different use case.

Anyway, it's extremely close to the switch statement's use case and
should give some guidance if a proper switch statement is ever worked
into the language. What's killing the performance is the backtrace
generation and longjmp trickery. If an analogous syntax could be (A)
separated from BaseException and (B) compiled into a dict, we could have
a winner.


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Mon, Mar 3, 2014 at 2:52 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 Roy Smith r...@panix.com:

 In article 87fvn08vux@elektro.pacujo.net,
  Marko Rauhamaa ma...@pacujo.net wrote:
 3. TRY-EXCEPT (3500% slower than DICT DISPATCH TABLE)

 I'm glad to hear that. I hope nobody took me seriously when I
 suggested this.

 I actually have employed the idea before in a related but slightly
 different use case.

 Anyway, it's extremely close to the switch statement's use case and
 should give some guidance if a proper switch statement is ever worked
 into the language. What's killing the performance is the backtrace
 generation and longjmp trickery. If an analogous syntax could be (A)
 separated from BaseException and (B) compiled into a dict, we could have
 a winner.

The trouble is, try/except fundamentally can't be compiled into a
dict, because Python's exception handling is based on subclasses.

try: func()
except FileNotFoundError: pass
except OSError: raise RuntimeError(Oops)
except Exception as e: log(e)
except: log(Aborting!); raise
finally: log(Done)

How would you handle that with a dict? It's inherently ordered - a
FileNotFoundError would be caught by any one of those clauses, and
since there's no sane way to pick the narrowest, the best way to
handle it is sequential evaluation. (Also, it's worth noting that
exception lists are not constants. It's possible to do downright
insane things like calling a function to figure out what exceptions to
handle. Yeah, that's pretty stupid, right there.)

A switch block that works with constants and equality *can* be turned
into a dict. If the constants are hashable, use them as the keys
directly; if they're not hashable and/or you want to use object
identity as the criterion (effectively like using 'is' rather than
'==' for your case statements), use id(x) as the keys, and make sure
you have other references to the objects. Then it'll be fine as a
straight-up dict.

If the switch block uses inequalities, then it suffers from the same
problem as the try/except block - it's inherently ordered, in case
(pun intended) there's a switched-on value that matches more than one.
(You could possibly optimize the int case, but that would be way WAY
too specific for a generic language structure.)

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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Grant Edwards
On 2014-03-02, Dave Angel da...@davea.name wrote:
  Grant Edwards invalid@invalid.invalid Wrote in message:
 On 2014-02-24, Michael Torrie torr...@gmail.com wrote:


 Why would you think that? The address of the start of your malloc'ed
 structure is the same as the address of the first element.  Surely
 this is logical?
 
 Not only is it logical, the C standard explicitly requires it.  Here's
 a second-hand citation since I don't happend to have an actual copy of
 the standard on hand:
 
 C1x ???6.7.2.1.13:
 
A pointer to a structure object, suitably converted, points to
its initial member ... and vice versa. There may be unnamed
padding within a structure object, but not at its beginning.

 The quote you make from the C standard doesn't mention malloc,  so
 you're arguing different things.

No, I'm not.  A pointer to a structure object and a pointer to it's
first field are the same.  It doesn't matter where the object came
from.

 It's not the compiler that casts the malloc return value to the
 struct type.

That's irrelevent.  The actual location of the memory containing the
struct object (static, stack, heap, shared) doesn't matter.  The
address of the first field in a struture object _is_ the address of
the structure object.

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Mark Lawrence

On 02/03/2014 16:23, Chris Angelico wrote:


A switch block that works with constants and equality *can* be turned
into a dict. If the constants are hashable, use them as the keys
directly; if they're not hashable and/or you want to use object
identity as the criterion (effectively like using 'is' rather than
'==' for your case statements), use id(x) as the keys, and make sure
you have other references to the objects. Then it'll be fine as a
straight-up dict.

If the switch block uses inequalities, then it suffers from the same
problem as the try/except block - it's inherently ordered, in case
(pun intended) there's a switched-on value that matches more than one.
(You could possibly optimize the int case, but that would be way WAY
too specific for a generic language structure.)

ChrisA



You clearly don't get my point.  I *DON'T* want to use stupid constants 
and stupid equalities, I want to use identities.  I *DON'T* want to use 
stupid ==, I want to use 'is'.  I *DON'T* care how many people with 
years of experience of Python tell me that this is the wrong thing to 
do, that is how I am going to do it.  So, for the final time of asking, 
how do I do the above with, and only with, the identity, even if you 
stupidly keep on trying to tell me that this is wrong?


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Mark Lawrence

On 02/03/2014 16:45, Grant Edwards wrote:


That's irrelevent.  The actual location of the memory containing the
struct object (static, stack, heap, shared) doesn't matter.  The
address of the first field in a struture object _is_ the address of
the structure object.



You say struture, I'll say structure, let's call the whole thing off :)

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Michael Torrie
On 03/02/2014 03:07 AM, Chris Angelico wrote:
 
 import os
 type(os.POSIX_FADV_RANDOM)
 class 'int'
 
 So use ==. If it's later changed and you have to instead use 'is', you
 can change your code.

I don't see why == wouldn't continue to work if os.POSIX_FADV_RANDOM
became an object of a different type.

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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Dave Angel
 Chris Angelico ros...@gmail.com Wrote in message:
 On Mon, Mar 3, 2014 at 12:22 AM, Dave Angel da...@davea.name wrote:
 Sure,  for some definition of usable.  Overhead such as block
  size, freelist pointer etc., are obviously outside of the
  returned block.  But the array size that's specified in a call to
  new [], and the vptr, are definitely inside the malloc'ed block,
  and may be before the struct data.
 
 Hmm. Last I was working with it, the array size to new[] was outside
 the block, just as the block size to malloc(). The vptr is part of any
 struct/class with virtual functions, and effectively acts as a hidden
 class member, so you get one of those inside the block, and it's
 included in sizeof.
 
 //Allocated Space: The Final Frontier!
 #include stdio.h //cout sucks :)
 
 class Foo
 {
 int x;
 int y;
 int z;
 };
 
 class Bar
 {
 int x;
 int y;
 int z;
 virtual int get_x() {return x;}
 };
 
 int main()
 {
 printf(sizeof(int) = %u\n,sizeof(int));
 printf(sizeof(int*) = %u\n,sizeof(int*));
 printf(sizeof(Foo) = %u\n,sizeof(Foo));
 printf(sizeof(Bar) = %u\n,sizeof(Bar));
 Foo *foo = new Foo[10];
 printf(foo = %p/%p = %u\n,foo,foo+10,(char *)(foo+10)-(char *)foo);
 Bar *bar = new Bar[10];
 printf(bar = %p/%p = %u\n,bar,bar+10,(char *)(bar+10)-(char *)bar);
 return 0;
 }
 
 
 rosuav@sikorsky:~$ g++ frontier.cpp  ./a.out
 sizeof(int) = 4
 sizeof(int*) = 8
 sizeof(Foo) = 12
 sizeof(Bar) = 24
 foo = 0xf38010/0xf38088 = 120
 bar = 0xf38090/0xf38180 = 240
 
 
 
 The rules of structs are that they be contiguous, that they be laid
 out sequentially, and that any padding needed between structures is at
 the end of the previous one (which is why three of 4 bytes makes 12
 bytes, but three of 4 bytes plus 8 bytes makes 24 - the eight-byte
 pointer has to be aligned on a multiple of eight bytes, so having a
 20-byte structure that starts with an 8-byte pointer is a no-no). The
 allocated block of memory is, by definition, the same as the pointer
 to its first element. As it happens, the pointer bar is not synonymous
 with bar-x, bar-y, or bar-z, which means the vptr is at the
 beginning of bar, which makes sense; but the compiler's not obliged to
 do that, and in some cases may choose not to - for instance, if bar
 (with a virtual function) inherited from foo (with none), it might be
 convenient to allow a pointer-cast to not change the value of the
 pointer. (g++ 4.7.2 still puts the vptr at the beginning of bar in
 that case, but other compilers or other versions may differ.)
 
 Array size is outside the block, presumably before it, as foo[0] is
 by definition identical to foo, and there's no room inside the
 structure for any spare data. Virtual function table is inside the
 block because it's a hidden member of the object (like __class__ in
 Python, only better hidden).
 

Array size is inside the malloc block, but outside the struct
 block.  As you can see if you try to delete without the brackets
 when you used new [], some runtimes will crash. 

This is not to say that there will always be these extra offsets, 
 just that they can be there.

-- 
DaveA

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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Mon, Mar 3, 2014 at 3:55 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 On 02/03/2014 16:45, Grant Edwards wrote:


 That's irrelevent.  The actual location of the memory containing the
 struct object (static, stack, heap, shared) doesn't matter.  The
 address of the first field in a struture object _is_ the address of
 the structure object.


 You say struture, I'll say structure, let's call the whole thing off :)

:)

Note that, technically, Grant is correct as long as you grant (heh)
that a structure may have an invisible member, the virtual function
table pointer. C++ only (I don't believe C has virtual functions - but
it may have grown them in one of the newer standards), so in C, all
members are public.

With an array, the array's pointer *is* the same as the pointer to its
first member, because adding zero to a pointer does nothing, and x -
x[0] - (*(x+0)).

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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Mon, Mar 3, 2014 at 6:17 AM, Dave Angel da...@davea.name wrote:
 Array size is inside the malloc block, but outside the struct
  block.  As you can see if you try to delete without the brackets
  when you used new [], some runtimes will crash.

As in, you have to use delete [] x to correspond with x = new
whatever[n]? Yes, that's right, but that array size is earlier in
memory than x itself. I can pretend that x is the same as one declared
statically as whatever x[n], and it'll function the same way. When
new[] is implemented using malloc(), it'll be something like this:

{
data = malloc(n * sizeof(whatever) + sizeof n);
*(int *)data = n;
return ((int *)data)+1;
}

so in that case, the array size is inside the malloc'd block, but it's
still invisible to the calling function. A fully compliant C++
implementation could choose to store that elsewhere, in some kind of
lookup table - it could then easily catch bugs like delete
malloc(1), delete [] malloc(1), delete [] new whatever, and
delete new whatever[1] (because the pointer given wouldn't be in the
'new' table or the 'new[]' table, respectively).

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Michael Torrie torr...@gmail.com:

 I don't see why == wouldn't continue to work if os.POSIX_FADV_RANDOM
 became an object of a different type.

It probably would.

If one were begging for trouble, one *could* define:

   class ABC:
   A = 1
   B = 1.0
   C = 1+0j

Now:

   ABC.A == ABC.B
   ABC.B == ABC.C
   ABC.C == ABC.A

but:

   ABC.A is not ABC.B
   ABC.B is not ABC.C
   ABC.C is not ABC.A


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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Roy Smith
In article 87txbg48kd@elektro.pacujo.net,
 Marko Rauhamaa ma...@pacujo.net wrote:

 Michael Torrie torr...@gmail.com:
 
  I don't see why == wouldn't continue to work if os.POSIX_FADV_RANDOM
  became an object of a different type.
 
 It probably would.
 
 If one were begging for trouble, one *could* define:
 
class ABC:
A = 1
B = 1.0
C = 1+0j
 
 Now:
 
ABC.A == ABC.B
ABC.B == ABC.C
ABC.C == ABC.A
 
 but:
 
ABC.A is not ABC.B
ABC.B is not ABC.C
ABC.C is not ABC.A
 
 
 Marko

On can do all sorts of bizarre things.  If you wish to shoot yourself in 
the foot, Python is happy to provide the gun.

class ABC(object):
_instance = None
def __new__(cls):
if cls._instance is None:
i = object.__new__(cls)
i.__class__ = ABC
cls._instance = i
return cls._instance

def __eq__(self, other):
return False

a = ABC()
b = ABC()

print a is b
print a == b
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-02 Thread Chris Angelico
On Mon, Mar 3, 2014 at 8:03 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 If one were begging for trouble, one *could* define:

class ABC:
A = 1
B = 1.0
C = 1+0j

You're missing the point of flags, though. One does not use floats for
flags. Flags are normally going to be integers (passed directly to an
underlying C API), strings (self-documenting), or arbitrary objects
with no value beyond their identities. In all cases, value equality is
the normal way to recognize them, except in the special case of
bit-flag integers, where you use bitwise operations (and then equality
checks, possibly):

DIRECTORY = 512 # Not sure that one's right, tbh
OWNER_READ = 256
OWNER_WRITE = 128
OWNER_EXEC = 64
GROUP_READ = 32
...
OTHERS_EXEC = 1

mode = 1005
if mode  DIRECTORY:
# It's a directory!
if mode  OTHERS_READ:
# You're allowed to read (eg 'ls')
if mode  GROUP_EXEC:
# You get the idea.

With multi-bit flags you might have to do a bitwise AND followed by an
equality check:

NOT_STICKY = 0
STICKY_PARTIAL = 16
STICKY_MOSTLY = 32
STICKY_ENTIRELY = 48
STICKY_BITS = 48

if style  STICKY_BITS == STICKY_MOSTLY:
# I've no idea what this means, actually

At no time can you do identity checks. It might happen to work with
the lower bit values and CPython, but when you check the 2048 bit, you
don't get that. Value is all that matters.

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Michael Torrie
On 03/02/2014 02:03 PM, Marko Rauhamaa wrote:
 Michael Torrie torr...@gmail.com:
 
 I don't see why == wouldn't continue to work if os.POSIX_FADV_RANDOM
 became an object of a different type.
 
 It probably would.
 
 If one were begging for trouble, one *could* define:
 
class ABC:
A = 1
B = 1.0
C = 1+0j

And one could also set A=1 and B=1 if he was trying to be stupid.  That
would fail the equality test and the identity test (in CPython).  Seems
like this argument is getting a bit on the absurd side.  The normal
idiom is to use equality checks to test state variables' *values*.  I
don't know of any developer that would purposely try to break that when
defining a new module or class.

If Mark H wants to use an idiom that isn't conventional, or isn't widely
used, he is free to do so; I can't see much harm in it.  But certainly
it's not the normal way that it's done in Python from what I can see.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-02 Thread Marko Rauhamaa
Michael Torrie torr...@gmail.com:

 And one could also set A=1 and B=1 if he was trying to be stupid.
 [...]
 If Mark H wants to use an idiom that isn't conventional, or isn't
 widely used, he is free to do so; I can't see much harm in it. But
 certainly it's not the normal way that it's done in Python from what
 I can see.

You might be referring to what I have proposed.

Note that the idiom is in use in some standard python modules
(socket.py, ftplib.py, argparse.py, optparse.py). It is used extensively
in sre_compile.py/sre_constants.py:

   ANY = any
   [...]
   AT = at
   [...]
   CALL = call
   [...]
   IN = in

   elif op is IN:
   [...]
   elif op is ANY:
   [...]
   elif op is CALL:
   [...]
   elif op is AT:


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


Re: [OT] Can global variable be passed into Python function?

2014-03-02 Thread Dave Angel
 Chris Angelico ros...@gmail.com Wrote in message:

 }
 
 so in that case, the array size is inside the malloc'd block, but it's
 still invisible to the calling function. 
 

Please quit using negative language when you're so vehemently
 agreeing with me. 

The data is sometimes not at the beginning of the malloc'ed block.

-- 
DaveA

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


Re: Can global variable be passed into Python function?

2014-03-02 Thread Steven D'Aprano
On Sun, 02 Mar 2014 13:33:11 +0200, Marko Rauhamaa wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:
 
 On Sun, 02 Mar 2014 11:35:43 +0200, Marko Rauhamaa wrote:
 Now, what kinds of object are those constants? We are not supposed to
 know or care.

 Incorrect. We are supposed to know and care.
 
 Then, the documentation is seriously flawed. It gives no hint whatsoever
 on the nature of those objects.

Seriously flawed? I doubt it. It's a trivial, pedantic point, and I 
expect that most practising Python programmers will consider it too 
obvious to bother documenting the fact that flags meant for compatibility 
with POSIX operating systems are ints.

On the other hand, perhaps I am wrong and it is a documentation bug. Feel 
free to suggest a documentation patch on the bug tracker.


 os.posix is exactly the sort of library I mentioned earlier when I said
 sometimes you're constrained by compatibility with some other system.
 In this case, the os module is explicitly designed to be compatible
 with the POSIX interface, which is defined to use certain integer
 values as flags. This is not an implementation choice which
 implementers can change at will, it is part of the interface.
 
 The values of those Python constants don't need to have any relationship
 with those of the underlying operating system.

In theory, they could be different. In practice, no they won't. You 
should be able to pass the Python constants directly to some C library 
which expects to see ints. It's a thin wrapper, not a bridge.


 Python does not guarantee that there is only a single 1 instance.
 
 Nobody has ever argued such a thing. I certainly haven't.

You may not have intended to, but by championing the use of is, that is 
precisely what you have done. Using is tests for *identity*, not value. 
To get the behaviour you want, it requires those objects to be singletons.


 However, nothing in the API spec gives you the right to call the
 function with an integer.

But you do call the function with an integer. And if you don't, you get a 
type error that explicitly tells you that an integer is needed:

py os.posix_fadvise(open(/tmp/spam).fileno(), 0, 100, None)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: an integer is required


 If you want to test whether a value is os.POSIX_FADV_RANDOM, the right
 way is to compare that value for equality with os.POSIX_FADV_RANDOM,
 not identity.
 
 That might well be true but is not explicitly or implicitly specified in
 the documentation. (The os.SEEK_* constants are explicitly defined.)

Not everything needs to be documented explicitly. Would you rather the 
Python developers spend their time fixing bugs and improving the 
language, or ensuring that every trivial and obvious point is explicitly 
documented?

If you feel this is not a trivial or obvious point, and that it needs 
documenting, then feel free to contribute a documentation patch.



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Ben Finney ben+pyt...@benfinney.id.au:

 Since you don't care about identity, only that the objects have
 different values, you should be comparing for equality with ‘==’.

Ok, one last attempt.

I need *identifiers*. I could simply define:

   class ABC:
   A = object()
   B = object()
   C = object()

The program would work perfectly.

Except, if it's got a bug. I know self.abc contains either A, B or C,
but which one? Printing out self.abc won't give me any help. I could
print out ABC.A, ABC.B and ABC.C and see which one matches, but that's
cumbersome.

The next variant is to use objects that have names:

   class Symbol:
   def __init__(self, name):
   self.name = name
   def __str__(self):
   return self.name

   class ABC:
   A = Symbol(A)
   B = Symbol(B)
   C = Symbol(C)


The same program still works (and still uses is for identity tests,
mind you).

The next realization is that the Symbol class is completely redundant as
any string object would fit the bill. Hence we can reduce the visual
clutter by simply defining:

   class ABC:
   A = A
   B = B
   C = C

The same program still works (and still uses is for identity tests,
mind you).


Marko


PS The only remaining redundancy is having to repeat the symbol name in
every assignment. If Python (like Lisp) had a builtin symbol datatype,
you wouldn't have to define anything at all but simply assign something
like this:

self.abc = $A

where $A would be a symbol.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 But I'm not sure that there is a good reason to put the class definitions 
 inside the __init__ method. That means every time you create a new 
 StateMachine instance, the classes have to be re-created.

 [...]

 It will be much more efficient if you pull all the Idle, etc. classes out 
 and make them top-level global classes.
 [...]
 But then the closure over sm won't work...

Precisely.

As for effiency, I don't know if it is more efficient to create ad hoc
classes or ad hoc instances; might be a tossup in CPython.

 Since in this example you've actually got significant behaviour in the
 states, they aren't just symbols, and some sort of solution along
 these lines (whether you use multiple inner classes or not) is
 appropriate.

That inner class solution is an alternative to the symbol approach. In
the absense of a switch statement, the inner class has lots going for
it.


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ben Finney
Marko Rauhamaa ma...@pacujo.net writes:

 Ben Finney ben+pyt...@benfinney.id.au:

  Since you don't care about identity, only that the objects have
  different values, you should be comparing for equality with ‘==’.

 Ok, one last attempt.

 I need *identifiers*.

And, as you've realised, without an Enum pattern you have the option of
using string *values* — because it's the values you want to see in error
message output.

The *identity* of the values doesn't matter. Any string of the given
value will work fine.

So don't fool the reader into thinking you actually care about object
identity; don't use ‘is’ for comparing these values. Use ‘==’, since
that's all that matters for getting a value that will work fine.

 The same program still works (and still uses is for identity tests,
 mind you).

You have provided no justification for using an identity test. It
confuses the matter by pretending you care about object identity, when
you *do not* as evidenced by all your arguments so far.

The equality operator ‘==’ is clearer for your purpose, and less
confusing.

-- 
 \  “[Entrenched media corporations will] maintain the status quo, |
  `\   or die trying. Either is better than actually WORKING for a |
_o__)  living.” —ringsnake.livejournal.com, 2007-11-12 |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Ben Finney ben+pyt...@benfinney.id.au:

 Use ‘==’, since that's all that matters for getting a value that will
 work fine.

You are telling me to use '==' if I choose string objects and 'is' if I
choose some other objects.

I prefer a solution that works regardless of what objects I choose for
identifiers.

There really is no taboo against string object identity if you know what
you are doing.


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sat, Mar 1, 2014 at 10:28 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Ben Finney ben+pyt...@benfinney.id.au:

 Use ‘==’, since that's all that matters for getting a value that will
 work fine.

 You are telling me to use '==' if I choose string objects and 'is' if I
 choose some other objects.

 I prefer a solution that works regardless of what objects I choose for
 identifiers.

 There really is no taboo against string object identity if you know what
 you are doing.

And, as proven here in this thread, you do not know what you are doing.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ben Finney
Marko Rauhamaa ma...@pacujo.net writes:

 Ben Finney ben+pyt...@benfinney.id.au:

  Use ‘==’, since that's all that matters for getting a value that will
  work fine.

 You are telling me to use '==' if I choose string objects and 'is' if I
 choose some other objects.

No. I'm telling you that ‘is’ is *wrong* for comparing strings, because
it is unreliable.

 I prefer a solution that works regardless of what objects I choose for
 identifiers.

Some languages have a “symbol” type, whose values can be directly
compared. Python doesn't have such a type. If you want to use strings as
a substitute, go ahead: they work fine.

But compare strings by *equality*, not identity, because it's their
*values* which will be the identifiers. Their object identity will not
be reliably comparable.

That's what everyone has been telling you all along, for reasons already
explained.

 There really is no taboo against string object identity if you know what
 you are doing.

You, as has been amply demonstrated, do not, despite your dogmatic
assertions.

-- 
 \ “Under democracy one party always devotes its chief energies to |
  `\   trying to prove that the other party is unfit to rule — and |
_o__) both commonly succeed, and are right.” —Henry L. Mencken |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark Lawrence

On 01/03/2014 11:59, Chris Angelico wrote:

On Sat, Mar 1, 2014 at 10:28 PM, Marko Rauhamaa ma...@pacujo.net wrote:


There really is no taboo against string object identity if you know what
you are doing.


And, as proven here in this thread, you do not know what you are doing.



Why do you think I admitted him onto my dream team some days ago? :)

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Michael Torrie
On 03/01/2014 04:28 AM, Marko Rauhamaa wrote:
 Ben Finney ben+pyt...@benfinney.id.au:
 
 Use ‘==’, since that's all that matters for getting a value that will
 work fine.
 
 You are telling me to use '==' if I choose string objects and 'is' if I
 choose some other objects.

No, '==' works fine no matter what objects you assign to your state
variables.

class Foo(object):
STATE1 = object()
STATE2 = testing
STATE3 = 2

def __init__(self):
self.state = Foo.STATE1

def bar(self):
if self.state == Foo.STATE1:
pass
elif self.state == Foo.STATE2:
pass
elif self.state == Foo.STATE3:
pass

 I prefer a solution that works regardless of what objects I choose for
 identifiers.

As shown, '==' does work for this too.  I don't know which is more
correct, but it does work.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Steven D'Aprano
On Sat, 01 Mar 2014 22:59:52 +1100, Chris Angelico wrote:

 On Sat, Mar 1, 2014 at 10:28 PM, Marko Rauhamaa ma...@pacujo.net
 wrote:
 Ben Finney ben+pyt...@benfinney.id.au:

 Use ‘==’, since that's all that matters for getting a value that will
 work fine.

 You are telling me to use '==' if I choose string objects and 'is' if I
 choose some other objects.

 I prefer a solution that works regardless of what objects I choose for
 identifiers.

 There really is no taboo against string object identity if you know
 what you are doing.
 
 And, as proven here in this thread, you do not know what you are doing.

Steady on, that's a bit harsh. In context, I think that Marko is assuming 
that the caller will only ever use the state values via their symbolic 
names, e.g. only refer to them as IDLE, CONNECTED etc. and never use 
their internal string values IDLE, CONNECTED.

I don't think that's a safe assumption, since it requires the caller to 
only ever do the right thing, but if it is true, then using is in the 
way he suggests cannot fail.

Still, I've repeatedly asked Marko to justify why we should care about 
the symbols being singletons, and unless I've missed something, he hasn't 
even attempted to justify that. It seems to me that he's just assuming 
that symbols ought to be singletons, hence his focus on identity rather 
than equality.




-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Steven D'Aprano
On Sat, 01 Mar 2014 12:31:39 +0200, Marko Rauhamaa wrote:

 I need *identifiers*. I could simply define:
 
class ABC:
A = object()
B = object()
C = object()
 
 The program would work perfectly.
 
 Except, if it's got a bug. I know self.abc contains either A, B or C,
 but which one? Printing out self.abc won't give me any help. I could
 print out ABC.A, ABC.B and ABC.C and see which one matches, but that's
 cumbersome.

All very good so far.

 
 The next variant is to use objects that have names:
 
class Symbol:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
 
class ABC:
A = Symbol(A)
B = Symbol(B)
C = Symbol(C)
 
 
 The same program still works (and still uses is for identity tests,
 mind you).

But why are you using identity tests? Equality will work perfectly well, 
and won't expose the implementation detail that these objects may be 
singletons. That's especially important at the next step, when you 
replace the Symbol class with regular strings. If the caller happens to 
use C rather than ABC.C, why is this a problem?



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Ben Finney ben+pyt...@benfinney.id.au:

 No. I'm telling you that ‘is’ is *wrong* for comparing strings,
 because it is unreliable.

No, it isn't as long as the string object references have a common
assignment pedigree. Assignment (including parameter passing) is
guaranteed to preserve identity of any object.


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 4:07 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Sat, 01 Mar 2014 22:59:52 +1100, Chris Angelico wrote:
 And, as proven here in this thread, you do not know what you are doing.

 Steady on, that's a bit harsh. In context, I think that Marko is assuming
 that the caller will only ever use the state values via their symbolic
 names, e.g. only refer to them as IDLE, CONNECTED etc. and never use
 their internal string values IDLE, CONNECTED.

A bit harsh, perhaps, but I stand by it: by repeatedly declaring that
something is safe when it has been proven not safe, he shows that he
does not know what he is doing - that he is not fully comprehending
the significance of object value vs identity as regards strings.

Incidentally, Python somewhat creates this issue, by sometimes
interning and sometimes not. (And the same with small integers,
although I've never heard the expression int interning.) If strings
were always interned, then it would be obvious that identity and value
were one and the same. On the flip side, if a string literal always
created a new string (that is, if it were more like a string
construction syntax like square brackets for lists), then it would be
obvious that each one is a separate object. I don't say either option
is worth doing (especially the latter, O!), but by sometimes merging
and sometimes not, Python does slightly blur the line between identity
and value. (Obviously if strings were mutable, they'd *have* to have
separate identities.)

 I don't think that's a safe assumption, since it requires the caller to
 only ever do the right thing, but if it is true, then using is in the
 way he suggests cannot fail.

If you're depending on the caller doing the right thing, it's still
safe to use == rather than is. The only reason to use 'is' is to
prevent the caller from stuffing in some other string that happens to
be correct - hence his point about being able to change the keywords.
If the caller stuffs in the string INIT instead of the object
Foo.INIT, then == will happen to work until such time as Foo.INIT
becomes INITIALIZING, at which point it breaks. Preventing that
means that unique object identity is crucial to the system working,
and that's pretty much impossible with strings. (I don't say it's
absolutely impossible; maybe if you intern some other string with the
same value, and then construct the string you want out of pieces, and
somehow prevent the compiler from figuring out what you're doing and
optimizing it all away, then maybe you could have something that
doesn't get reused anywhere else. But it's certainly not normal to be
able to be sure of that.)

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 4:23 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 Ben Finney ben+pyt...@benfinney.id.au:

 No. I'm telling you that ‘is’ is *wrong* for comparing strings,
 because it is unreliable.

 No, it isn't as long as the string object references have a common
 assignment pedigree. Assignment (including parameter passing) is
 guaranteed to preserve identity of any object.

Of course it is, but your identity tests also depend on there NOT
being a common object when there is NOT an assignment pedigree. The
positive is guaranteed; the negative is not. And if you don't care
about a false positive - that is, that some other string with the same
value matches - then what you actually want is equality, not identity,
comparison.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Michael Torrie torr...@gmail.com:

 No, '==' works fine no matter what objects you assign to your state
 variables.

Well, it doesn't since

a = float(nan)
a is a
   True
a == a
   False

More generally, it depends on how the __eq__ method has been implemented
for the class. You might even (foolishly) define a class such that:

a == b
   False
a != b
   False

The is operator is immune to such modality.


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 4:29 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 You might even (foolishly) define a class such that:

 a == b
False
 a != b
False

Not necessarily even foolish; the SQL NULL value [1] behaves like that.

ChrisA

[1] Which isn't a value, except when it is
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Michael Torrie
On 03/01/2014 10:29 AM, Marko Rauhamaa wrote:
 Michael Torrie torr...@gmail.com:
 
 No, '==' works fine no matter what objects you assign to your state
 variables.
 
 Well, it doesn't since
 
 a = float(nan)
 a is a
True
 a == a
False
 
 More generally, it depends on how the __eq__ method has been implemented
 for the class. You might even (foolishly) define a class such that:
 
 a == b
False
 a != b
False

Yes, good point.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Marko Rauhamaa
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

 It seems to me that he's just assuming that symbols ought to be
 singletons, hence his focus on identity rather than equality.

Yes.

A practical angle is this: if I used strings as symbols and compared
them with ==, logically I shouldn't define them as constants but
simply use strings everywhere:

   class Connection:
   def __init__(self):
   self.state = IDLE

   def connect(self, address):
   if self.state == IDLE:
   ...
   elif self.state == ...

The principal (practical) problem with that is that I might make a typo
and write:

   if self.state == IDLE :

which could result in some hard-to-find problems. That's why I want get
the help of the Python compiler and always refer to the states through
symbolic constants:

   if self.state == self.IDLE:


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


Re: [OT] Can global variable be passed into Python function?

2014-03-01 Thread Grant Edwards
On 2014-02-24, Michael Torrie torr...@gmail.com wrote:
 On 02/24/2014 11:05 AM, j.e.ha...@gmail.com wrote:
 typedef struct {
   int value;
 } Number;
 
   Number *o;
   o = malloc(sizeof(*o));
   o-value=3;
   printf(o%p, o-value%p\n, o, o-value);
 
 o0x9fe5008, o-value0x9fe5008
 
 Is the compiler borked?

 Why would you think that? The address of the start of your malloc'ed
 structure is the same as the address of the first element.  Surely
 this is logical?

Not only is it logical, the C standard explicitly requires it.  Here's
a second-hand citation since I don't happend to have an actual copy of
the standard on hand:

C1x §6.7.2.1.13:

   A pointer to a structure object, suitably converted, points to
   its initial member ... and vice versa. There may be unnamed
   padding within a structure object, but not at its beginning.

-- 
Grant Edwards   grant.b.edwardsYow! I'm gliding over a
  at   NUCLEAR WASTE DUMP near
  gmail.comATLANTA, Georgia!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Grant Edwards
On 2014-02-28, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:

 Can you elaborate on this nonliteral constants point? How is it a
 problem if DISCONNECTING isn't technically a constant? It follows the
 Python convention of being in all upper-case, so the programmer
 understands not to rebind it. Is the problem that someone might
 (naively or maliciously) change the value of DISCONNECTING, or is the
 problem that Python doesn't fundamentally know that it won't change?

 This last point. It would make it impossible for Python to treat the
 switch statement as anything but an alternate form of chained if-else.

There are a couple nice things about a switch () statement:

 1) It guarantees that 'expr' is evaluated exactly once.  If you want
that with a chained if/else you have to create a temporary variable.

 2) It guarantees that exactly one path is chosen (assuming we're not
going to duplicate C's fall through mistake).

The result is that it makes the author's intention instantly clear to
the reader: we're going to evaluate some expression _exactly_once_ and
then select _exactly_one_ of several paths based on that value.  Sure,
you can do the same thing with a chained if/elif/else, but it requires
some effort for the reader to figure that out.  Accidently type if
instead of elif two thirds of the way down, and you get something
that works right _most_ of the time, but not always.  [Not that _I've_
ever done that and then read through the whole thing six times over a
period of two days before noticing it.] :)

reductio ad absurdum
If the availability of an alternate but computationally equivalent
representation was a valid argument against a language feature, then
we ought to toss out Python entirely: It's always possible to write
the exact same algorithm, so why bother with Python?
/reductio ad absurdum

 A dict optimization wouldn't actually optimize anything because it
 would have to be constructed every time the statement is executed.

I don't think question should be how does this help the compiler?

The question should be how does this help the _user_ of the compiler?

The user of the compiler spends more time reading code than anything
else.  Something that makes code easier to read is therefore worth
considering. A switch statement is easier to read than a chained
if/else.  IMO, _that's_ the proper argument for a switch statement.

Trying to justify a switch statement as a way to help generate more
efficient code seems silly: This is not 1970 -- any decent compiler
should be able to generate the same code for a switch statement and
for an equivalent chained if/else.

-- 
Grant Edwards   grant.b.edwardsYow! I want to read my new
  at   poem about pork brains and
  gmail.comouter space ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Roy Smith
On Sat, Mar 1, 2014 at 10:06 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 A colleague of mine taught me decades back that the whole point of OO
 was the avoidance of if and switch statements. So if your code has an if
 or switch statement, chances are you are doing something wrong.

This sounds like a classic case of a useful observation being taken out 
of context.

On of the standard mantras about OOP is that you should not use code to 
find code.  By that, they mean, you should not do things like 
(pseudo-code):

if type(obj) == Foo:
frobnicate_with_foo(obj)
else if type(obj_ == Bar:
frobnicate_with_bar(obj)
else:
frobnicate_with_other(obj)

But rather, you should let the class dispatch machinery handle figuring 
out which version of frobnicate() to call.  That's a reasonable 
statement, but somehow that seems to have gotten twisted into, If 
you're doing OOP, you should never have any 'if' statements.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Roy Smith
In article 87d2i7wbxs@elektro.pacujo.net,
 Marko Rauhamaa ma...@pacujo.net wrote:

 Neil Cerutti ne...@norwich.edu:
 
  Check out Go's switch statement for an example of what it might
  look like in Python. Except you'd get it without labeled break or
  the fallthrough statement.

Python already has a switch statement.  It's just spelled funny...

class Switch(Exception): pass
class Case1(Switch): pass
class Case2(Switch): pass
class Case3(Switch): pass

try:
   raise value
except Case1:
   print did case 1
except (Case2, Case3):
   print did either case 2 or 3
else:
   print did default

No fall-through, however.  I'm sure with a little meta-class magic, you 
could write a Case() which eliminates the need for manually declaring 
the cases.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Grant Edwards
On 2014-02-28, Marko Rauhamaa ma...@pacujo.net wrote:

 Here's a use case for is with strings (or ints):

class Connection:
IDLE = IDLE
CONNECTING = CONNECTING
CONNECTED = CONNECTED
DISCONNECTING = DISCONNECTING
DISCONNECTED = DISCONNECTED

def __init__(self):
self.state = IDLE

def connect(self, address):
...
self.state = CONNECTING
...

def disconnect(self):
...
if self.state is CONNECTED:
...

I don't really see the point.  Why won't '==' work just as well?

Are you hoping that 'is' is faster at runtime than '=='?

-- 
Grant Edwards   grant.b.edwardsYow! Th' MIND is the Pizza
  at   Palace of th' SOUL
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Grant Edwards
On 2014-02-28, Mark Lawrence breamore...@yahoo.co.uk wrote:

 http://c2.com/cgi/wiki?SwitchStatementsSmell

So lack of a switch state is an attempt to force Python programmers to
write things in an object oriented way?

-- 
Grant Edwards   grant.b.edwardsYow! FUN is never having to
  at   say you're SUSHI!!
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Roy Smith
In article 0b414429-74ee-45dd-9465-c87e98c36...@googlegroups.com,
 Mark H. Harris harrismh...@gmail.com wrote:

 On Friday, February 28, 2014 3:03:25 PM UTC-6, Marko Rauhamaa wrote:
  
  Marko
 
...  and between me and you, here is a snip from dmath.py from the atan(x) 
function:
 
 if (n**2  D(1)):
 a = __atan__(n)
 elif (n == D(1)):
 a = gpi/4
 elif (n == D(-1)):
 a = -(gpi/4)
 elif (n  D(-1)):
 a = __atan__Lt_neg1__(n)
 else:
 a = __atan__Gt_1__(n)
 
This if--elif--else  is not only ugly, its just not readable either, and 
besides that, its not elegant, nor is it humanly helpful...   its does 
work though, and its absolutely necessary.   ugh.
 
First, its not immediately clear what it does. Well, there isn't just one 
atan(x) routine,  there are at least four of them, depending on whether 
you're a purist, and they must be selected.

This kind of stuff is pretty common in numerical code.  Depending on the 
sign/magnitude/quadrant/whatever of the argument, you'll want to use one 
of several algorithms to minimize roundoff error, etc.

But, how would this be any nicer with switch?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Roy Smith
In article mailman.7483.1393632181.18130.python-l...@python.org,
 Ben Finney ben+pyt...@benfinney.id.au wrote:

 Of course. That's the point of describing something as a “code smell”:
 it may have exceptions where the smell does not indicate an actual
 problem, but those are not the normal case where the smell is
 encountered. More often, it indicates a problem that should be fixed.

An apt analogy is refrigerator smell.  Sometimes it means the leftovers 
from 3 months ago have evolved into a sentient life form.  Sometimes it 
just means you've got a piece of Roquefort.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Roy Smith
In article 87mwh9969m@elektro.pacujo.net,
 Marko Rauhamaa ma...@pacujo.net wrote:

 Michael Torrie torr...@gmail.com:
 
  No, '==' works fine no matter what objects you assign to your state
  variables.
 
 Well, it doesn't since
 
 a = float(nan)
 a is a
True
 a == a
False
 
 More generally, it depends on how the __eq__ method has been implemented
 for the class. You might even (foolishly) define a class such that:
 
 a == b
False
 a != b
False

Well, there's always things like SQL's NULL, which is both not equal and 
not not equal to itself.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark H. Harris
On Saturday, March 1, 2014 12:24:15 AM UTC-6, Chris Angelico wrote:
 much code. If you want to change anything, you potentially have to
 
 edit three places: the list of constants at the top, the condition
 
 function, and the switch.
 
 
 
 This can't be your idea of readability. Show me where I'm wrong.
 
 
 
 ChrisA

hi Chris,  I don't think you're wrong.  There are two issues for me (and one of 
them is not how the switch is implemented).

1) Is it easier for average users of python as a language to read switch case 
default,  or if elif else ?

2) Would most average users concur that 'readable' means something like, 
readily understandable at quick glance, or rapid preview (or quiv).

I readily admit that 'subjective' is the operative work here. As Guido found at 
his 2007 keynote most experienced devs are not clamoring for a switch block. 
Just so. But I'm not thinking of experienced devs. I'm thinking of the average 
coder who is used to looking at switch blocks.  

I personally can see and understand a switch block 2x to 3x faster than looking 
at an elif chain. Because I am primarily a C programmer and I personally use 
and read switch blocks.

An experienced python dev can readily 'see' an elif chain, well, because that's 
all they have and that's all they look at day to day.  So, naturally a python 
dev is going to think an elif chain is readable. 

Thank you sir, you have good insights. A quote from the high seas is classy.

(another post with no elipses)

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark Lawrence

On 01/03/2014 21:40, Mark H. Harris wrote:

On Saturday, March 1, 2014 12:24:15 AM UTC-6, Chris Angelico wrote:

much code. If you want to change anything, you potentially have to

edit three places: the list of constants at the top, the condition

function, and the switch.



This can't be your idea of readability. Show me where I'm wrong.



ChrisA


hi Chris,  I don't think you're wrong.  There are two issues for me (and one of 
them is not how the switch is implemented).

1) Is it easier for average users of python as a language to read switch case 
default,  or if elif else ?

2) Would most average users concur that 'readable' means something like, readily 
understandable at quick glance, or rapid preview (or quiv).

I readily admit that 'subjective' is the operative work here. As Guido found at 
his 2007 keynote most experienced devs are not clamoring for a switch block. 
Just so. But I'm not thinking of experienced devs. I'm thinking of the average 
coder who is used to looking at switch blocks.

I personally can see and understand a switch block 2x to 3x faster than looking 
at an elif chain. Because I am primarily a C programmer and I personally use 
and read switch blocks.

An experienced python dev can readily 'see' an elif chain, well, because that's 
all they have and that's all they look at day to day.  So, naturally a python 
dev is going to think an elif chain is readable.

Thank you sir, you have good insights. A quote from the high seas is classy.

(another post with no elipses)

Cheers



No elipses, just the paragraphs not wrapped and the double line spacing. 
 Good old gg, I just love it.


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark H. Harris
On Saturday, March 1, 2014 4:01:12 PM UTC-6, Mark Lawrence wrote:

 
 No elipses, just the paragraphs not wrapped and the double line spacing. 
 
   Good old gg, I just love it.

How do I fix it?   Is there a setting someplace?  I tried pulling up the page 
you linked, but blank.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 8:40 AM, Mark H. Harris harrismh...@gmail.com wrote:
 hi Chris,  I don't think you're wrong.  There are two issues for me (and one 
 of them is not how the switch is implemented).

 1) Is it easier for average users of python as a language to read switch case 
 default,  or if elif else ?

 I personally can see and understand a switch block 2x to 3x faster than 
 looking at an elif chain. Because I am primarily a C programmer and I 
 personally use and read switch blocks.

Sure. But before you can ask us to consider how readable it is, we
need to have comparisons. Mock up a switch statement equivalent and
show us how it'd be better. I just looked at your version, and
couldn't see any way that it would be an improvement, because it
required that there be the exact same if/elif chain to figure out what
to switch on. So give us your readable version, in an exact
reimplementation of the if/elif chain, so we can see exactly how it
would go.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ben Finney
Marko Rauhamaa ma...@pacujo.net writes:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:

  It seems to me that he's just assuming that symbols ought to be
  singletons, hence his focus on identity rather than equality.

 Yes.

Give that up, then. Your assumption is false in Python, and is not
needed to get the behaviour you say you need.

 A practical angle is this: if I used strings as symbols and compared
 them with ==, logically I shouldn't define them as constants but
 simply use strings everywhere

Yes, that works fine. It's also quite understandable for the reader.

 The principal (practical) problem with that is that I might make a
 typo and write:

if self.state == IDLE :

 which could result in some hard-to-find problems.

That's just one of a huge variety of problems. Write a comprehensive
unit test suite to catch this and a great many other errors.

 That's why I want get the help of the Python compiler and always refer
 to the states through symbolic constants

Python doesn't let you compare symbols, only values. Work within its
constraints.

-- 
 \ “I cannot conceive that anybody will require multiplications at |
  `\   the rate of 40,000 or even 4,000 per hour …” —F. H. Wales, 1936 |
_o__)  |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ben Finney
Marko Rauhamaa ma...@pacujo.net writes:

 Ben Finney ben+pyt...@benfinney.id.au:

  No. I'm telling you that ‘is’ is *wrong* for comparing strings,
  because it is unreliable.

 No, it isn't as long as the string object references have a common
 assignment pedigree. Assignment (including parameter passing) is
 guaranteed to preserve identity of any object.

The unreliability isn't “will the same object have the same identity?”.
The unreliability is “will objects defined elsewhere have a different
identity?” In the case of Python strings, the latter question is not
reliably answerable from the programmer's perspective.

You are obstinately ignoring the point that the identity of a string is
*not* guaranteed to be different from a string with the same value.

Since you're persistently misconstruing what is being said to you, I'm
not going to run through it all again.

-- 
 \ “[W]e are still the first generation of users, and for all that |
  `\  we may have invented the net, we still don't really get it.” |
_o__)   —Douglas Adams |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ben Finney
Grant Edwards invalid@invalid.invalid writes:

 On 2014-02-28, Mark Lawrence breamore...@yahoo.co.uk wrote:

  http://c2.com/cgi/wiki?SwitchStatementsSmell

 So lack of a switch state is an attempt […]

Since when is the absence of action an “attempt” to do anything?

You're assuming the not-doing of something must have a purpose. That
assumption doesn't seem justified.

-- 
 \ “You are welcome to visit the cemetery where famous Russian and |
  `\Soviet composers, artists, and writers are buried daily except |
_o__)   Thursday.” —Russian orthodox monastery, Moscow |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark H. Harris
On Saturday, March 1, 2014 4:36:07 PM UTC-6, Ben Finney wrote:
 Since when is the absence of action an attempt to do anything?
 
 You're assuming the not-doing of something must have a purpose. That
 assumption doesn't seem justified.

Correct.  Argument from silence is logical fallacy;  lack of motion is not the 
doing of being motionless.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Steven D'Aprano
On Sat, 01 Mar 2014 20:25:51 +0200, Marko Rauhamaa wrote:

 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info:
 
 It seems to me that he's just assuming that symbols ought to be
 singletons, hence his focus on identity rather than equality.
 
 Yes.
 
 A practical angle is this: if I used strings as symbols and compared
 them with ==, logically I shouldn't define them as constants 

That doesn't follow. There is no logical connection between using named 
constants (well, pseudo-constants, constants by convention only) and ==. 
You can do both, or neither, or either one, whichever suits you.

You might as well say that when you have float constants:

TAU = 6.283185307179586

that logically implies that you are prohibited in asking whether 
another float is less than or greater than TAU.

[...]
 The principal (practical) problem with that is that I might make a typo
 and write:
 
if self.state == IDLE :

Then used named constants. 

if self.state == IDLE:


See how easy it is? Just replace is with == unless you have a good 
reason for caring about identity instead of equality.




-- 
Steven D'Aprano
http://import-that.dreamwidth.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark Lawrence

On 01/03/2014 22:07, Mark H. Harris wrote:

On Saturday, March 1, 2014 4:01:12 PM UTC-6, Mark Lawrence wrote:



No elipses, just the paragraphs not wrapped and the double line spacing.

   Good old gg, I just love it.


How do I fix it?   Is there a setting someplace?  I tried pulling up the page 
you linked, but blank.

Thanks in advance.



https://wiki.python.org/moin/GoogleGroupsPython

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark H. Harris
On Saturday, March 1, 2014 5:21:57 PM UTC-6, Mark Lawrence wrote:

 https://wiki.python.org/moin/GoogleGroupsPython

Thanks, Mark.  Whoohoo! Looks like gg has some work to do. rats(). Ok, so I'm 
typing away here and when
I get to the boarder I should press the enter key so that the text is forced to 
wrap to the next line so that
you don't see the text as a run-off the page nuisance and complete annoyance 
leading to homicidal rage
and/or other illicit behaviors like nail-biting. 
How does this look on your news client. I just need to setup an nntp server and 
use a real client.

Thanks for your input Mark. 

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 11:23 AM, Mark H. Harris harrismh...@gmail.com wrote:
 On Saturday, March 1, 2014 5:21:57 PM UTC-6, Mark Lawrence wrote:

 https://wiki.python.org/moin/GoogleGroupsPython

 Thanks, Mark.  Whoohoo! Looks like gg has some work to do. rats(). Ok, so I'm 
 typing away here and when
 I get to the boarder I should press the enter key so that the text is forced 
 to wrap to the next line so that
 you don't see the text as a run-off the page nuisance and complete annoyance 
 leading to homicidal rage
 and/or other illicit behaviors like nail-biting.
 How does this look on your news client. I just need to setup an nntp server 
 and use a real client.

The usual recommendation is to wrap to 70-80 characters. Most likely
you're seeing a proportionally-spaced font, so going for the border of
the display is going to be inherently sloppy.

What I would recommend, if you don't feel like setting up NNTP, is to
subscribe to the mailing list:

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

All the same content, but via email instead. Take your pick between
that and a newsreader - whichever's easier to get to work.

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark Lawrence

On 02/03/2014 00:23, Mark H. Harris wrote:

On Saturday, March 1, 2014 5:21:57 PM UTC-6, Mark Lawrence wrote:


https://wiki.python.org/moin/GoogleGroupsPython


Thanks, Mark.  Whoohoo! Looks like gg has some work to do. rats(). Ok, so I'm 
typing away here and when
I get to the boarder I should press the enter key so that the text is forced to 
wrap to the next line so that
you don't see the text as a run-off the page nuisance and complete annoyance 
leading to homicidal rage
and/or other illicit behaviors like nail-biting.
How does this look on your news client. I just need to setup an nntp server and 
use a real client.

Thanks for your input Mark.

Peace.   marcus



I love it when a plan comes together :)

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Ned Deily
In article 
captjjmqgh5-n8fgki+vmd8grzcw5np64kinka9_b6ewf8gv...@mail.gmail.com,
 Chris Angelico ros...@gmail.com wrote:
 What I would recommend, if you don't feel like setting up NNTP, is to
 subscribe to the mailing list:
 
 https://mail.python.org/mailman/listinfo/python-list
 
 All the same content, but via email instead. Take your pick between
 that and a newsreader - whichever's easier to get to work.

Or use one of the multiple interfaces to the group/list provided by 
gmane.org: nntp, web, or (read-only) rss.

http://dir.gmane.org/gmane.comp.python.general

-- 
 Ned Deily,
 n...@acm.org

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


Re: Can global variable be passed into Python function?

2014-03-01 Thread Mark Lawrence

On 02/03/2014 00:55, Ned Deily wrote:

In article
captjjmqgh5-n8fgki+vmd8grzcw5np64kinka9_b6ewf8gv...@mail.gmail.com,
  Chris Angelico ros...@gmail.com wrote:

What I would recommend, if you don't feel like setting up NNTP, is to
subscribe to the mailing list:

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

All the same content, but via email instead. Take your pick between
that and a newsreader - whichever's easier to get to work.


Or use one of the multiple interfaces to the group/list provided by
gmane.org: nntp, web, or (read-only) rss.

http://dir.gmane.org/gmane.comp.python.general



This mechanism has the added advantage of being a one stop shop.  Not 
only can you subscribe to hundreds of Python lists there is also a setup 
that lets you take feeds from numerous Python blogs.


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [OT] Can global variable be passed into Python function?

2014-03-01 Thread Dave Angel
 Grant Edwards invalid@invalid.invalid Wrote in message:
 On 2014-02-24, Michael Torrie torr...@gmail.com wrote:


 Why would you think that? The address of the start of your malloc'ed
 structure is the same as the address of the first element.  Surely
 this is logical?
 
 Not only is it logical, the C standard explicitly requires it.  Here's
 a second-hand citation since I don't happend to have an actual copy of
 the standard on hand:
 
 C1x �6.7.2.1.13:
 
A pointer to a structure object, suitably converted, points to
its initial member ... and vice versa. There may be unnamed
padding within a structure object, but not at its beginning.

The quote you make from the C standard doesn't mention malloc,  so
 you're arguing different things. It's not the compiler that casts
 the malloc return value to the struct type.

C++ does implicitly convert the result,  and the return value of
 new already has the struct type. But the runtime stores at least
 two kinds of overhead on occasion,  the array size, and the
 vtable. So the malloc address can not be assumed to match the
 struct beginning.  (Not even considering that one can override
 operator new at two levels)

Glad python doesn't have any of this mess.


-- 
DaveA

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


Re: [OT] Can global variable be passed into Python function?

2014-03-01 Thread Chris Angelico
On Sun, Mar 2, 2014 at 3:02 PM, Dave Angel da...@davea.name wrote:
 The quote you make from the C standard doesn't mention malloc,  so
  you're arguing different things. It's not the compiler that casts
  the malloc return value to the struct type.

 C++ does implicitly convert the result,  and the return value of
  new already has the struct type. But the runtime stores at least
  two kinds of overhead on occasion,  the array size, and the
  vtable. So the malloc address can not be assumed to match the
  struct beginning.  (Not even considering that one can override

Whatever pointer malloc returns is the beginning of the *usable*
space. Any overhead for array size etc has to be before that; a
virtual function table pointer would be inside that space, but that's
very much compiler-dependent.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Steven D'Aprano
On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote:

 Chris Angelico ros...@gmail.com:
 
 Simple rule of thumb: Never use 'is' with strings or ints. They're
 immutable, their identities should be their values. Playing with 'is'
 will only confuse you, unless you're specifically going for
 introspection and such.
 
 Here's a use case for is with strings (or ints):

I don't think this is a use-case for is. See below.

class Connection:
IDLE = IDLE
[...]
CONNECTED = CONNECTED
[...]
def disconnect(self):
...
if self.state is CONNECTED:
...

Why do you care that the state is *that specific* string, rather than any 
old string with the value CONNECTED?

Unless you can explain a good reason why, say, *this* instance 
CONNECTED should fail the test, while *that* instance with the same 
value passes, it's not a good use-case for is.


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Ben Finney
Steven D'Aprano st...@pearwood.info writes:

 On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote:
 class Connection:
 IDLE = IDLE
 [...]
 CONNECTED = CONNECTED
 [...]
 def disconnect(self):
 ...
 if self.state is CONNECTED:
 ...

 Why do you care that the state is *that specific* string, rather than
 any old string with the value CONNECTED?

I can think of a reason:

* When you publish the API for the ‘Connection’ class,

* and another party writes code that sets ‘state’ to a string with the
  value ‘CONNECTED’,

* and you implemented the check as ‘self.state == CONNECTED’,

* and their code works with your class and it goes into production,

* you're then not able to change the expected value without breaking
  that party's code.

On the other hand, if the only value which will work is the one which
the caller gets via ‘Connection.CONNECTED’, then you can change the
implementation later without breaking existing code.


There are two reasons why I think this is *still* not a justification
for using ‘is’ with string values:

First reason: This is better done by making it clear the value is an
arbitrary object that won't be compared for equality. Just use
‘object()’ to creeate each value and be done with it. That's a hack, but
it's better than pretending you'll use the string as a string of text
and then breaking that expectation.

Second reason: This use case is a primary motivation for the Enum
pattern. The Enum pattern is implemented in the standard-library ‘enum’
module, now in Python 3.4 URL:http://python.org/dev/peps/pep-0435/.

So, I think Marko's use case is not a justification for comparing string
values with ‘is’.

-- 
 \“Pinky, are you pondering what I'm pondering?” “Wuh, I think |
  `\   so, Brain, but if we didn't have ears, we'd look like weasels.” |
_o__)   —_Pinky and The Brain_ |
Ben Finney

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Fri, Feb 28, 2014 at 6:43 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Here's a use case for is with strings (or ints):

class Connection:
IDLE = IDLE
CONNECTING = CONNECTING
CONNECTED = CONNECTED
DISCONNECTING = DISCONNECTING
DISCONNECTED = DISCONNECTED

 The state objects could have been defined like this:

IDLE = object()
CONNECTING = object()
CONNECTED = object()
DISCONNECTING = object()
DISCONNECTED = object()

 However, strings have the advantage in troubleshooting:

sys.stderr.write(state = {}\n.format(self.state))

As Ben said, strong use-case for enums (either migrate to 3.4, or
check PyPI). But here's an alternative that uses object identity
safely. (Remember, all it takes is a bit of string interning and two
equal strings could become identical.)

class enum:
def __init__(self, desc):
self.desc = desc
def __repr__(self):
return self.desc

   IDLE = enum(IDLE)
   CONNECTING = enum(CONNECTING)
   CONNECTED = enum(CONNECTED)
   DISCONNECTING = enum(DISCONNECTING)
   DISCONNECTED = enum(DISCONNECTED)

Now object identity is the right way to do things, and you can still
do the formatting just like you say; plus there's no way to
accidentally get something that seems to work.

Of course, the real enum type is far more sophisticated than that, but
the concept is the same. It's an object.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Ben Finney ben+pyt...@benfinney.id.au:

 There are two reasons why I think this is *still* not a justification
 for using ‘is’ with string values:

 First reason: This is better done by making it clear the value is an
 arbitrary object that won't be compared for equality. Just use
 ‘object()’ to creeate each value and be done with it. That's a hack,
 but it's better than pretending you'll use the string as a string of
 text and then breaking that expectation.

 Second reason: This use case is a primary motivation for the Enum
 pattern. The Enum pattern is implemented in the standard-library
 ‘enum’ module, now in Python 3.4
 URL:http://python.org/dev/peps/pep-0435/.

 So, I think Marko's use case is not a justification for comparing
 string values with ‘is’.

Yes, enums are long overdue. However, since any distinct objects will
do, there is nothing preventing you from using string objects.


Marko

PS On the topic of enums, when are we getting support for a switch
statement?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Fri, Feb 28, 2014 at 9:02 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Yes, enums are long overdue. However, since any distinct objects will
 do, there is nothing preventing you from using string objects.


String literals will often be interned if they look like (especially,
if they *are*) identifiers, so if you want to prevent other strings
from happening to match, you can't trust 'is'.

 class Foo:
INIT = INIT
def __init__(self):
self.state = self.INIT
def initializing(self):
return self.state is self.INIT
 a=Foo()
 a.initializing()
True
 a.state=INIT
 a.initializing()
True


So you should use some string value that doesn't look like an identifier:

 class Foo:
INIT = INIT
def __init__(self):
self.state = self.INIT
def initializing(self):
return self.state is self.INIT
 a=Foo()
 a.initializing()
True
 a.state=INIT
 a.initializing()
False

But even then, chances are you can force the matter by interning explicitly.

 class Foo:
INIT = INIT
def __init__(self):
self.state = self.INIT
def initializing(self):
return self.state is self.INIT
 a=Foo()
 a.initializing()
True
 sys.intern(a.state)
'INIT'
 a.state=sys.intern(INIT)
 a.initializing()
True

Note that in no case did I at all tamper with the class definition,
either to change its idea of the INIT string or to fetch that
particular object. Two equal strings, in Python, might and might not
be identical, and you simply cannot rely on interning either way.

The third example, incidentally, depends on sys.intern reusing a.state
as the one interned string. This will normally be what happens if
it's the first string of that value to be used. So you might be able
to first force the strings to be in the interning table, and then
force your sentinels to be different objects. But at that point, you
really should be using object(), or a proper enum module.

If you're using strings as state values, you should be using == to
compare them. Nothing else is safe.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Fri, Feb 28, 2014 at 9:02 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 PS On the topic of enums, when are we getting support for a switch
 statement?

I don't see that they're particularly connected. In my C code, I've
used enums frequently as quick constants, often never switching on
them. Conversely, I often use switch in C code with either integer or
character constants. (ASCII character, of course, as that's all you
get.) Take this, for example, from my C++ MUD client:

enum 
{IS=0x00,ECHO=0x01,SEND=0x01,SUPPRESSGA=0x03,TERMTYPE=0x18,NAWS=0x1F,SE=0xF0,GA=0xF9,SB,WILL,WONT,DO=0xFD,DONT,IAC=0xFF};

That one happens to be used in a switch at one point, but it's also
used in other ways, like this:

static char naws[]={IAC,SB,NAWS,0,0,0,0,IAC,SE};

(The actual window size gets patched in separately, in case you're
curious... but I suspect most people here won't be aware that IAC SB
NAWS means Interpret-As-Command, Subnegotiation Begin, Negotiate About
Window Size, and that this is a TELNET command sequence.)

With bit flags, they'll never be used in switch:

enum //Bitflags in hackity
{
HACK_ATAT=1, //Perform @@ - fill-in translation
HACK_AUTOEDIT=2, //Respond to the autoedit markers [now active by default]
};

...

if (hackityHACK_ATAT) ...

Sometimes, they're just states, and they're assigned and/or compared
for equality:

enum {ic, court, citizen, trivia, sports, chancount} lastlinetype;

Some things check if (lastlinetype == ic), but nothing ever switches on it.

Meanwhile, here's a switch block from Gypsum that will never use enumerations:

switch (max(delay,base))
{
case 0..59: ... handling for 1 minute ...
case 60..3599: ... handling for 1 hour ...
default: ... handling for = 1 hour ...
}

No, the features are quite independent. Python currently has dispatch
tables and if/elif chains, and a strong cultural aversion to switch.
You could change that by coming up with some *really* awesome
proposal, but you'll be fighting against the tide a bit.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 String literals will often be interned if they look like (especially,
 if they *are*) identifiers, so if you want to prevent other strings
 from happening to match, you can't trust 'is'.

 [...]

 If you're using strings as state values, you should be using == to
 compare them. Nothing else is safe.

You didn't quite understand the use case. You would never ever do things
like:

  a.state=INIT

You'd only refer to the state names symbolically:

   a.state = a.INIT


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 Python currently has dispatch tables and if/elif chains, and a strong
 cultural aversion to switch. You could change that by coming up with
 some *really* awesome proposal, but you'll be fighting against the
 tide a bit.

It's easy have a cultural aversion when the language doesn't provide
the facility.

Switch statements provide for excellent readability in parsers and state
machines, for example. They also allow the Python compiler to optimize
the statement internally unlike long if-else chains.


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Fri, Feb 28, 2014 at 10:30 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:

 String literals will often be interned if they look like (especially,
 if they *are*) identifiers, so if you want to prevent other strings
 from happening to match, you can't trust 'is'.

 [...]

 If you're using strings as state values, you should be using == to
 compare them. Nothing else is safe.

 You didn't quite understand the use case. You would never ever do things
 like:

  a.state=INIT

 You'd only refer to the state names symbolically:

a.state = a.INIT

In theory, yes. If that's all people will ever do, then you can safely
use == to check. Why are you using is? To prevent the case where some
other random string will happen to compare equal. So I stuffed some
other random string in, and it was equal, and I proved that I could
make it identical as well.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Fri, Feb 28, 2014 at 10:38 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:

 Python currently has dispatch tables and if/elif chains, and a strong
 cultural aversion to switch. You could change that by coming up with
 some *really* awesome proposal, but you'll be fighting against the
 tide a bit.

 It's easy have a cultural aversion when the language doesn't provide
 the facility.

I'm talking about the strong resistance that gets put up any time the
suggestion comes up on python-ideas or somesuch. The core devs and
Guido especially are against the idea.

 Switch statements provide for excellent readability in parsers and state
 machines, for example. They also allow the Python compiler to optimize
 the statement internally unlike long if-else chains.

It's usually possible to turn any concrete example of a switch
statement into an equally-readable dispatch table. All you need is for
your search terms to be hashable (which is a much less stringent
requirement than is usually put on switch blocks, like must be
machine word signed integer), and you can do something like this:

compare_key = {
# Same target(s).
ast.Assign: lambda node: ' '.join(dump(t) for t in node.targets),
# Same target and same operator.
ast.AugAssign: lambda node: dump(node.target) + dump(node.op) + =,
# A return statement is always compatible with another.
ast.Return: lambda node: (easy),
# Calling these never compatible is wrong. Calling them
# always compatible will give lots of false positives.
ast.Expr: lambda node: (maybe),
# These ones are never compatible, so return some
# object that's never equal to anything.
ast.Import: lambda node: float(nan),
ast.ImportFrom: lambda node: float(nan),
ast.Pass: lambda node: float(nan),
ast.Raise: lambda node: float(nan),
ast.If: lambda node: float(nan),
}

I then effectively do a big switch block like this:

if try_type not in compare_key:
print(Unrecognized type,try_type.__name__,file=sys.stderr)
compare_key[try_type] = lambda node: float(nan)
func = compare_key[try_type]
try_node = func(node.body[0])
for handler in node.handlers:
if try_node != func(handler.body[0]): return

The first check (the not in bit) is kinda like a default clause, but
it makes the output only once for any given type. For a more 'true'
default clause, I could do this:

try:
func = compare_key[try_type]
except KeyError:
func = compare_key[default]

but I take advantage of the fact that the dispatch table is a dict and
mutate it. Also, if this were done in a switch block, there'd be some
redundancy. I call the same function on node.body[0] and on
handler.body[0] for each handler in handlers, so there's structure
that's common to all the branches there. I'm not sure how, with a
classic C-style switch block, I could implement that cleanly. Probably
I'd end up using function pointers and basically doing it exactly the
same way :)

The only major thing C's switch does that a dispatch table doesn't is
fall-through. And let's face it, if your big argument in favour of a
switch statement is I need fall-through, you're not just going to
have Python devs against you, you're also going to fight against the
roughly 50% of C programmers who detest that feature :)

(FWIW, I'm in the other 50%. I quite like fall-through, and there are
times when it's a very clean way to express something. But even those
cases can usually be expressed one way or another with only a little
more redundancy - for instance, have one case that sets the key to be
the next one, and then have stand-alone if blocks rather than if/elif.
Considering that that use of fall-through usually requires an
explanatory comment anyway, you're not really losing much.)

So, going back to your statement:

 Switch statements provide for excellent readability in parsers and state
 machines, for example.

The best way to start trying to build support for this would be to
mock up a syntax for a switch statement, and find a currently-existing
parser or state machine to translate. Show us the before and after
shots. That's what I'm currently doing to justify an exception
expression syntax - examples like this:

pwd = (os.getcwd() except OSError: None)

# Lib/tkinter/filedialog.py:210:
try:
pwd = os.getcwd()
except OSError:
pwd = None


g = (grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid)
u = (pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid)

# Lib/tarfile.py:2198:
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
u = tarinfo.uid


This is real Python code, straight out of the standard library. I
don't know if you could find many examples in the stdlib that beg for
a switch statement, but pick up some real-world code of your own, or
from some open source project, or 

Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 On Fri, Feb 28, 2014 at 10:30 PM, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:
a.state = a.INIT

 In theory, yes. If that's all people will ever do, then you can safely
 use == to check. Why are you using is?

The main reason to use is is to indicate that the object is a sentinel
object whose identity is what is meaningful, not the content. Using ==
would work but would give some poor soul the idea that the state
variable could hold any imaginable string.

The implementation should be able to change the state objects to any
(distinct) objects at all (say, the new enums, or ints, or some more
elaborate class instances) without any changes in the code.


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Neil Cerutti
On 2014-02-28, Marko Rauhamaa ma...@pacujo.net wrote:
 Chris Angelico ros...@gmail.com:
 Python currently has dispatch tables and if/elif chains, and a
 strong cultural aversion to switch. You could change that by
 coming up with some *really* awesome proposal, but you'll be
 fighting against the tide a bit.

 It's easy have a cultural aversion when the language doesn't
 provide the facility.

 Switch statements provide for excellent readability in parsers
 and state machines, for example. They also allow the Python
 compiler to optimize the statement internally unlike long
 if-else chains.

Once you remove all the features of switch that wouldn't fit in
Python, e.g.; fall-through, jumps, breaks; whats left provides
negligible benefit over if-elif-else or dict-dispatch.

A pythonic switch statement doesn't provide enough features to
bother with its implemention.

Check out Go's switch statement for an example of what it might
look like in Python. Except you'd get it without labeled break or
the fallthrough statement. Would you still want to use it?

-- 
Neil Cerutti

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Neil Cerutti ne...@norwich.edu:

 Check out Go's switch statement for an example of what it might
 look like in Python. Except you'd get it without labeled break or
 the fallthrough statement.

No need for the fallthrough (except that multiple cases should be
supported).

Labeled breaks wouldn't be needed because there are no fallthroughs.

 Would you still want to use it?

Probably.

Guile (scheme) has:

   (case (state self)
 ((CONNECTING CONNECTED)
  ...)
 ((DISCONNECTING)
  ...)
 (else
  ...))

Python isn't averse to the switch statement because it would be not
that useful. Rather, the problem is that Python doesn't have nonliteral
constants (scheme has builtin symbols). It is difficult to come up with
truly Pythonic syntax for the switch statement.

Something like

   switch self.state from Connection.State:
   case CONNECTING or CONNECTED:
   ...
   case DISONNECTING:
   ...
   else:
   ...

would be possible, but here, Connection.State is evaluated at compile
time. Don't know if there are any precedents to that kind of thing in
Python.


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


Re: References, and avoiding use of ???variable??? (was: Can global variable be passed into Python function?)

2014-02-28 Thread Neil Cerutti
On 2014-02-28, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Mark H. Harris harrismh...@gmail.com writes:
 So, yeah, thinking about variables is just not going away.

 Right. I would like, ideally, for the Python documentation to
 avoid mentioning that term entirely; and I would hope for that
 to promote a better understanding of Python's data model.

 The wider programming community, though, will no doubt continue
 to use that term to refer to various (incompatible) data
 models, and I certainly don't expect the Python community to
 pretend it doesn't exist.

I like the characteristic of Python that assignment and argument
passing work the same way. If only C were so simple!

The tutorial makes things sound more high-falutin' than that
[Tutorial 4.6 Defining Functions]:

  The actual parameters (arguments) to a function call are
  introduced in the local symbol table of the called function
  when it is called; thus, arguments are passed using call by
  value (where the value is always an object reference, not the
  value of the object). [...]

How about:

  The actual parameters (arguments) to a function call are passed
  via assignment to the variables in the local symbol table of
  the called function. 

Am I oversimplifying?

-- 
Neil Cerutti

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Sat, Mar 1, 2014 at 1:26 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 Python isn't averse to the switch statement because it would be not
 that useful. Rather, the problem is that Python doesn't have nonliteral
 constants (scheme has builtin symbols). It is difficult to come up with
 truly Pythonic syntax for the switch statement.

 Something like

switch self.state from Connection.State:
case CONNECTING or CONNECTED:
...
case DISONNECTING:
...
else:
...

 would be possible, but here, Connection.State is evaluated at compile
 time. Don't know if there are any precedents to that kind of thing in
 Python.

Can you elaborate on this nonliteral constants point? How is it a
problem if DISCONNECTING isn't technically a constant? It follows the
Python convention of being in all upper-case, so the programmer
understands not to rebind it. Is the problem that someone might
(naively or maliciously) change the value of DISCONNECTING, or is the
problem that Python doesn't fundamentally know that it won't change?

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Mark Lawrence

On 28/02/2014 11:38, Marko Rauhamaa wrote:

Switch statements provide for excellent readability in parsers and state
machines, for example. They also allow the Python compiler to optimize
the statement internally unlike long if-else chains.



There are umpteen recipes for switch statements so take your pick or if 
you don't like any of them write your own.  Much easier than beating 
your head against multiple brick walls, which is what raising this one 
on python-ideas is likely to be.  See 
http://legacy.python.org/dev/peps/pep-0275/ and 
http://legacy.python.org/dev/peps/pep-3103/


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Michael Torrie
On 02/28/2014 01:46 AM, Ben Finney wrote:
 Steven D'Aprano st...@pearwood.info writes:
 
 On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote:
class Connection:
IDLE = IDLE
 [...]
CONNECTED = CONNECTED
 [...]
def disconnect(self):
...
if self.state is CONNECTED:
...

 Why do you care that the state is *that specific* string, rather than
 any old string with the value CONNECTED?
 
 I can think of a reason:
 
 * When you publish the API for the ‘Connection’ class,
 
 * and another party writes code that sets ‘state’ to a string with the
   value ‘CONNECTED’,
 
 * and you implemented the check as ‘self.state == CONNECTED’,
 
 * and their code works with your class and it goes into production,
 
 * you're then not able to change the expected value without breaking
   that party's code.

Sure.  If he replaced the line if self.state is CONNECTED with if
self.state == self.CONNECTED then he is free to change CONNECTED at any
time.  So yes, is is not necessary here.  Equality checking works fine.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Marko Rauhamaa
Chris Angelico ros...@gmail.com:

 Can you elaborate on this nonliteral constants point? How is it a
 problem if DISCONNECTING isn't technically a constant? It follows the
 Python convention of being in all upper-case, so the programmer
 understands not to rebind it. Is the problem that someone might
 (naively or maliciously) change the value of DISCONNECTING, or is the
 problem that Python doesn't fundamentally know that it won't change?

This last point. It would make it impossible for Python to treat the
switch statement as anything but an alternate form of chained if-else.
A dict optimization wouldn't actually optimize anything because it would
have to be constructed every time the statement is executed.

   switch self.state from Connection.State:
   case CONNECTING or CONNECTED:
   ...
   case DISONNECTING:
   ...
   else:
   ...

would have to be transformed by Python into:

   _X1 = self.state
   _X2 = Connection.State
   if _X1 is _X2.CONNECTING or _X1 is _X2.CONNECTED:
   ...
   elif _X1 is _X2.DISCONNECTING:
   ...
   else:
   ...

So optimization is gone. Then we have the syntactic burden. Python
currently doesn't (seem to) have a syntactic precedent for such implicit
dot notation. (Note that even Java had to complicate its syntax
analogously with enums.) In CONNECTING or CONNECTED, or wouldn't be
an operator in an expression but a particle.

Another syntactic oddity is the two indentation levels.

BTW, here's a syntax that doesn't introduce any new keywords:

   with self.state from Connection.State:
   if CONNECTING or CONNECTED:
   ...
   elif DISONNECTING:
   ...
   else:
   ...


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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Chris Angelico
On Sat, Mar 1, 2014 at 2:29 AM, Marko Rauhamaa ma...@pacujo.net wrote:
 BTW, here's a syntax that doesn't introduce any new keywords:

with self.state from Connection.State:
if CONNECTING or CONNECTED:
...
elif DISONNECTING:
...
else:
...

Okay, I understand your 'from' now. What it really does is introduce a
new scope, a read-only one presumably (because you really do NOT want
the Pandora's Box that ECMAScript's 'with' is) from which unqualified
names will be looked up. I would say that that's a very reasonable
idea, quite separately from a switch statement. Suppose you had
something like this:

with scope(Connection.State):
if self.state == CONNECTING:
print(I am not,DISCONNECTING)

It'd require a change to the LOAD_GLOBAL opcode to have it look in
multiple scopes. If you want to change something, be explicit about
where the change goes, but for lookups, it would be possible to have
them go to multiple places. I suspect, though, that this wouldn't fly;
I already posited such a theory, and was told that CPython's internals
made it much more convenient to not introduce infinitely nesting
scopes - the two use-cases that I'd most look at are these:

# This executes as a function
doubled = [x*2 for x in lst]

# This implicitly unbinds e in a finally clause
try:
foo()
except Exception as e:
pass

Neither is quite perfect; the closure method is mostly clean, but has
some extremely esoteric edge cases, and the unbinding means that a
previous value for 'e' is lost. But both are kept rather than
introducing this concept of true subscoping, because CPython's
implementation makes the latter hard.

Predicating your entire proposal on something that has been avoided
twice and just recently turned down, though, is a good way to get the
whole proposal rejected.

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


Re: Can global variable be passed into Python function?

2014-02-28 Thread Steven D'Aprano
On Fri, 28 Feb 2014 12:02:03 +0200, Marko Rauhamaa wrote:

 PS On the topic of enums, when are we getting support for a switch
 statement?

http://legacy.python.org/dev/peps/pep-3103/

http://legacy.python.org/dev/peps/pep-0275/



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


  1   2   3   >