Re: What killed Smalltalk could kill Python

2015-01-24 Thread Bob Martin
in 734904 20150123 225104 Tim Daneliuk  wrote:
>On 01/21/2015 05:55 PM, Chris Angelico wrote:
>> On Thu, Jan 22, 2015 at 10:37 AM, Tim Daneliuk  wrote:
>>> I find these kinds of discussions sort of silly.  Once there is a critical
>>> mass of installed base, no language EVER dies.
>>
>> Not sure about that. Back in the 1990s, I wrote most of my code in
>> REXX, either command-line or using a GUI toolkit like VX-REXX. Where's
>> REXX today? Well, let's see. It's still the native-ish language of
>> OS/2. Where's OS/2 today? Left behind. REXX has no Unicode support (it
>> does, however, support DBCS - useful, no?), no inbuilt networking
>> support (there are third-party TCP/IP socket libraries for OS/2 REXX,
>> but I don't know that other REXX implementations have socket services;
>> and that's just basic BSD sockets, no higher-level protocol handling
>> at all), etc, etc. Sure, it's not technically dead... but is anyone
>> developing the language further? I don't think so. Is new REXX code
>> being written? Not a lot. Yet when OS/2 was more popular, REXX
>> definitely had its installed base. It was the one obvious scripting
>> language for any OS/2 program. Languages can definitely die, or at
>> least be so left behind that they may as well be dead.
>>
>> ChrisA
>>
>
>Rexx is still well used on mainframes.

http://www.oorexx.org/

I use ooRexx every day, on Linux mostly, but also available on Windows.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What killed Smalltalk could kill Python

2015-01-24 Thread Chris Angelico
On Sat, Jan 24, 2015 at 7:09 PM, Bob Martin  wrote:
> http://www.oorexx.org/
>
> I use ooRexx every day, on Linux mostly, but also available on Windows.

So the question really is: Why that, as opposed to some other
language? Can you say, in one sentence, what ooRexx has that other
languages don't have?

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


Re: Comparisons and sorting of a numeric class....

2015-01-24 Thread Steven D'Aprano
Andrew Robinson wrote:

> But let me explain a bit more why I'm picking on Python:  For even if we
> set the electronic engineering concerns aside that I've raised (and they
> are valid, as OOP is supposed to model reality, not reality be bent to
> match OOP) -- People's facile explanations about why Python's version of
> bool is the way it is -- still bothers me here in the python mail list
> -- because people seem to have a very wrong idea about bool's nature as
> a dualton being somehow justified solely by the fact that there are only
> two values in Boolean logic; 

Nobody has suggested that except you. Earlier I even stated that I didn't
know GvR's motivation in making True and False singletons, but suggested
that it might have been a matter of efficiency.

Right here, right now, the reason doesn't matter. It doesn't matter if some
other language chooses differently, or that Python might have been designed
differently. What matters is:

(1) Python is the way it is, not the way it might have been had it been
designed differently;
(2) it isn't going to change; and
(3) it doesn't matter for what you are trying to do.

You have invented an imaginary problem then spent your time complaining that
Python doesn't allow you to solve this non-existent problem in a specific
way.


[...]
> -- And I know 
> Charles bool didn't use singletons in his algebra,  -- just read his
> work and you'll see he never mentions them or describes them, but he
> does actually use dozens of instances of the True and False objects he
> was talking about -- for the obvious reason that he would have needed
> special mirrors, dichroic or partially silvered, to be even able to
> attempt to make one instance of True written on paper show up in
> multiple places; And that's silly to do when there's no compelling
> reason to do it.

In the words of physicist Wolfgang Pauli, that is not even wrong.

http://en.wikipedia.org/wiki/Not_even_wrong

I'm actually gobsmacked that you could seriously argue that because Boole
wrote down true and false (using whatever notation he choose) more than
once, that proves that they aren't singletons. That's as sensible as
claiming that if I write your name down twice, you must be two people.


> Yet -- people here seem to want to insist that the bool type with only
> two instances is some kind of pure re-creation of what Charles Bool
> did -- when clearly it isn't.

Nobody has argued that Boole (note the spelling of his name) considered True
and False to be singletons. Being a mathematician, he probably considered
that there is a single unique True value and a single unique False value,
in the same way that there is a single unique value pi (3.1415...) and a
single unique value 0.

But "the number of instances" and "singleton" are concepts from object
oriented programming, which didn't exist when Boole was alive. It is not
even wrong to ask the question whether Boole thought of true and false to
be singleton objects. He no more had an opinion on that than Julius Caesar
had an opinion on whether the Falkland Islands belong to the UK or
Argentina.


> It's a amalgamation of enhancements such 
> as binary words instead of just True/False and many other things
> (operators that work on words rather than single bits.).  So -- I don't
> see that Python's implementation of Bool is justified by either a purist
> appeal to Charles bool, or by ignoring pragmatic concerns that have been
> attached to Bool's work for years by Electrical Engineers in order to
> make it more useful for practical computer problems.  Yet these two
> things are what this python list has sort of harped on.

Python's bools are objects, and they represent Boolean values, not strings,
not lists, not floats, and not three-value or four-value logic values. They
are designed for Boolean two-valued logic, like the bulk of programming
languages, not for simulating hardware. You might as well be complaining
that Python's bools are no use for doing vector arithmetic. Correct. That's
not what they're designed for. If you want vectors, don't use a bool, write
a vector class.

Three- or four-value logic is of great use to the hardware engineer making
electrical circuits, we get that, thank you. But they are of little use in
solving most programming problems, which is why no general purpose
programming language I am aware of supports non-Boolean logic in the
language itself.

Simulating physical hardware is a niche. I am impressed by your anecdote of
running Python on an operating system running on a simulated computer,
that's very impressive, but it is still a niche requirement.


[...]
> Where python is different from other languages regarding bool -- and
> deserves a little extra picking on, is that Guido has imposed four
> constraints simultaneously to bool which together cause a conflict
> that I don't think (offhand) I've ever encountered in another language;
> Definitely not in C/C++!
> 
> The four things are: 1 -- he cut off subtyping and created 

Re: Python is DOOMED! Again!

2015-01-24 Thread Nicholas Cole
On Sat, Jan 24, 2015 at 5:51 AM, Steven D'Aprano
 wrote:


> and Ruby has an experimental one:
>
> http://blog.codeclimate.com/blog/2014/05/06/gradual-type-checking-for-ruby/

Interesting.  Ruby has avoided the magic comment, and the typing is
done in annotations rather than in the function signatures.  It's
interesting to see them go a different way so that we can compare the
two approaches.

I rather like it.  It's a shame that the rest of Ruby's syntax is
inferior to python's. ;-)

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Marko Rauhamaa
Steven D'Aprano :

> Marko Rauhamaa wrote:
>
>>def weekday(day):
>>assert isinstance(day, int) and 0 <= day <= 6
>>...
>
> [...]
>
> Requiring the type-checker to parse and understand arbitrarily complex
> assertions would require the type-checker to be as complex as Python
> itself:

The static type checker / optimizer would of course be limited to a set
of known fixed expression patterns. More complex expressions would
simply be ignored by it.

Moreover, the type checker would probably operate in a compile-time
environment where you assume "isinstance" and "int" retain their usual
meanings. 

Scheme already employs somewhat analogous dirty tricks like that in its
macro preprocessing.

> Assertions also have the problem that they execute arbitrarily complex
> code at runtime.

Assertions don't *have* to execute anything, anywhere, any time. The
static analysis can decide when executing assertions is worth the
trouble. All of the above can also be done JIT.

> Lastly, this use of assertions clashes with "best practice" for
> assertions. Since assertions may be disabled, you should not use them
> for testing user-supplied arguments. So that means you have to write:
>
> def func(arg):
> assert isinstance(arg, int)  # satisfy the type checker
> if isinstance(arg, int):  # support times when assert is disabled
> ...

I think that's a silly argument. You never second-guess assertions.

> This doesn't apply to annotations:
>
> def func(arg:int):
> # since this is a public function, not private, we cannot assume the
> # caller will run the type-checker
> if isinstance(arg, int):
> ...

I think that usage is plainly bad style as well. Reminds me of the old
adage:

   Dad is always right, and even when he isn't, he's never wrong.


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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mario Figueiredo

Steven D'Aprano,


Rick, you seem to be under the misapprehension that a reductio ad
absurdum argument is a fallacy. It is not. From Webster's dictionary:

Indirect demonstration, or Negative demonstration (called
also reductio ad absurdum), in which the correct
conclusion is an inference from the demonstration that any
other hypothesis must be incorrect.
And from Wordnet:

reductio ad absurdum
n 1: (reduction to the absurd) a disproof by showing that the
consequences of the proposition are absurd; or a proof of a
proposition by showing that its negation leads to a
contradiction [syn: reductio ad absurdum, reductio]
Example:

Argument:

Human population growth can continue forever, without any limits
at all. There shall never come a time where lack of resources
will constrain growth.
Refutation by reductio ad absurdum:

If human population doubles every fifty years, in 718 years every
square metre of the world's land surface will have a person in it.
In 840 years we will be jammed shoulder-to-shoulder. In 2335 years
there will be a million people per square inch of the planet's
surface (including oceans). Before that, after just 2155 years,
the
entire mass of the planet will be converted to human flesh. In
6760
years, the entire solar system will be a solid sphere of humans,
expanding outward at 15840400 km per hour.
Since this is clearly absurd, something (war, famine, disease,
reduced fertility) must reduce or halt population growth.
(Aside: those numbers are more or less correct, as best as I can
calculate them.)

Reductio arguments can, of course, be fallacious. "The world cannot be
a sphere. If the world was a sphere, people on the bottom would fall
off!" This argument is fallacious because it fails to understand that
gravity acts towards the centre of the Earth, not "down" relative to
outer space.


And that's cherry picking. Another fallacy. That is, presenting only results 
that support your argument.


When Reductio ad absurdum fails to respect the principle of non-contradition 
it is no longer a proof by contradiction devise, but  a proper fallacy. Reductio 
ad absurdum becomes then one of the well know forms of straw man argument.


Your argument that the 70s things were bad and Rick wanted to go back to 
those times is both debatable (the 70s brought much of what we use today 
as gospel, like design patterns, for instance). You also try to reduce rick 
argument to the absurd by insinuating he is trying to support the idea that 
we should declare function names in one file, function parameters in another 
file and the function body in another file. That's a proper reductio ad absurdum 
straw man argument if I ever saw one.



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


Re: kivy secret of mana game

2015-01-24 Thread Larry Martell
On Fri, Jan 23, 2015 at 3:44 PM,   wrote:
> On Friday, January 23, 2015 at 10:10:08 AM UTC-8, Tony the Tiger wrote:
>> On Thu, 22 Jan 2015 17:13:12 +, Automn wrote:
>>
>> > game
>>
>> No interest, at all, nada, zilch. zero, nothing.
>>
>>  /Grrr
>
> Why don't you like fun?

I spend 10-12 hours a day on the computer - writing code for a living,
paying bills, banking, running my business, shopping, communicating
with family, researching real estate, etc. - the last thing I want to
do is spend more time on it playing a game. There's a lot of fun to be
had without a computer - try it, you may like it.
-- 
https://mail.python.org/mailman/listinfo/python-list


__bases__ misleading error message

2015-01-24 Thread Mario Figueiredo


Consider the following code at your REPL of choice

   class Super:
   pass

   class Sub:
   pass

   foo = Sub()

   Sub.__bases__
   foo.__bases__

The last statement originates the following error:

   AttributeError: 'Sub' object has no attribute '__bases__'

Naturally the 'Sub' object has an attribute __bases__. It's the instance 
that has not. So shouldn't the error read like:


   AttributeError: 'Sub' instance has no attribute '__bases__', or
   AttributeError: 'foo' object has no attribute '__bases__'


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


Re: Random ALL CAPS posts on this group

2015-01-24 Thread alister
On Fri, 23 Jan 2015 14:40:15 -0800, sohcahtoa82 wrote:

> On Monday, January 19, 2015 at 4:16:13 PM UTC-8, Luke Tomaneng wrote:
>> Has anyone noticed these? There have been about three of them recently
>> and they don't seem to have anything to do with Python at all. Does
>> anyone know if there is a good reason they are here?
> 
> My question is, does anyone know what the hell they're ranting about?

Does anyone care?
i just kill file the author (i could instigate the other suggestions made 
here but i like to make my on decisions rather than fully automating) 



-- 
Death comes on every passing breeze,
He lurks in every flower;
Each season has its own disease,
Its peril -- every hour.
--Reginald Heber
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Check for running DHCP daemon?

2015-01-24 Thread Michael Ströder
Chris Angelico wrote:
> On Sat, Jan 24, 2015 at 9:38 AM,   wrote:
>> Secondly, even if you find a module, keep in mind that the module probably 
>> won't stay in Python land.  It will probably call an external utility itself.
>>
>> If you REALLY wanted to check it without calling an external utility, you 
>> could connect to port 67 and see what happens, but that could cause problems.
> 
> We're talking UDP here, so there's no "connect to" concept. You have
> to send a packet and listen for a reply,

If I'd want to implement a serious DHCP monitoring I'd use a DHCP module and
try to renew a certain monitoring lease. With that approach you'd also see
whether the DHCP server does something meaningful.

Ciao, Michael.

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


OpenCv: different behavior of cv2.imread and cv2.imdecode

2015-01-24 Thread maurog
The starting point is an invalid jpg file, grabbed from a site showing 
pictures from a webcam while the site is updating the picture itself. So 
the upper part of the picture is ok, the lower part no.

If I execute this code
flags = cv2.CV_LOAD_IMAGE_COLOR
img = cv2.imread('bad.jpg', flags)

this message is printed on stderr

"Premature end of JPEG file"

and in the part of img np array related to the lower part of the picture 
all the values are 128 for all the RGB layers, that is black pixels.

If I execute this code, as suggested here 

https://stackoverflow.com/questions/13329445/how-to-read-image-from-in-
memory-buffer-stringio-or-from-url-with-opencv-pytho

r = open('bad.jpg','rb').read()
img_array = np.asarray(bytearray(r), dtype=np.uint8)
flags = cv2.CV_LOAD_IMAGE_COLOR
img = cv2.imdecode(img_array, flags)

no error message is shown and in the img np array there are mixed values 
in the part related to the lower part of the picture

So it looks to me that cv2.imread and cv2.imdecode handle in a different 
way the loading of a jpg image. Is it like that or am I missing something?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What killed Smalltalk could kill Python

2015-01-24 Thread Gene Heskett
On Saturday 24 January 2015 03:09:51 Bob Martin did opine
And Gene did reply:
> in 734904 20150123 225104 Tim Daneliuk  wrote:
> >On 01/21/2015 05:55 PM, Chris Angelico wrote:
> >> On Thu, Jan 22, 2015 at 10:37 AM, Tim Daneliuk 
 wrote:
> >>> I find these kinds of discussions sort of silly.  Once there is a
> >>> critical mass of installed base, no language EVER dies.
> >> 
> >> Not sure about that. Back in the 1990s, I wrote most of my code in
> >> REXX, either command-line or using a GUI toolkit like VX-REXX.
> >> Where's REXX today? Well, let's see. It's still the native-ish
> >> language of OS/2. Where's OS/2 today? Left behind. REXX has no
> >> Unicode support (it does, however, support DBCS - useful, no?), no
> >> inbuilt networking support (there are third-party TCP/IP socket
> >> libraries for OS/2 REXX, but I don't know that other REXX
> >> implementations have socket services; and that's just basic BSD
> >> sockets, no higher-level protocol handling at all), etc, etc. Sure,
> >> it's not technically dead... but is anyone developing the language
> >> further? I don't think so. Is new REXX code being written? Not a
> >> lot. Yet when OS/2 was more popular, REXX definitely had its
> >> installed base. It was the one obvious scripting language for any
> >> OS/2 program. Languages can definitely die, or at least be so left
> >> behind that they may as well be dead.
> >> 
> >> ChrisA
> >
> >Rexx is still well used on mainframes.
> 
> http://www.oorexx.org/
> 
> I use ooRexx every day, on Linux mostly, but also available on Windows.

Can it run typical AREXX source?  I don't see a single syllable on that 
now 5 year old site indicating any such capability.

Example: Something needs to be synchronized to occur in the first tick of 
the next minute, and has nothing to do until then, so it queries the 
system for the number of ticks remaining in this minute, then puts itself 
to sleep for that long.

Is this possible in ooRexx?

Cheers, Gene Heskett
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page 
US V Castleman, SCOTUS, Mar 2014 is grounds for Impeaching SCOTUS
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Tim Chase
On 2015-01-24 17:28, Chris Angelico wrote:
> but this is hardly generic. There's no convenient way to give an
> argument to a decorator that says "please assign this here", short
> of using some stupid eval hack... is there?
> 
> (Incidentally, for a non-generic dispatch table, a callable dict
> subclass could be pretty clean:
> 
> class DispatchTable(dict):
> """Self-populating dictionary - use this as a function decorator
> to stuff functions into it."""
> def __call__(self, func):
> self[func.__name__] = func
> return func
> 
> cmd = DispatchTable()
> 
> @cmd
> def foo(*args):
> print("You asked to foo.")

As best I can tell, your question is "is there a better way to do
dispatch tables without duplicating the storage location while
remaining sufficiently generic?"

The closest I've seen is something like cmd.Cmd does where you have a
class and dispatch methods on it with a certain naming convention
(this prevents odd access to dunder methods).  Akin to your first
example [reordered from your original post]

> cmd = {} # Command dispatch table
> 
> def cmd["foo"](*args):
> print("You asked to foo.")
> 
> def cmd["bar"](*args):
> print("There's no wine in the bar.")
> 
> def cmd["asdf"](*args):
> print("Asdf! Asdf!")

It usually looks something like

  class Dispatcher(object):
def __getitem__(self, name):
  return getattr(self, "do_" + name)

  class MyExample(Dispatcher):
def do_hello(self, who):
  print("Hello, %s" % who)
def do_goodbye(self, who, feeling):
  print("Goodbye, %s. I'm %s to see you go" % (
who, feeling))

  mydispatch = MyExample()
  mydispatch["hello"]("world")
  mydispatch["goodbye"]("cruel world", "sorry")
  mydispatch["does not exist"]("give me an AttributeError")

The root Dispatcher object can grow helpful methods like

  class Dispatcher(object):
# ...
def get_help(self, name):
  return getattr(self, name, "No help for %r" % name)
def __iter__(self):
  for name in dir(self):
if name.startswith("do_") and callable(getattr(self, "do_" + name)):
  yield name
  # ...
def do_hello(self, who):
  "Say hello to a person"
  # ...

  # print out all known methods and their help
  for method in mydispatch:
print("%s: %s" % (method, mydispatch.get_help(method_name)))

-tkc





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


Re: __bases__ misleading error message

2015-01-24 Thread Steven D'Aprano
Mario Figueiredo wrote:

> 
> Consider the following code at your REPL of choice
> 
> class Super:
> pass

Super is irrelevant here, since it isn't used.

> class Sub:
> pass
> 
> foo = Sub()
> 
> Sub.__bases__
> foo.__bases__
> 
> The last statement originates the following error:
> 
> AttributeError: 'Sub' object has no attribute '__bases__'

It's a bit ambiguous, but the way to read it is to think of object as a
synonym for instance. This is, in my opinion, a Java-ism which is
inappropriate for Python where classes are objects too, but we seem to be
stuck with it.

So we have a Sub instance (object) which has no attribute '__bases__'. This
is no different from:

py> (23).spam
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute 'spam'



> Naturally the 'Sub' object has an attribute __bases__. 

Correct, in the sense that classes are objects too. But in the sense of
object=instance, no. Isn't ambiguous terminology wonderful?


> It's the instance 
> that has not. So shouldn't the error read like:
> 
> AttributeError: 'Sub' instance has no attribute '__bases__', or
> AttributeError: 'foo' object has no attribute '__bases__'

The first would be nice. The second is impossible: objects may have no name,
one name, or many names, and they do not know what names they are bound to.
So the Sub instance bound to the name 'foo' doesn't know that its name
is 'foo', so it cannot display it in the error message.



-- 
Steven

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Tim Chase
On 2015-01-24 17:21, Steven D'Aprano wrote:
> # Cobra
> def sqroot(i as int) as float
> 
> # Python
> def sqroot(i:int)->float:
> 
> 
> Cobra's use of "as" clashes with Python. In Python, "as" is used for
> name-binding:
> 
> import module as name
> with open('file') as f
> except Exception as e
> 
> but apart from that minor difference, they're virtually identical.

Though given that

 def sqrt(i as int) as float:

is invalid Python syntax (both in the parameter list and as the
return value of the function), the meaning of "as" could be overloaded
in both senses to allow for the Cobra-like syntax.

-tkc


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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Steven D'Aprano
Mario Figueiredo wrote:

> In article <[email protected]>,
> [email protected] says...
>> 
>> (Example modified for PEP8 compliance ;-)
>> 
>> @typehint(arg1:str, arg2:int, returns:bool)
>> def myfunction(arg1, arg2):
>> return True
>> 
>> Of course "@typehint" could be an extension of the decorator
>> syntax, a keyword, a build-in function or whatever, i don't
>> care.
> 
> I'd rather it'd be a docstring parameter.
> 
> - Decorators are transformation tools. Which type hints are not.

But they can be. Python annotations are available at runtime, they are not
mere declarations for the compiler like in Pascal or C:

py> def spam(x:int, y:float)->float:
... return x+y
...
py> spam.__annotations__
{'x': , 'y': , 'return': }


They're writable too:

py> def eggs(x, y):
... return x + y
...
py> eggs.__annotations__ = spam.__annotations__
py> eggs.__annotations__['x']



So we can write a transformation tool which adds, modifies or deletes
annotations:

@annotate(x=int, y=float)  # return is a little tricky...
def eggs(x, y):
return x+y

eggs.__annotations__['x']
# returns int


Except we don't need such a tool. Python 3 already has syntax for it, and it
supports annotating the return result too. Annotation syntax is just
syntactic sugar for a transformation.


> - keywords should be few and used only for language features. Static
> analysis isn't and should never be a language feature. It's an
> extension, perhaps.

I'm not sure if you're making a general observation or one which is specific
to Python. Plenty of languages have static analysis as a language feature.
Are you arguing they are wrong to do so?

In the case of Python, there are no plans for CPython to include static
analysis, or for it to be general language feature. Other implementations,
such as MyPy, and other tools, are intended to perform the analysis, not
the CPython reference implementation.


> - Same with built-in functions... although a case could be made for a
> static analysis package, hmmm.

I'm not sure what you mean here.



> So I'd rather see:
> 
>  def myfunction(arg1, arg2):
>  """
>  Normal docstring.
>  """
>  "@typehint: (str, int) -> bool"
>  return True

By the rules of implicit (compile-time) concatenation of string literals,
that is equivalent to:

def myfunction(arg1, arg2):
"""
Normal docstring.
@typehint: (str, int) -> bool"""
return True

One of the problems with this is that it put the information about
parameters far away from the parameter list itself. Most docstrings are
considerable more than a single line:

py> from random import sample
py> len(sample.__doc__.split('\n'))
16


I consider 16 lines a short docstring! I've written docstrings which are 40
or 50 lines long, so potentially the annotations are almost a full page
away from the function signature.

The usual convention among document generator tools is that parameter
metadata is at the start of the docstring, not the end:

def myfunction(arg1, arg2):
"""
One line summary.

@param arg1: str
@param arg2: int
@returns bool

Longer discussion of the function.
"""
return True

I'm not keen on that, but at least it puts the types close to the function
signature, and it's a defacto standard.


> I removed the arguments names on purpose. They are only necessary on the
> PEP because type hinting is a part of the function header there.
> However, when using a documentation like pattern as above (or as in your
> own example), they can be safely removed, with the added benefit of
> making the syntax simpler.

Only at the cost of making it hard to read. I go to look up a function which
I am unfamiliar with, and find the function signature:

def open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None):
"""Open a file.

blah blah blah blah...
thirty lines of documentation...


My documentation view shows only the first thirty lines, so I hit the Page
Down key and see:

blah blah blah blah...
thirty lines of documentation...

I page down again:

blah blah blah...
@typehint: (str, str, int, Optional[str], Optional[str], 
Optional[str], bool, Callable)


Well that's rather less than useful. Which argument is newline again? Number
3 or 4 or 5?

Syntax which appears reasonable with toy examples (one-line docstring, two
arguments) is less reasonable with real-world cases (docstrings can be a
page or more in length, there may be five or a dozen arguments to a
function).


> Alternatively, because dangling strings are always considered
> documentation and completely ignored by the interpreter (PEP 258), one
> could also do:
> 
>  "@typehint: (str, int) -> bool"
>  def myfunction(arg1, arg2):

That's somewhat better, in that at least the hint is close to the function
signature. But it has a lot of disadvantages:

Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Steven D'Aprano
Tim Chase wrote:

> On 2015-01-24 17:21, Steven D'Aprano wrote:
>> # Cobra
>> def sqroot(i as int) as float
>> 
>> # Python
>> def sqroot(i:int)->float:
>> 
>> 
>> Cobra's use of "as" clashes with Python. In Python, "as" is used for
>> name-binding:
>> 
>> import module as name
>> with open('file') as f
>> except Exception as e
>> 
>> but apart from that minor difference, they're virtually identical.
> 
> Though given that
> 
>  def sqrt(i as int) as float:
> 
> is invalid Python syntax (both in the parameter list and as the
> return value of the function), the meaning of "as" could be overloaded
> in both senses to allow for the Cobra-like syntax.

OF course it could. But it shouldn't, because "as" already has an
established and consistent meaning: it is used for name binding.

Things which look similar should be similar. "i as int" and "module as name"
look similar, but they are the same syntax for different concepts. "foo as
bar" will sometimes mean that bar is the name bound to foo, and sometimes
it will mean that foo is declared to be type bar. That's messy and
inconsistent and best avoided.



-- 
Steven

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


Re: What killed Smalltalk could kill Python

2015-01-24 Thread Bob Martin
in 734937 20150124 081658 Chris Angelico  wrote:
>On Sat, Jan 24, 2015 at 7:09 PM, Bob Martin  wrote:
>> http://www.oorexx.org/
>>
>> I use ooRexx every day, on Linux mostly, but also available on Windows.
>
>So the question really is: Why that, as opposed to some other
>language? Can you say, in one sentence, what ooRexx has that other
>languages don't have?

I was a mainframe programmer from 1963 to 2003 and used Rexx from its 
beginnings in 1981; also on OS/2 and Linux. 
I've never found anything to replace it, and it's the most readable language.
 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Roy Smith
In article <[email protected]>,
 Steven D'Aprano  wrote:

> Tim Chase wrote:
> 
> > On 2015-01-24 17:21, Steven D'Aprano wrote:
> >> # Cobra
> >> def sqroot(i as int) as float
> >> 
> >> # Python
> >> def sqroot(i:int)->float:
> >> 
> >> 
> >> Cobra's use of "as" clashes with Python. In Python, "as" is used for
> >> name-binding:
> >> 
> >> import module as name
> >> with open('file') as f
> >> except Exception as e
> >> 
> >> but apart from that minor difference, they're virtually identical.
> > 
> > Though given that
> > 
> >  def sqrt(i as int) as float:
> > 
> > is invalid Python syntax (both in the parameter list and as the
> > return value of the function), the meaning of "as" could be overloaded
> > in both senses to allow for the Cobra-like syntax.
> 
> OF course it could. But it shouldn't, because "as" already has an
> established and consistent meaning: it is used for name binding.
> 
> Things which look similar should be similar. "i as int" and "module as name"
> look similar, but they are the same syntax for different concepts. "foo as
> bar" will sometimes mean that bar is the name bound to foo, and sometimes
> it will mean that foo is declared to be type bar. That's messy and
> inconsistent and best avoided.

On the other hand, flip it around and say:

def sqrt(int as i):

and now the name-binding semantics works.  "The first argument is an 
int, which is bound to the name i".  Not sure how you would apply that 
to the return type, though.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Mario Figueiredo
In article <[email protected]>, 
[email protected] says...
> 
> I'm not sure if you're making a general observation or one which is
> specific
> to Python. Plenty of languages have static analysis as a language feature.
> Are you arguing they are wrong to do so?
> 

No. I'm arguing static analysis should not consume a programming 
language keyword space. Static analysis is just a development tool.

> 
> def myfunction(arg1, arg2):
> """
> Normal docstring.
> @typehint: (str, int) -> bool"""
> return True
> 
> One of the problems with this is that it put the information about
> parameters far away from the parameter list itself.

Then move it to the first line of the docstring...


> > I removed the arguments names on purpose. They are only necessary on 
> > the
> > PEP because type hinting is a part of the function header there.
> > However, when using a documentation like pattern as above (or as in your
> > own example), they can be safely removed, with the added benefit of
> > making the syntax simpler.
> 
> Only at the cost of making it hard to read.

If you want the redundancy and a potential source of new bugs by having 
a type hint in a docstring include argument names... You see, there's 
always a downside to everything.

Meanwhile, object names have nothing to do with type analsys, which 
makes arguments names rather irrelevant in the context of static 
analysis. I'd rather promote types than names. Remove names and you 
will.

> > 
> >  "@typehint: (str, int) -> bool"
> >  def myfunction(arg1, arg2):
> 
> That's somewhat better, in that at least the hint is close to the function
> signature. But it has a lot of disadvantages: it is compile-time only, the
> type hints aren't available at runtime.

It's static analysis. You don't need runtime execution.

> It requires extra complexity to the
> parser, so that decorators may be separated from the function by a hint:
> 
> @decorate
> "@typehint: (str, int) -> bool"
> def myfunction(arg1, arg2):
> 
> No doubt some people will get them the wrong way around, and the type
> checker may silently ignore their hints:
> 
> "@typehint: (str, int) -> bool"
> @decorate
> def myfunction(arg1, arg2):
> 
> And others will write:
> 
> @decorate
> @typehint(str, int) -> bool
> def myfunction(arg1, arg2):
> 

That seems like you are fishing. What is exactly your point? That people 
will not be able to understand the rules of type hinting? And that 
somehow is going to be an universal problem?

> Some syntax will be a bug magnet. This is one.

You think?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What killed Smalltalk could kill Python

2015-01-24 Thread Bob Martin
in 734949 20150124 113420 Gene Heskett  wrote:
>On Saturday 24 January 2015 03:09:51 Bob Martin did opine
>And Gene did reply:
>> in 734904 20150123 225104 Tim Daneliuk  wrote:
>> >On 01/21/2015 05:55 PM, Chris Angelico wrote:
>> >> On Thu, Jan 22, 2015 at 10:37 AM, Tim Daneliuk
> wrote:
>> >>> I find these kinds of discussions sort of silly.  Once there is a
>> >>> critical mass of installed base, no language EVER dies.
>> >>
>> >> Not sure about that. Back in the 1990s, I wrote most of my code in
>> >> REXX, either command-line or using a GUI toolkit like VX-REXX.
>> >> Where's REXX today? Well, let's see. It's still the native-ish
>> >> language of OS/2. Where's OS/2 today? Left behind. REXX has no
>> >> Unicode support (it does, however, support DBCS - useful, no?), no
>> >> inbuilt networking support (there are third-party TCP/IP socket
>> >> libraries for OS/2 REXX, but I don't know that other REXX
>> >> implementations have socket services; and that's just basic BSD
>> >> sockets, no higher-level protocol handling at all), etc, etc. Sure,
>> >> it's not technically dead... but is anyone developing the language
>> >> further? I don't think so. Is new REXX code being written? Not a
>> >> lot. Yet when OS/2 was more popular, REXX definitely had its
>> >> installed base. It was the one obvious scripting language for any
>> >> OS/2 program. Languages can definitely die, or at least be so left
>> >> behind that they may as well be dead.
>> >>
>> >> ChrisA
>> >
>> >Rexx is still well used on mainframes.
>>
>> http://www.oorexx.org/
>>
>> I use ooRexx every day, on Linux mostly, but also available on Windows.
>
>Can it run typical AREXX source?  I don't see a single syllable on that
>now 5 year old site indicating any such capability.

AREXX is based on Mike Cowlishaw's original mainframe Rexx so I doubt there
was much difference.
ooRexx is compatible with Rexx and is actively maintained by current & past 
IBMers.
A new version is coming soon.

>
>Example: Something needs to be synchronized to occur in the first tick of
>the next minute, and has nothing to do until then, so it queries the
>system for the number of ticks remaining in this minute, then puts itself
>to sleep for that long.
>
>Is this possible in ooRexx?

Yes, you'll find all you need in the utility classes at
http://www.oorexx.org/docs/rexxref/book1.htm

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Mario Figueiredo
In article , [email protected] 
says...
> 
> In article <[email protected]>, 
> [email protected] says...
> > 
> > def myfunction(arg1, arg2):
> > """
> > Normal docstring.
> > @typehint: (str, int) -> bool"""
> > return True
> > 
> > One of the problems with this is that it put the information about
> > parameters far away from the parameter list itself.
> 
> Then move it to the first line of the docstring...

Here's a more concrete example of what can be done in the docstring, 
taken from one of the examples in PEP 484. (Remember, we just moving the 
whole structure of type hinting to a new docstring parameter, instead of 
having it in the function header.

"PEP 484"
def handle_employees(e: Union[Employee, Sequence[Employee]]):
if isinstance(e, Employee):
e = [e]
...

"My proposal:"

def handle_employees(e):
"""
Handles an employee or list of employees by firing the whole
bunch of 'em lazy sods.

@hint: Union[Employee, Sequence[Employee]]
:param e: A single employee or a list of employees 
:return: None
"""
if isinstance(e, Employee):
e = [e]
...

If you find that hard to read or feel you still can't match type hints 
to their respective arguments in the function header... then, yeah, 
there's no convincing you.

My only pet peevee with this is that @int: becomes part of __doc__ and 
some pundits may argue against that inclusion. I don't have a real 
answer to that problem. I personally see that as a minor consequence, 
but can understand static analysis isn't really a part of a function 
documentation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python is DOOMED! Again!

2015-01-24 Thread Mark Lawrence

On 24/01/2015 01:15, Chris Angelico wrote:

On Sat, Jan 24, 2015 at 12:00 PM, Sturla Molden  wrote:

But without a thriving community, Python has no value to me.

If we add type hinting, then that community will go away, because other
languages are better options.

Who will win? Julia? Ruby? They are all waiting in line for Python to fail.
Then Python will be like Smalltalk.


The Python community that was already killed by Python 3.0? Funny, it
seems to be a bit more resilient than the naysayers would have us
believe.

ChrisA



That's unfair as there was a distinct fall back position, what with 
Python 2.8 and RickedPython(3).  Is anybody aware of just how far 
advanced these projects are?


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

Mark Lawrence

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mark Lawrence

On 24/01/2015 06:35, Steven D'Aprano wrote:

Obviously I'm not a fanatic. If I'm working out my share of a $37 meal split
three ways, I just do 37/3 the same as anyone else :-)



Always rounding down I take it? :)

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

Mark Lawrence

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


ANN: Version 0.1.4 of sarge (a subprocess wrapper library) has been released.

2015-01-24 Thread Vinay Sajip
Version 0.1.4 of Sarge, a cross-platform library which wraps the subprocess
module in the standard library, has been released.

What changed?
-

- Fixed issue #20: Now runs a pipeline in a separate thread if async.

- Fixed issue #21: The command line isn't parsed if shell=True is specified.

- Added Coveralls to Travis configuration.

- Tests added to cover added functionality and reported issues.

- Numerous documentation updates.

What does Sarge do?
---

Sarge tries to make interfacing with external programs from your
Python applications easier than just using subprocess alone.

Sarge offers the following features:

* A simple way to run command lines which allows a rich subset of Bash-
style shell command syntax, but parsed and run by sarge so that you
can run on Windows without cygwin (subject to having those commands
available):

>>> from sarge import capture_stdout
>>> p = capture_stdout('echo foo | cat; echo bar')
>>> for line in p.stdout: print(repr(line))
...
'foo\n'
'bar\n'

* The ability to format shell commands with placeholders, such that
variables are quoted to prevent shell injection attacks.

* The ability to capture output streams without requiring you to
program your own threads. You just use a Capture object and then you
can read from it as and when you want.

* The ability to look for patterns in captured output and to interact
accordingly with the child process.

Advantages over subprocess
---

Sarge offers the following benefits compared to using subprocess:

* The API is very simple.

* It's easier to use command pipelines - using subprocess out of the
box often leads to deadlocks because pipe buffers get filled up.

* It would be nice to use Bash-style pipe syntax on Windows, but
Windows shells don't support some of the syntax which is useful, like
&&, ||, |& and so on. Sarge gives you that functionality on Windows,
without cygwin.

* Sometimes, subprocess.Popen.communicate() is not flexible enough for
one's needs - for example, when one needs to process output a line at
a time without buffering the entire output in memory.

* It's desirable to avoid shell injection problems by having the
ability to quote command arguments safely.

* subprocess allows you to let stderr be the same as stdout, but not
the other way around - and sometimes, you need to do that.

Python version and platform compatibility
-

Sarge is intended to be used on any Python version >= 2.6 and is
tested on Python versions 2.6, 2.7, 3.1, 3.2, 3.3 and 3.4 on Linux,
Windows, and Mac OS X (not all versions are tested on all platforms,
but sarge is expected to work correctly on all these versions on all
these platforms).

Finding out more


You can read the documentation at

http://sarge.readthedocs.org/

There's a lot more information, with examples, than I can put into
this post.

You can install Sarge using "pip install sarge" to try it out. The
project is hosted on BitBucket at

https://bitbucket.org/vinay.sajip/sarge/

And you can leave feedback on the issue tracker there.

I hope you find Sarge useful!

Regards,

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Steven D'Aprano
Mark Lawrence wrote:

> On 24/01/2015 06:35, Steven D'Aprano wrote:
>> Obviously I'm not a fanatic. If I'm working out my share of a $37 meal
>> split three ways, I just do 37/3 the same as anyone else :-)
>>
> 
> Always rounding down I take it? :)

I'm hurt. I have a maths degree, I know how to do division:

  _
3| 37


3 goes into 3 once, and 3 goes into 7 twice with one remainder. So the
answer is 12 and 1/3.



-- 
Steven

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Steven D'Aprano
Mario Figueiredo wrote:

> In article <[email protected]>,
> [email protected] says...
>> 
>> I'm not sure if you're making a general observation or one which is
>> specific
>> to Python. Plenty of languages have static analysis as a language
>> feature. Are you arguing they are wrong to do so?
>> 
> 
> No. I'm arguing static analysis should not consume a programming
> language keyword space. Static analysis is just a development tool.

Hmmm. I don't see how that could possible work in practice. Let's take C
syntax for example:

int i;

declares i to be an int. How is this supposed to work without making int a
reserved word? Likewise for Pascal:

i: Integer;

In Python, built-in functions aren't reserved words, but we surely don't
expect a lexical type-checker to evaluate arbitrary code in order to check
whether int has been shadowed:

import random
if random.random() < 0.5:
int = str

def spam(n:int):
"""Or if you prefer docstrings:
@param n: int
"""

Even though int is not actually reserved, the type-checker is permitted to
behave as if it were, and it is difficult to see how it could possibly work
in practice if it did not behave that way.

At least it is difficult for me.


>> def myfunction(arg1, arg2):
>> """
>> Normal docstring.
>> @typehint: (str, int) -> bool"""
>> return True
>> 
>> One of the problems with this is that it put the information about
>> parameters far away from the parameter list itself.
> 
> Then move it to the first line of the docstring...

Which is close to the current convention used by document generators.


>> > I removed the arguments names on purpose. They are only necessary on
>> > the
>> > PEP because type hinting is a part of the function header there.
>> > However, when using a documentation like pattern as above (or as in
>> > your own example), they can be safely removed, with the added benefit
>> > of making the syntax simpler.
>> 
>> Only at the cost of making it hard to read.
> 
> If you want the redundancy and a potential source of new bugs by having
> a type hint in a docstring include argument names... You see, there's
> always a downside to everything.

True, true.

But you can't really avoid duplicating the name in the documentation, just
as you can't avoid duplicating the name in the body of the function. How
can you talk about the parameter if you don't refer to it by name? Such
unavoidable duplication of names is not what most people call "redundancy".


> Meanwhile, object names have nothing to do with type analsys, which
> makes arguments names rather irrelevant in the context of static
> analysis. I'd rather promote types than names. Remove names and you
> will.

How can type analyse avoid dealing with names?

def function(arg: int):
x = arg + 1
arg.append(None)


How does the type checker know that "x = arg + 1" is legal, but arg.append
is not? It has to know that since arg has not been rebinded yet, arg is an
int, not a list. It cannot do that unless it knows the name arg.

Type analysis has to deal with more than *just* names. Ideally, it should be
able to infer the type of a whole expression. But it *must* be able to deal
with names -- it would be a pretty poor type-checker that couldn't warn
about this:

n = 1
n.sort()


>> >  "@typehint: (str, int) -> bool"
>> >  def myfunction(arg1, arg2):
>> 
>> That's somewhat better, in that at least the hint is close to the
>> function signature. But it has a lot of disadvantages: it is compile-time
>> only, the type hints aren't available at runtime.
> 
> It's static analysis. You don't need runtime execution.

You don't "need" it, but Python has it, so that's what any alternative has
to target. If an alternative fails to met that target, that doesn't
necessarily rule the alternative out, but it is a point against it.

If you want to talk about programming languages in their full generality,
please say so, otherwise I'll assume you're referring to Python. Python
offers rich and powerful introspection abilities, and annotations are
available at runtime, which enables runtime access to the type hints. Any
alternative which does not offer that same runtime introspection is missing
an important piece of functionality.


>> It requires extra complexity to the
>> parser, so that decorators may be separated from the function by a hint:
>> 
>> @decorate
>> "@typehint: (str, int) -> bool"
>> def myfunction(arg1, arg2):
>> 
>> No doubt some people will get them the wrong way around, and the type
>> checker may silently ignore their hints:
>> 
>> "@typehint: (str, int) -> bool"
>> @decorate
>> def myfunction(arg1, arg2):
>> 
>> And others will write:
>> 
>> @decorate
>> @typehint(str, int) -> bool
>> def myfunction(arg1, arg2):
>> 
> 
> That seems like you are fishing. What is exactly your point? That people
> will not be able to understand the rules of type hinting?

No. My point was in the next sentence of my 

Re: Python is DOOMED! Again!

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 3:00 AM, Steven D'Aprano
 wrote:
> Mark Lawrence wrote:
>
>> On 24/01/2015 06:35, Steven D'Aprano wrote:
>>> Obviously I'm not a fanatic. If I'm working out my share of a $37 meal
>>> split three ways, I just do 37/3 the same as anyone else :-)
>>>
>>
>> Always rounding down I take it? :)
>
> I'm hurt. I have a maths degree, I know how to do division:
>
>   _
> 3| 37
>
>
> 3 goes into 3 once, and 3 goes into 7 twice with one remainder. So the
> answer is 12 and 1/3.

I'm not sure whereabouts you are, but I don't have a $1/3 coin in my
pocket most of the time. Mark probably doesn't have many £1/3 coins
either. So... rounding up or down? :)

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


pysftp connection not sending files, hanging on 'put'

2015-01-24 Thread Jules Stevenson
Hi List,

I'm trying to send some files via pysftp, authentication seems fine, but
actually putting the file results in it hanging, doing nothing. The files
are small (<200kb) so I don't believe it's an upload issue (internet access
is fine). Eventually the connection times out.

Code:

if os.listdir(ftp_path):# only do if files are there
with pysftp.Connection(FTP_SERVER,

port=

username=FTP_USER,

private_key=FTP_SSH_PRIVATE_KEY_PATH

) as sftp:

with sftp.cd(FTP_REMOTE_FOLDER):

for f in os.listdir(ftp_path):

if os.path.isfile(os.path.join(ftp_path,f)) :

# upload image to server

self.log.info("HB FTP, Start upload: "+f)

print(ftp_path+"\\"+f)

sftp.put(os.path.join(ftp_path,f))

self.log.info("HB FTP, Finished Upload: "+f)


Logging output here:

FSW_COMMS paramiko.transport 01/24/2015 04:23:58 PM: INFO: Authentication
(publickey) successful!
FSW_COMMS paramiko.transport 01/24/2015 04:23:58 PM: DEBUG: [chan 1] Max
packet in: 32768 bytes
FSW_COMMS paramiko.transport 01/24/2015 04:23:58 PM: DEBUG: [chan 1] Max
packet out: 0 bytes
FSW_COMMS paramiko.transport 01/24/2015 04:23:58 PM: DEBUG: Secsh channel 1
opened.
FSW_COMMS paramiko.transport 01/24/2015 04:23:58 PM: DEBUG: [chan 1] Sesch
channel 1 request ok
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: INFO: [chan 1]
Opened sftp connection (server version 3)
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: DEBUG: [chan 1]
normalize('.')
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: DEBUG: [chan 1]
stat('files')
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: DEBUG: [chan 1]
normalize('files')
FSW_COMMS root 01/24/2015 04:23:58 PM: INFO: HB FTP, Start upload:
2015-01-17-19-37-07.jpg
D:\FSW\ftp\2015-01-17-19-37-07.jpg
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: DEBUG: [chan 1]
open('/files/2015-01-17-19-37-07.jpg', 'wb')
FSW_COMMS paramiko.transport.sftp 01/24/2015 04:23:58 PM: DEBUG: [chan 1]
open('/files/2015-01-17-19-37-07.jpg', 'wb') ->
34613039393262343666383036653839

Any help much appreciated,

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Rick Johnson
On Saturday, January 24, 2015 at 7:30:02 AM UTC-6, Steven D'Aprano wrote:
> [...] It requires extra complexity to the parser, so that
> decorators may be separated from the function by a hint:
> 
> @decorate
> "@typehint: (str, int) -> bool"
> def myfunction(arg1, arg2):
> 
> No doubt some people will get them the wrong way around,
> and the type checker may silently ignore their hints:
> 
> "@typehint: (str, int) -> bool"
> @decorate
> def myfunction(arg1, arg2):
> 
> And others will write:
> 
> @decorate
> @typehint(str, int) -> bool
> def myfunction(arg1, arg2):
> 
> 
> and be annoyed or perplexed by the syntax error.
> 
> Some syntax will be a bug magnet. This is one.

Your argument is weak here. If the interpreter cannot
distinguish between "@typehint ..." and "@ ..." then those
who defined the logic need to go back to CS-101. Secondly,
why set *ANY* rules as to the order of typehints -vs-
decorators? Who cares about the "syntactical order", when
they can be parsed and then applied in *ANY* order.
Syntactical order need not *ALWAYS* be significant. In fact,
in this case, syntactic ordering rules are superfluously 
onerous on the human.

And that is how you kill two birds with one stone.


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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Steven D'Aprano
Rick Johnson wrote:

> On Saturday, January 24, 2015 at 7:30:02 AM UTC-6, Steven D'Aprano wrote:
>> [...] It requires extra complexity to the parser, so that
>> decorators may be separated from the function by a hint:
>> 
>> @decorate
>> "@typehint: (str, int) -> bool"
>> def myfunction(arg1, arg2):
>> 
>> No doubt some people will get them the wrong way around,
>> and the type checker may silently ignore their hints:
>> 
>> "@typehint: (str, int) -> bool"
>> @decorate
>> def myfunction(arg1, arg2):
>> 
>> And others will write:
>> 
>> @decorate
>> @typehint(str, int) -> bool
>> def myfunction(arg1, arg2):
>> 
>> 
>> and be annoyed or perplexed by the syntax error.
>> 
>> Some syntax will be a bug magnet. This is one.
> 
> Your argument is weak here. If the interpreter cannot
> distinguish between "@typehint ..." and "@ ..." 

Thank you for demonstrating my point for me.

The difference is not

@typehint(...)
def func(...): 

versus any other decorator, but the STRING:

"@typehint(...)"

being used where a decorator would normally be expected.

If a genius of the degree like Rick can be fooled, what hope do ordinary
mortals have?



-- 
Steven

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Steven D'Aprano
Chris Angelico wrote:

> On Sun, Jan 25, 2015 at 3:00 AM, Steven D'Aprano
>  wrote:
>> Mark Lawrence wrote:
>>
>>> On 24/01/2015 06:35, Steven D'Aprano wrote:
 Obviously I'm not a fanatic. If I'm working out my share of a $37 meal
 split three ways, I just do 37/3 the same as anyone else :-)

>>>
>>> Always rounding down I take it? :)
>>
>> I'm hurt. I have a maths degree, I know how to do division:
>>
>>   _
>> 3| 37
>>
>>
>> 3 goes into 3 once, and 3 goes into 7 twice with one remainder. So the
>> answer is 12 and 1/3.
> 
> I'm not sure whereabouts you are, but I don't have a $1/3 coin in my
> pocket most of the time. Mark probably doesn't have many £1/3 coins
> either. So... rounding up or down? :)

I'm right here, in front of my computer. Where are you?

Of course we don't have $1/3 dollar coins, but I do have a pair of tin-snips
and can easily cut a $1 coin into three equal pieces.

Either that, or make up change with 20¢, 10¢ and 5¢ (we practice
round-to-nearest-5-cents here).



-- 
Steven

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Mark Lawrence

On 24/01/2015 17:26, Steven D'Aprano wrote:

Rick Johnson wrote:


On Saturday, January 24, 2015 at 7:30:02 AM UTC-6, Steven D'Aprano wrote:

[...] It requires extra complexity to the parser, so that
decorators may be separated from the function by a hint:

@decorate
"@typehint: (str, int) -> bool"
def myfunction(arg1, arg2):

No doubt some people will get them the wrong way around,
and the type checker may silently ignore their hints:

"@typehint: (str, int) -> bool"
@decorate
def myfunction(arg1, arg2):

And others will write:

@decorate
@typehint(str, int) -> bool
def myfunction(arg1, arg2):


and be annoyed or perplexed by the syntax error.

Some syntax will be a bug magnet. This is one.


Your argument is weak here. If the interpreter cannot
distinguish between "@typehint ..." and "@ ..."


Thank you for demonstrating my point for me.

The difference is not

@typehint(...)
def func(...):

versus any other decorator, but the STRING:

"@typehint(...)"

being used where a decorator would normally be expected.

If a genius of the degree like Rick can be fooled, what hope do ordinary
mortals have?



So Rick is having a bad hair day, hence using fuzzy logic?  Ooh, that 
one is so bad even my stomach hurts :)


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

Mark Lawrence

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Paul Rubin
Steven D'Aprano  writes:
> versus any other decorator, but the STRING:
> "@typehint(...)"
> being used where a decorator would normally be expected.

I didn't catch that either.  I think if hints are to go in decorators,
then it's best to extend the decorator mechanism to allow arbitrary
syntax, e.g.

@-typehint (str, int) -> bool

The @- would signify that the typehint function is to receive an AST as
its argument, rather than its callable.  The AST would be the parse tree
for the rest of the line.  Alternatively, it could get the line as a
string and parse it with appropriate functions from the ast module.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python is DOOMED! Again!

2015-01-24 Thread Tim Chase
On 2015-01-25 04:31, Steven D'Aprano wrote:
> Of course we don't have $1/3 dollar coins, but I do have a pair of
> tin-snips and can easily cut a $1 coin into three equal pieces.

I'm impressed that you can use tin-snips to cut it into exactly three
equal pieces with greater precision than the floating point numbers
that you're cautioning against in Python.  I believe at that point,
you're talking about at least the sub-sub-sub-atomic scale. :-)

-tkc



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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Ethan Furman
On 01/23/2015 10:28 PM, Chris Angelico wrote:
> 
> cmd = {}
> def command(func):
> cmd[func.__name__] = func
> return func
> 
> @command
> def foo(*args):
> print("You asked to foo.")
> 
> but this is hardly generic. There's no convenient way to give an
> argument to a decorator that says "please assign this here", short of
> using some stupid eval hack... is there?

If the non-generic is what you're concerned about:

# not tested
dispatch_table_a = {}
dispatch_table_b = {}
dispatch_table_c = {}

class dispatch:
  def __init__(self, dispatch_table):
self.dispatch = dispatch_table
  def __call__(self, func):
self.dispatch[func.__name__] = func
return func

@dispatch(dispatch_table_a)
def foo(...):
   pass

--
~Ethan~



signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python is DOOMED! Again!

2015-01-24 Thread Rustom Mody
On Sunday, January 25, 2015 at 12:15:28 AM UTC+5:30, Tim Chase wrote:
> On 2015-01-25 04:31, Steven D'Aprano wrote:
> > Of course we don't have $1/3 dollar coins, but I do have a pair of
> > tin-snips and can easily cut a $1 coin into three equal pieces.
> 
> I'm impressed that you can use tin-snips to cut it into exactly three
> equal pieces with greater precision than the floating point numbers
> that you're cautioning against in Python.  I believe at that point,
> you're talking about at least the sub-sub-sub-atomic scale. :-)
> 
> -tkc

With Superman¹, you should expect nails that cut electrons precisely

¹ And other s-starting names
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Terry Reedy

On 1/24/2015 5:16 AM, Mario Figueiredo wrote:


Consider the following code at your REPL of choice



class Sub:
pass

foo = Sub()

Sub.__bases__
foo.__bases__

The last statement originates the following error:


This is an anomalous situation.  Normally, if a class has an attribute, 
instances have the same attribute (unless overriden).  But this does not 
matter.



AttributeError: 'Sub' object has no attribute '__bases__'


In this message, 'Sub' is an adjective, modifying 'object, not naming 
it.  If you attend to the last line of the traceback


foo.__bases__

which is an integral part of the total error message, the interpretation 
of this exception message should be clear.



AttributeError: 'Sub' instance has no attribute '__bases__',


'Sub' is an instance of 'type', so "'Sub' instance" could also be taken 
to mean the class if the traceback were ignored.  But that would also be 
wrong.  An attribute error for the class, such as "Sub.xyz" give a 
message ending with

...
Sub.xyz
AttributeError: type object 'Sub' has no attribute 'xyz'

--
Terry Jan Reedy

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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 5:56 AM, Ethan Furman  wrote:
> If the non-generic is what you're concerned about:
>
> # not tested
> dispatch_table_a = {}
> dispatch_table_b = {}
> dispatch_table_c = {}
>
> class dispatch:
>   def __init__(self, dispatch_table):
> self.dispatch = dispatch_table
>   def __call__(self, func):
> self.dispatch[func.__name__] = func
> return func
>
> @dispatch(dispatch_table_a)
> def foo(...):
>pass

That's still only able to assign to a key of a dictionary, using the
function name. There's no way to represent fully arbitrary assignment
in Python - normally, you can assign to a name, an attribute, a
subscripted item, etc. (Augmented assignment is a different beast
altogether, and doesn't really make sense with functions.) There's no
easy way to say "@stash(dispatch_table_a['asdf'])" and have that end
up assigning to exactly that.

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 4:37 AM, Paul Rubin  wrote:
> Steven D'Aprano  writes:
>> versus any other decorator, but the STRING:
>> "@typehint(...)"
>> being used where a decorator would normally be expected.
>
> I didn't catch that either.  I think if hints are to go in decorators,
> then it's best to extend the decorator mechanism to allow arbitrary
> syntax, e.g.
>
> @-typehint (str, int) -> bool
>
> The @- would signify that the typehint function is to receive an AST as
> its argument, rather than its callable.  The AST would be the parse tree
> for the rest of the line.  Alternatively, it could get the line as a
> string and parse it with appropriate functions from the ast module.

That seems extremely messy. Why not use what can already be done?
Since you talk about getting the line as a string...

@typehint("(str, int) -> bool")

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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Devin Jeanpierre
On Sat, Jan 24, 2015 at 11:55 AM, Chris Angelico  wrote:
> That's still only able to assign to a key of a dictionary, using the
> function name. There's no way to represent fully arbitrary assignment
> in Python - normally, you can assign to a name, an attribute, a
> subscripted item, etc. (Augmented assignment is a different beast
> altogether, and doesn't really make sense with functions.) There's no
> easy way to say "@stash(dispatch_table_a['asdf'])" and have that end
> up assigning to exactly that.

Obviously, nobody will be happy until you can do:

def call(*a, **kw): return lambda f: f(*a, **kw)

@call()
def x, y ():
yield 1
yield 2

Actually, maybe not even then.

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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread MRAB

On 2015-01-24 19:55, Chris Angelico wrote:

On Sun, Jan 25, 2015 at 5:56 AM, Ethan Furman  wrote:

If the non-generic is what you're concerned about:

# not tested
dispatch_table_a = {}
dispatch_table_b = {}
dispatch_table_c = {}

class dispatch:
  def __init__(self, dispatch_table):
self.dispatch = dispatch_table
  def __call__(self, func):
self.dispatch[func.__name__] = func
return func

@dispatch(dispatch_table_a)
def foo(...):
   pass


That's still only able to assign to a key of a dictionary, using the
function name. There's no way to represent fully arbitrary assignment
in Python - normally, you can assign to a name, an attribute, a
subscripted item, etc. (Augmented assignment is a different beast
altogether, and doesn't really make sense with functions.) There's no
easy way to say "@stash(dispatch_table_a['asdf'])" and have that end
up assigning to exactly that.


Here's a slight variation on the theme:


class DispatchTable(dict):
def __call__(self, name):
def setter(func):
self[name] = func
return func
return setter

command = DispatchTable()

@command("foo")
def _(*args):
print("You asked to foo.")

@command("bar")
def _(*args):
print("There's no wine in the bar.")

@command("asdf")
def _(*args):
print("Asdf! Asdf!")

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


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Fetchinson .
On 1/24/15, Steven D'Aprano  wrote:
> Fetchinson . wrote:
>
>> On 1/23/15, Steven D'Aprano  wrote:
> [...]
>>> Cobra is especially close to Python-like syntax, and supports unit tests
>>> as well:
>>>
>>>
>>> def sqroot(i as int) as float
>>> require
>>>i > 0
>>> ensure
>>>result > 0
>>> tests
>>>assert sqroot(25) == 5.0
>>> body
>>> ...
>>>
>>> It would be nice to be able to include at least *some* tests right there
>>> in the code rather than in a separate file.
>>
>> I completely agree. A cobra-style type hinting implementation would
>> satisfy everyone who doesn't want to make function signatures noisy
>> (including me) and would also satisfy those who advocate for the
>> actual feature (type hinting) without worrying much about the
>> implementation detail. These two groups are overlapping by the way :)
>
> I don't understand this. Cobra's type-hints are right there in the function
> signature, just like Python annotations.
>
>
> # Cobra
> def sqroot(i as int) as float
>
> # Python
> def sqroot(i:int)->float:

You are right. This aspect is pretty close, what I had in mind, but
expressed myself poorly is this idiom in cobra:

def myfunc( a, b )
require
something_about( a, b )
ensure
something_about_the_return_value

Yes, type hinting and arbitrary constraints on the function arguments
and return types are different things, but closely related. I'd say it
makes sense to combine the two.

>
> Cobra's use of "as" clashes with Python. In Python, "as" is used for
> name-binding:
>
> import module as name
> with open('file') as f
> except Exception as e
>
> but apart from that minor difference, they're virtually identical.
>
>
>> In any case, I'm pretty sure it was said before, but I can't really
>> find it anywhere, can someone tell me what the rationale is for
>> *function signature* type hinting?
>
> The basic principle is that things which are related should be found
> together. The further away they are, the worse.
>
> Bad:
> - the parameter name and the type are in different files
>
> Better:
> - the parameter name and the type are only a few lines apart
>
> Best:
> - the parameter name and type are right next to each other
>
>
> The closer they are, the easier it is to keep them in sync, and the easier
> it is to see the relevant information at a glance. Putting them together
> also means that you don't have to repeat the argument name:
>
> int n
> def spam(n): ...
>
> versus
>
> def spam(n:int): ...
>
>
> Those reasons are why decorators have the syntax which they do:
>
> @decorator
> def spam(n):
> do_this()
> do_that()
> do_something_else()
>
>
> is better than the old way of using decorators:
>
> def spam(n):
> do_this()
> do_that()
> do_something_else()
>
> spam = decorator(spam)
>
>
> The decorator is only a single line away from the signature, and you don't
> have to repeat the name.
>
>
> We can see this at work in Pascal. Pascal functions have type declarations
> in the signature, and variable declarations between the signature and the
> body:
>
>
> function sqroot(arg: Integer): Real;
>   var
> x: Integer;
> y: Real;
> z: Something_Else;
>   begin
> do_this(1, 2);
> do_that(3, 4);
> do_something_else(5, 6);
> x := some expression;  { what's the type of x again? }
>   end;
>
>
> The declarations in the signature work very well and are easy to use, but
> the "var" section, not so much. Especially in large functions, the place
> where you declare the variable and its type, and the place where you first
> use it, can be separated by many lines. This makes maintenance and reading
> of the code more difficult.
>
> Newer languages like Java let you declare the variable the first time you
> use it:
>
> int x = some expression;
>
> and you don't have to search very far to find out what sort of thing x is,
> it is right there.
>
>
>
> --
> Steven
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> > AttributeError: 'Sub' object has no attribute '__bases__'
> 
> In this message, 'Sub' is an adjective, modifying 'object, not naming 
> it.  If you attend to the last line of the traceback
> 

My first reaction is to look at 'Sub' as a noun, not an adjective, since 
I know that NAME well on my code as being a noun. Meanwhile I know that 
objects may be qualified (adjectivized) as class objects or instance 
objects. So, I also happen to look at the word "object" as an adjective, 
as Python object semantics would me do.

What you propose is that I look at that phrase the other way around, 
which is kind of contrarian to how you actually use them in your code.


> > AttributeError: 'Sub' instance has no attribute '__bases__',
> 
> 'Sub' is an instance of 'type', so "'Sub' instance" could also be taken 
> to mean the class if the traceback were ignored.

I agree. Sub instance is still somewhat ambiguous. So, maybe:

 AttributeError: Instance of object 'Sub' has no attribute 
'__bases__'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python is DOOMED! Again!

2015-01-24 Thread alister
> 
> Of course we don't have $1/3 dollar coins, but I do have a pair of
> tin-snips and can easily cut a $1 coin into three equal pieces.

wow you have just given a physical demonstration of integer Maths
$1 /3 =$0
as the coin is now worthless ;-)
> 
> Either that, or make up change with 20¢, 10¢ and 5¢ (we practice
> round-to-nearest-5-cents here).

I suppose if you all pay 35¢  it at least gives the waitress a tip.





-- 
Many pages make a thick book.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article <[email protected]>, 
[email protected] says...
> > AttributeError: 'Sub' instance has no attribute '__bases__', 
> > AttributeError: 'foo' object has no attribute '__bases__'
> 
> The first would be nice. The second is impossible: objects may have no name,
> one name, or many names, and they do not know what names they are bound to.
> So the Sub instance bound to the name 'foo' doesn't know that its name
> is 'foo', so it cannot display it in the error message.

Thanks for the information! :)

But that begs the OT question: How does Python maps names to memory 
addresses in the interpreter?

"__main__"
from module import a_name
y = a_name + 1

How does python interpreter know how to map 'name' to the correct memory 
location, if this __main__ code is only ran after 'module' code?  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Sanity Proposal: Type Hinting Solution

2015-01-24 Thread Christian Gollwitzer
Am 23.01.15 um 20:23 schrieb Rick Johnson:
> On Thursday, January 22, 2015 at 9:22:40 PM UTC-6, Terry Reedy wrote:
>> that it is already an option in mypy and is part of the new
>> type-hint proposal.
> 
> An *OPTION*? If it is not mandatory then why bother? If
> authors have a choice between writing type hints into func
> sigs or writing them in a "stub file", then the natural
> human behavior of "slothfulness" will bring about the
> destruction of Python via syntactic noise. Heck, why don't
> we just adopt the *REAL* fairness doctrine and make
> indentation optional? 

Actually, optional indentation is not a bad idea in itself. For example
in Haskell, you can use indentation much in the same way as you use it
in Python. But you can also add semicolons and braces instead, which
override the indentation, on a per-statement basis. This permits more
freedom in code layout, for example it allows reasonable one-line ifs.


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


Re: __bases__ misleading error message

2015-01-24 Thread Ian Kelly
On Sat, Jan 24, 2015 at 2:14 PM, Mario Figueiredo  wrote:
> In article <[email protected]>,
> [email protected] says...
>> > AttributeError: 'Sub' instance has no attribute '__bases__',
>> > AttributeError: 'foo' object has no attribute '__bases__'
>>
>> The first would be nice. The second is impossible: objects may have no name,
>> one name, or many names, and they do not know what names they are bound to.
>> So the Sub instance bound to the name 'foo' doesn't know that its name
>> is 'foo', so it cannot display it in the error message.
>
> Thanks for the information! :)
>
> But that begs the OT question:

No, it doesnt. http://en.wikipedia.org/wiki/Begging_the_question

> How does Python maps names to memory
> addresses in the interpreter?

Global variables are looked up in the current stack frame's globals dict.

>>> a = 1
>>> b = 2
>>> globals()['a']
1
>>> globals()['b']
2

Local variables of functions could be handled the same way, but for
efficiency the compiler instead maps the names to indices of a local
variable array associated with the stack frame. Either way, at the C
level the value stored in the dict or array is a pointer to the memory
location of the object.

> "__main__"
> from module import a_name
> y = a_name + 1
>
> How does python interpreter know how to map 'name' to the correct memory
> location, if this __main__ code is only ran after 'module' code?

I'm not sure I'm understanding what you're asking, but the import
statement imports the module, looks up "a_name" in that module's
globals dict, and binds the same object to a_name in the current
module's globals dict.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Marco Buttu

On 24/01/2015 20:24, Terry Reedy wrote:


On 1/24/2015 5:16 AM, Mario Figueiredo wrote:


Consider the following code at your REPL of choice



class Sub:
pass

foo = Sub()

Sub.__bases__
foo.__bases__

The last statement originates the following error:


This is an anomalous situation.  Normally, if a class has an attribute,
instances have the same attribute (unless overriden).  But this does not
matter.


That is not true: if a class has an attribute, you can not say its 
instances have the same attribute. You can just say if a type defines an 
attribute, all its instances have that attribute. Look at this example:


>>> class Foo(type):
... foo = 33
...
>>> Foo.foo
33
>>> MyClass = Foo('MyClass', (), {})

MyClass is an instance of Foo, so it must have the attribute foo:

>>> isinstance(MyClass, Foo)
True
>>> MyClass.foo
33

But an instance of MyClass is not an instance of Foo, and so MyClass() 
must not have the attribute foo. In fact:


>>> m = MyClass()
>>> isinstance(m, Foo)
False
>>> m.foo
Traceback (most recent call last):
...
AttributeError: 'MyClass' object has no attribute 'foo'


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


Re: Python is DOOMED! Again!

2015-01-24 Thread Ian Kelly
On Sat, Jan 24, 2015 at 2:14 PM, alister
 wrote:
>>
>> Either that, or make up change with 20¢, 10¢ and 5¢ (we practice
>> round-to-nearest-5-cents here).
>
> I suppose if you all pay 35¢  it at least gives the waitress a tip.

"""
In the Pacific States they have made a bolder push for complexity, and
settle their affairs by a coin that no longer exists – the BIT, or old
Mexican real. The supposed value of the bit is twelve and a half
cents, eight to the dollar. When it comes to two bits, the
quarter-dollar stands for the required amount. But how about an odd
bit? The nearest coin to it is a dime, which is, short by a fifth.
That, then, is called a SHORT bit. If you have one, you lay it
triumphantly down, and save two and a half cents. But if you have not,
and lay down a quarter, the bar-keeper or shopman calmly tenders you a
dime by way of change; and thus you have paid what is called a LONG
BIT, and lost two and a half cents, or even, by comparison with a
short bit, five cents.
"""
-- Robert Louis Stevenson
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Terry Reedy

On 1/24/2015 4:14 PM, Mario Figueiredo wrote:

In article <[email protected]>,
[email protected] says...

 AttributeError: 'Sub' instance has no attribute '__bases__',
 AttributeError: 'foo' object has no attribute '__bases__'


The first would be nice. The second is impossible: objects may have no name,
one name, or many names, and they do not know what names they are bound to.
So the Sub instance bound to the name 'foo' doesn't know that its name
is 'foo', so it cannot display it in the error message.


Thanks for the information! :)

But that begs the OT question: How does Python maps names to memory
addresses in the interpreter?


Python the language maps names to objects that have identity, type, and 
value.  The CPython implementation does the mapping with a hash table 
and C pointers (to computer memory addresses), but addresses are not 
part of the language definition.  Neuroscientists still puzzle over how 
we do such mapping.



 "__main__"
 from module import a_name


A module is a namespace associating names with objects.  This statememt 
says to import the a_name to object association from module and add it 
to __main__



 y = a_name + 1


This statement uses the imported association in __main__ to access the 
object and add 1, and bind 'y' to the resulting object.


--
Terry Jan Reedy

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


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> 
> >  "__main__"
> >  from module import a_name
> 
> A module is a namespace associating names with objects.  This statememt 
> says to import the a_name to object association from module and add it 
> to __main__
> 
> >  y = a_name + 1
> 
> This statement uses the imported association in __main__ to access the 
> object and add 1, and bind 'y' to the resulting object.


But I'm being told the interpreter has no knowledge of a variable name. 
So, how does the interpreter know, once it reaches the assigment line 
above, how to map a_name to the correct object in memory?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> 
> On Sat, Jan 24, 2015 at 2:14 PM, Mario Figueiredo  wrote:
> > But that begs the OT question:
> 
> No, it doesnt. http://en.wikipedia.org/wiki/Begging_the_question

Cute.

> I'm not sure I'm understanding what you're asking, but the import
> statement imports the module, looks up "a_name" in that module's
> globals dict, and binds the same object to a_name in the current
> module's globals dict.

Meaning the interpreter knows a variable's name. Which would allow it to 
produce an error message such as:

AttributeError: 'foo' object has no attribute '__bases__'

For the following code:

class Sub:
pass
 
foo = Sub()
foo.__bases__


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


Re: __bases__ misleading error message

2015-01-24 Thread Marco Buttu

On 24/01/2015 13:43, Steven D'Aprano wrote:


Mario Figueiredo wrote:


> class Sub:
> pass
>
> foo = Sub()
>
> Sub.__bases__
> foo.__bases__
>
>The last statement originates the following error:
>
> AttributeError: 'Sub' object has no attribute '__bases__'

It's a bit ambiguous, but the way to read it is to think of object as a
synonym for instance.

...



>Naturally the 'Sub' object has an attribute __bases__.

Correct, in the sense that classes are objects too. But in the sense of
object=instance, no. Isn't ambiguous terminology wonderful?


In my opinion it is not ambiguous, because as you say in Python an 
object is a synonym for instance. We can say in Python an object is an 
instance of the type object, that's all. And that's why everything is an 
object in Python:


>>> isisntace(foo, object) # For every foo
True

So a class (a type) is an instance too, an instance of its metaclass. 
Therefore, the message says that the Sub instance has no attribute 
'__bases__'. In fact the Sub object (instance) has no attribute 
'__bases__' because it is not an instance of type, and only types 
(classes) have this attribute.


So if we want to find some differences between objects, we have to 
distinguish between types (classes) and non-types (non-classes) objects, 
and not between objects and classes.
In the Python documentation there is also a bit of confusion about 
this... In the descriptor howto: "The details of invocation depend on 
whether obj is an object or a class" :/



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


Re: __bases__ misleading error message

2015-01-24 Thread Ian Kelly
On Sat, Jan 24, 2015 at 3:02 PM, Mario Figueiredo  wrote:
> In article ,
> [email protected] says...
>>
>> >  "__main__"
>> >  from module import a_name
>>
>> A module is a namespace associating names with objects.  This statememt
>> says to import the a_name to object association from module and add it
>> to __main__
>>
>> >  y = a_name + 1
>>
>> This statement uses the imported association in __main__ to access the
>> object and add 1, and bind 'y' to the resulting object.
>
>
> But I'm being told the interpreter has no knowledge of a variable name.
> So, how does the interpreter know, once it reaches the assigment line
> above, how to map a_name to the correct object in memory?

No, you're being told that the *object* doesn't know the names of the
variables that it's bound to. In the context above, the variable is
right there under that name in the globals dict, as can be seen in the
disassembly:

>>> import dis
>>> dis.dis("y = a_name + 1")
  1   0 LOAD_NAME0 (a_name)
  3 LOAD_CONST   0 (1)
  6 BINARY_ADD
  7 STORE_NAME   1 (y)
 10 LOAD_CONST   1 (None)
 13 RETURN_VALUE

Now what happens in the byte code if we try to access an attribute on
that object?

>>> dis.dis("a_name.__bases__")
  1   0 LOAD_NAME0 (a_name)
  3 LOAD_ATTR1 (__bases__)
  6 RETURN_VALUE

1) The value of a_name is looked up and pushed onto the stack.

2) The interpreter attempts to load the attribute __bases__ of
whatever object is on the top of the stack. There is no name
associated with that object at this point; it's just an object.

Now imagine if the Python code in question were instead this:

def get_an_object(): return "foo"
get_an_object().__bases__

Would you really expect the interpreter to come up with a message like
"Return value of get_an_object() has no attribute '__bases__'"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 9:09 AM, Mario Figueiredo  wrote:
> Meaning the interpreter knows a variable's name. Which would allow it to
> produce an error message such as:
>
> AttributeError: 'foo' object has no attribute '__bases__'
>
> For the following code:
>
> class Sub:
> pass
>
> foo = Sub()
> foo.__bases__

Let me explain by way of analogy. You have ten shoeboxes to store your
stuff in. I hand you a thing and say "Here, put this into shoebox #4".
Then someone else comes along and says, "I need the thing from shoebox
#4", so you give him that thing. Now, he hands that thing to someone
else and asks him which shoebox it came out of, just by looking at the
thing itself. How can he say? The thing doesn't have any way of
knowing what shoebox it came out of.

Python names reference objects. But once you get an object, there's no
way of knowing which name was used to get to it. There might be one
such name; there might be more than one; and there might not be any.
You can't identify an object by the name it's bound to, but you can
identify it by something that's always true of the object itself, like
its type.

There are a few cases where names are so useful that they get attached
to the objects themselves. The 'def' and 'class' statements create
objects and also record the names used. But you still can't identify
what name was used to reference something:

>>> def func(x): print("x = %s"%x)
...
>>> func(123)
x = 123
>>> show = func
>>> show(234)
x = 234
>>> func = "not a function"
>>> func(123)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object is not callable
>>> show(123)
x = 123
>>> show


No matter what name I use to reference the function, it's still called
"func". Nobody can ever know that I'm identifying it by the name
'show' now.

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


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> 
> Let me explain by way of analogy. 
[snipped]

Gotcha! Thanks for the explanation :)

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mario Figueiredo
In article <[email protected]>, 
[email protected] says...
> 
> I don't think that a raise of 0.10001 (10%),
> 0.035003 (3.5%) or 0.070007 (7%) is quite what
> people intended.
> 
> (Don't use binary floating point numbers for anything related to
> money. Just don't.)

Few rules are written in stone and that rule isn't either. It all 
depends on the context. People often read these bits of well intentioned 
advise and go on to immediately make some kind of gospel out of it. Why 
is that?

And why is that? Why do you think I can't ever use floats for money? Is 
there some kind of unspoken rule that money must always be dealt with 
with enough precision to give a microscope an headache?

- What if I am storing money as an integer or a 2 decimal place Decimal 
to manage my electrical bill and I use a float to express a percentage?
- What if the float operation is not a repetitive operation that would 
indeed invariably lead to round errors, but instead a once in a lifetime 
operation?

I'm not saying I don't agree we should avoid it. I'm saying we need also 
to properly contextualize it before we decide to do so. If I'm writing a 
banking system, or a POS, you will be damn sure it will be hard to spot 
a float in my code.

But if I'm writing my household electrical bill yearly report, or I'm 
writting a damn code snippet on a python group to illustrate how type 
hinting mangles your code, who gives a flying arse if I'm using a float 
to express money? Sheesh!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 9:33 AM, Mario Figueiredo  wrote:
> In article ,
> [email protected] says...
>>
>> Let me explain by way of analogy.
> [snipped]
>
> Gotcha! Thanks for the explanation :)

Awesome! I'm always a bit wary of analogies... sometimes they're
really helpful, other times they're unhelpful and confusing. Glad this
was one of the better cases.

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


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> 
> No, you're being told that the *object* doesn't know the names of the
> variables that it's bound to. In the context above, the variable is
> right there under that name in the globals dict, as can be seen in the
> disassembly:
[snipped]

Yes. I got it now. I misinterpreted Steven words.
-- 
https://mail.python.org/mailman/listinfo/python-list


Delegation in Python

2015-01-24 Thread Brian Gladman
I would appreciate advice on how to set up delgation in Python.

I am continuously implementing a function to test whether a Python
Fraction is an integer so I wanted to define a new class, based on
Fraction, that includes this new method.

But I am not clear on how to delegate from my new class to the existing
Fraction class.  This is what I have:

--
class RF(Fraction):

  def __new__(self, x, y):
super().__new__(self, x, y)

  def is_integer(self):
return self.numerator % self.denominator == 0

  def __getattr__(self, attr):
return getattr(self, attr)
--

which doesn't work.

Any advice on how to do this would be much appreciated.

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


Re: __bases__ misleading error message

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> Awesome! I'm always a bit wary of analogies... sometimes they're
> really helpful, other times they're unhelpful and confusing.

Yeah. Your's was all it took :)

The thing with analogies is to never take them literally. They are 
analogies, after all. But there is this old funny thing we humans seem 
to share that an analogy should be dissected like it was a scientific 
paper.

- You say shoes in a box? Why, but memory addresses aren't boxes. 
Besides a box can only take shoes this big. Memory addresses can take 
any size object.

- No I meant.. Look, just imagine shoes in a box.

- Alright...

- Now the other person will be handed the shoe you asked. They don't 
know what box it came from. What this mea...

- How come?

- How come what?

- Why don't they know? They could just agree to know what box the shoe 
came from. Problem solved.

- No, but I am trying to illustrate how it works. Not how it could work.

- I still don't get it. Why does it work like that. Seems stupid...

- It's not. There are specific reasons to not know. It's got to do with 
the process stack and efficiency and...

- Right.

And there's also the most annoying of all, the smartasses that like to 
stay hidden in the shadows and as soon as they see an analogy they jump 
in and tada!

"It's not true that memory spaces can hold any object size. It is 
limited by the computer available memory" -- well, duh!

"Is that a float you are using to compute a salary raise in your code 
snippet meant as an example to illustrate code syntax? Hahaha" -- Sigh!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Yawar Amin
Hi,

On Saturday, January 24, 2015 at 3:36:04 PM UTC-5, Devin Jeanpierre
wrote:
> [...]
> Obviously, nobody will be happy until you can do:
> 
> def call(*a, **kw): return lambda f: f(*a, **kw)
> 
> @call()
> def x, y ():
> yield 1
> yield 2
> 
> Actually, maybe not even then.

You're probably right, because someone already _has_ come up with that: 


https://github.com/carymrobbins/python-blocks/blob/f51d10bd2439990cce7e2cb78e6e56ed05e78648/src/blocks.py#L191

Anyway Chris, to answer your question, the python-blocks repo shows the
'functional decorator style' taken to its logical conclusion, with
decorators for all the various functional building blocks like mapping,
folding, currying, etc.

Incidentally, with a properly-defined decorator 'factory', you could get
a pretty generic decorator for your dispatch example:

cmd = {}
dispatch = make_dispatch(cmd)

@dispatch
def foo(*args): print("You asked to foo.")

@dispatch
def bar(*args): print("There's no wine in the bar.")

@dispatch
def cmd2(*args): print("Asdf! Asdf!")

cmd["foo"]()
# Etc.

Regards,

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


Re: Delegation in Python

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman  wrote:
> But I am not clear on how to delegate from my new class to the existing
> Fraction class.  This is what I have:
>
> --
> class RF(Fraction):
>
>   def __new__(self, x, y):
> super().__new__(self, x, y)
>
>   def is_integer(self):
> return self.numerator % self.denominator == 0
>
>   def __getattr__(self, attr):
> return getattr(self, attr)

If you just drop everything but your new method, it should work just fine.

class RF(Fraction):
def is_integer(self):
   return self.numerator % self.denominator == 0

However, this doesn't ensure that operations on RFs will return more
RFs - they'll often return Fractions instead. There's no easy fix for
that, sorry.

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Rick Johnson
On Saturday, January 24, 2015 at 1:49:08 AM UTC-6, Steven D'Aprano wrote:
> Rick Johnson wrote:
> 
> [... snip absurdities...]
> 
> > Duh! Do you think i just pulled stub files out my arse
> > without giving all the other alternatives due consideration?
> 
> Actually, yes. I think that had Guido proclaimed that
> C-style header files were the only way to give type hints,
> you would be arguing right now that they were awful and
> that the one and only correct way to do type-hinting is to
> use annotations.

So now we arrive at the true nature of our conflict: your
"false projections" of my "true intentions".

Listen, I hold a deep respect for Guido's achievements and
his intellectual prowess, but i'm not about to kiss is
backside when i feel he is wrong, and this "type hints" idea
is dangerously wrong!

Diversity, dissension, and conflict are our friends, not
enemies to be feared. We must embrace those ideas that are
foreign to us, give them due consideration, and objectively
apply "weighted values" to them. Whereas, sitting in a room
surrounded by mirrors and becoming lost in the recursive
"reflection of self", is not evolution, but merely, an
illusion.

Besides, why does he need *ME* to lick his boots when he
already has plenty of fan-boys over at python-ideas and
python-dev lining up. This community is *NOT*, and should
never be, a homogeneous block -- for we would be doing
ourselves a disservice.

So if you cannot provide me with respect that i *DESERVE* as
a member of this fine community, then you should at least
admit that my presence is a vital counterbalance to prevent
this tiny life-vessel from capsizing as it's thrashed around
the treacherous "seas of evolution".

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 10:20 AM, Rick Johnson
 wrote:
> Besides, why does he need *ME* to lick his boots when he
> already has plenty of fan-boys over at python-ideas and
> python-dev lining up. This community is *NOT*, and should
> never be, a homogeneous block -- for we would be doing
> ourselves a disservice.

Wow. You think that, without you, python-ideas is homogeneous? I don't
think so. If it were, it would be called python-idea.

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


Re: Delegation in Python

2015-01-24 Thread Brian Gladman
On 24/01/2015 23:22, Chris Angelico wrote:
> class RF(Fraction):
> def is_integer(self):
>return self.numerator % self.denominator == 0

Thanks for your help on this.  I must admit that nowhere in a lot of
searching did I find that delegation is achieved by doing nothing!

   Brian



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


Re: Delegation in Python

2015-01-24 Thread Gary Herron

On 01/24/2015 03:22 PM, Chris Angelico wrote:

On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman  wrote:

But I am not clear on how to delegate from my new class to the existing
Fraction class.  This is what I have:

--
class RF(Fraction):

   def __new__(self, x, y):
 super().__new__(self, x, y)

   def is_integer(self):
 return self.numerator % self.denominator == 0

   def __getattr__(self, attr):
 return getattr(self, attr)

If you just drop everything but your new method, it should work just fine.

class RF(Fraction):
 def is_integer(self):
return self.numerator % self.denominator == 0

However, this doesn't ensure that operations on RFs will return more
RFs - they'll often return Fractions instead. There's no easy fix for
that, sorry.

ChrisA


You can always "monkey-path" the Fraction class on the fly to add a new 
method to it.  I think most would consider this a bad idea, but it does 
work.

Try this:

>>> from fractions import Fraction
>>> def is_integer(self):
... return self.numerator % self.denominator == 0
...
>>> Fraction.is_integer = is_integer # Monkey-patch Fraction
>>>
>>> Fraction(1,2).is_integer()
False
>>> Fraction(2,1).is_integer()
True


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mario Figueiredo
In article , 
[email protected] says...
> 
> On Sun, Jan 25, 2015 at 10:20 AM, Rick Johnson
>  wrote:
> > Besides, why does he need *ME* to lick his boots when he
> > already has plenty of fan-boys over at python-ideas and
> > python-dev lining up. This community is *NOT*, and should
> > never be, a homogeneous block -- for we would be doing
> > ourselves a disservice.
> 
> Wow. You think that, without you, python-ideas is homogeneous? I don't
> think so. If it were, it would be called python-idea.

He didn't say python-ideas is homogeneous. He didn't say either that he 
is the only one who dissents.

There's already too much of "not wanting to listen to what the other 
person is saying" by both sides of this debate. Let's not add more...


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


Re: Delegation in Python

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 10:38 AM, Brian Gladman  wrote:
> On 24/01/2015 23:22, Chris Angelico wrote:
>> class RF(Fraction):
>> def is_integer(self):
>>return self.numerator % self.denominator == 0
>
> Thanks for your help on this.  I must admit that nowhere in a lot of
> searching did I find that delegation is achieved by doing nothing!

Hehe :) If you want a technical look at it, what you have is the
fundamental nature of subclassing: you derive from another class, and
your class is identical to that with certain exceptions (in your case,
an additional method). Python's way of handling that is called the
Method Resolution Order or MRO, and you can find info on it on the
web, eg:

http://python-history.blogspot.com/2010/06/method-resolution-order.html

Enjoy!

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 10:39 AM, Mario Figueiredo  wrote:
> In article ,
> [email protected] says...
>>
>> On Sun, Jan 25, 2015 at 10:20 AM, Rick Johnson
>>  wrote:
>> > Besides, why does he need *ME* to lick his boots when he
>> > already has plenty of fan-boys over at python-ideas and
>> > python-dev lining up. This community is *NOT*, and should
>> > never be, a homogeneous block -- for we would be doing
>> > ourselves a disservice.
>>
>> Wow. You think that, without you, python-ideas is homogeneous? I don't
>> think so. If it were, it would be called python-idea.
>
> He didn't say python-ideas is homogeneous. He didn't say either that he
> is the only one who dissents.
>
> There's already too much of "not wanting to listen to what the other
> person is saying" by both sides of this debate. Let's not add more...

True. But anyone who's actually participated in python-ideas knows
that there are PLENTY of dissenting voices. :)

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


Re: Delegation in Python

2015-01-24 Thread Gary Herron

On 01/24/2015 03:38 PM, Brian Gladman wrote:

On 24/01/2015 23:22, Chris Angelico wrote:

class RF(Fraction):
 def is_integer(self):
return self.numerator % self.denominator == 0

Thanks for your help on this.  I must admit that nowhere in a lot of
searching did I find that delegation is achieved by doing nothing!

Brian


That's *not* "doing nothing".   And it's not even really "delegation".  
It's just sub-classing Fraction to add one new method and inherit all 
other methods.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: Delegation in Python

2015-01-24 Thread Brian Gladman
On 24/01/2015 23:41, Gary Herron wrote:

[snip]>
> You can always "monkey-path" the Fraction class on the fly to add a new
> method to it.  I think most would consider this a bad idea, but it does
> work.
> Try this:
> 
 from fractions import Fraction
 def is_integer(self):
> ... return self.numerator % self.denominator == 0
> ...
 Fraction.is_integer = is_integer # Monkey-patch Fraction

 Fraction(1,2).is_integer()
> False
 Fraction(2,1).is_integer()
> True

Thanks Gary.  As Chris says, the method he suggests is problematic since
anything delegated returns a Fraction, not an RF.  Patching Fraction
looks nicer to use even if it is frowned on.

   Brian

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mark Lawrence

On 24/01/2015 23:20, Rick Johnson wrote:

On Saturday, January 24, 2015 at 1:49:08 AM UTC-6, Steven D'Aprano wrote:

Rick Johnson wrote:

[... snip absurdities...]


Duh! Do you think i just pulled stub files out my arse
without giving all the other alternatives due consideration?


Actually, yes. I think that had Guido proclaimed that
C-style header files were the only way to give type hints,
you would be arguing right now that they were awful and
that the one and only correct way to do type-hinting is to
use annotations.


So now we arrive at the true nature of our conflict: your
"false projections" of my "true intentions".

Listen, I hold a deep respect for Guido's achievements and
his intellectual prowess, but i'm not about to kiss is
backside when i feel he is wrong, and this "type hints" idea
is dangerously wrong!


For at least the third time the PEP was written by three people, one of 
whom was the BDFL.  Why do you keep insisting that "he" is wrong, surely 
it should be "they" ?




Diversity, dissension, and conflict are our friends, not
enemies to be feared. We must embrace those ideas that are
foreign to us, give them due consideration, and objectively
apply "weighted values" to them. Whereas, sitting in a room
surrounded by mirrors and becoming lost in the recursive
"reflection of self", is not evolution, but merely, an
illusion.

Besides, why does he need *ME* to lick his boots when he
already has plenty of fan-boys over at python-ideas and
python-dev lining up. This community is *NOT*, and should
never be, a homogeneous block -- for we would be doing
ourselves a disservice.


A substantial number of people on both lists are perfectly happy to 
speak their mind, to the extent that Guido has been known to do u-turns. 
 Nobody has any need to lick anybody's boots, and to suggest that this 
is the case I find highly insulting to the entire Python community.




So if you cannot provide me with respect that i *DESERVE* as
a member of this fine community, then you should at least
admit that my presence is a vital counterbalance to prevent
this tiny life-vessel from capsizing as it's thrashed around
the treacherous "seas of evolution".



You (singular) have to *EARN* respect, you do not deserve it.  If you 
were to stick to subjects that you have knowledge of, such as 
tkinter/IDLE, you would earn that respect.  Serving up dross as you do 
so often gets you nothing except plonks.


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

Mark Lawrence

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


Hello World in Python

2015-01-24 Thread Christopher J. Pisz
I am trying to help a buddy out. I am a C++ on Windows guy. This buddy 
of mine is learning Python at work on a Mac. I figured I could 
contribute with non language specific questions and such.


When learning any new language, I said, the first step would be a Hello 
World program. Let's see if we can get that to work.


So my buddy creates opens the IDE they gave at the workplace, creates a 
new project, adds a demo.py file, writes one line : print "Hello World", 
hits Run in the IDE and indeed the display is shown at the bottom when 
it executes.


I say the next step would be to get that to run on the command line. So 
(keep in mind I know nothing about macs) my buddy opens a "zsh?" window, 
cd to the directory, and I say the command i most likely: python demo.py


It looks like it executes but there is no output to the command line window.

Can anyone explain why there is no output?
Can anyone recommend a good walkthrough of getting set up and doing basics?

It seems they jumped ahead at my buddy's workplace and want them to 
write a complicated script called by a "harness". I can only assume this 
harness is some compiled executable that takes python scripts as 
arguments and calls certain functions defined within them.


I'll probably end up learning python myself, just to help out. I hate to 
see someone making an effort to learn and not having the resources.

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


Re: Delegation in Python

2015-01-24 Thread Mark Lawrence

On 24/01/2015 23:41, Gary Herron wrote:

On 01/24/2015 03:22 PM, Chris Angelico wrote:

On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman  wrote:

But I am not clear on how to delegate from my new class to the existing
Fraction class.  This is what I have:

--
class RF(Fraction):

   def __new__(self, x, y):
 super().__new__(self, x, y)

   def is_integer(self):
 return self.numerator % self.denominator == 0

   def __getattr__(self, attr):
 return getattr(self, attr)

If you just drop everything but your new method, it should work just
fine.

class RF(Fraction):
 def is_integer(self):
return self.numerator % self.denominator == 0

However, this doesn't ensure that operations on RFs will return more
RFs - they'll often return Fractions instead. There's no easy fix for
that, sorry.

ChrisA


You can always "monkey-path" the Fraction class on the fly to add a new
method to it.  I think most would consider this a bad idea, but it does
work.
Try this:

 >>> from fractions import Fraction
 >>> def is_integer(self):
... return self.numerator % self.denominator == 0
...
 >>> Fraction.is_integer = is_integer # Monkey-patch Fraction
 >>>
 >>> Fraction(1,2).is_integer()
False
 >>> Fraction(2,1).is_integer()
True


Gary Herron



As regards this being a bad idea I'd suggest the latest score is 
Practicality 1 Purity 0 :)


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

Mark Lawrence

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


Re: Delegation in Python

2015-01-24 Thread Brian Gladman
On 24/01/2015 23:47, Gary Herron wrote:
> On 01/24/2015 03:38 PM, Brian Gladman wrote:
>> On 24/01/2015 23:22, Chris Angelico wrote:
>>> class RF(Fraction):
>>>  def is_integer(self):
>>> return self.numerator % self.denominator == 0
>> Thanks for your help on this.  I must admit that nowhere in a lot of
>> searching did I find that delegation is achieved by doing nothing!
>>
>> Brian
> 
> That's *not* "doing nothing".   And it's not even really "delegation". 
> It's just sub-classing Fraction to add one new method and inherit all
> other methods.

I realised that - I was being whimsical.

I really did want true delgation so that I get an RF returned even when
I delegate to Fractions.

   Brian

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


Re: Hello World in Python

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 10:53 AM, Christopher J. Pisz
 wrote:
> So my buddy creates opens the IDE they gave at the workplace, creates a new
> project, adds a demo.py file, writes one line : print "Hello World", hits
> Run in the IDE and indeed the display is shown at the bottom when it
> executes.
>
> I say the next step would be to get that to run on the command line. So
> (keep in mind I know nothing about macs) my buddy opens a "zsh?" window, cd
> to the directory, and I say the command i most likely: python demo.py
>
> It looks like it executes but there is no output to the command line window.
>
> Can anyone explain why there is no output?
> Can anyone recommend a good walkthrough of getting set up and doing basics?

Your broad methodology is fine! I'd normally expect that to work
correctly. Was the file properly saved? Ask him to display the file
(cat demo.py) to make sure it's what he thinks. Or maybe he's in a
different directory to the one he thinks he's in; again, catting the
file will help. Otherwise, it might be a weird problem with his shell,
but that's hard to diagnose.

One thing that I really like doing with my Python students (full
disclosure: I'm a mentor with www.thinkful.com and am thus at times
paid to help people learn Python) is some form of screen-sharing, so I
can watch him/her trying things. There are a number of zero-dollar
ways to do this, and it helps enormously. Flip on screen-share, ask
him to run the script, and see where that leads.

Good luck!

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


Re: Delegation in Python

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 10:59 AM, Mark Lawrence  wrote:
>> You can always "monkey-path" the Fraction class on the fly to add a new
>> method to it.  I think most would consider this a bad idea, but it does
>> work.
>
> As regards this being a bad idea I'd suggest the latest score is
> Practicality 1 Purity 0 :)

Indeed. But there's a huge difference between simple and complex
projects. I had a bit of a nightmare trying to figure out what was
going on with a project's logging... it looked like the Python logging
module, but there was another argument being processed, courtesy of
some monkey-patching. Try to keep these changes to small projects,
where it's easier to keep everything in your head; or for a temporary
bit of debugging, where you just want to do this temporarily and then
undo it again when you find the bug. Otherwise, it gets confusing for
the subsequent reader.

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


Python simple Code

2015-01-24 Thread Salem Alqahtani
Hi Guys,

I just joined the group and I hope that I can help and be active.

I have a question about python. I wrote a code on python 2.7 and I want to 
choose from the list of names that I provide n!. I execute the code but the 
result or output is the numbers. I want the people names are the result.


Sincerely

import sys
import array
a=['salem','Ali','sultan']
m = len(a)
def Factorials(m):
if m == 0:
return 1
else:
print m
return m * Factorials(m-1)
def output():
print a
def main():
print Factorials(m)
output()
main()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Delegation in Python

2015-01-24 Thread Brian Gladman
On 24/01/2015 23:43, Chris Angelico wrote:
> On Sun, Jan 25, 2015 at 10:38 AM, Brian Gladman  wrote:
>> On 24/01/2015 23:22, Chris Angelico wrote:
>>> class RF(Fraction):
>>> def is_integer(self):
>>>return self.numerator % self.denominator == 0
>>
>> Thanks for your help on this.  I must admit that nowhere in a lot of
>> searching did I find that delegation is achieved by doing nothing!
> 
> Hehe :) If you want a technical look at it, what you have is the
> fundamental nature of subclassing: you derive from another class, and
> your class is identical to that with certain exceptions (in your case,
> an additional method). Python's way of handling that is called the
> Method Resolution Order or MRO, and you can find info on it on the
> web, eg:
> 
> http://python-history.blogspot.com/2010/06/method-resolution-order.html

Thanks for the further background.

Is there a way of doing delegation rather than sub-classing?

That is, can I create a class (say RF) that passes some of its methods
to Fraction for implementation but always returns an RF?

   Brian

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


Re: Delegation in Python

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 11:18 AM, Brian Gladman  wrote:
> Is there a way of doing delegation rather than sub-classing?
>
> That is, can I create a class (say RF) that passes some of its methods
> to Fraction for implementation but always returns an RF?

Hmm. The key here is that you want more than just delegation; you want
to transform every return value. That's not going to be easy. It would
be easiest and cleanest to skip the whole thing, and have a separate
function for what you're doing here - not a method, a stand-alone
function.

def is_integer(fr):
return fr.numerator % fr.denominator == 0

Next best would be the monkey-patching option. Delegation with
transformation is a lot of effort for what you want.

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


Re: Python simple Code

2015-01-24 Thread Denis McMahon
On Sat, 24 Jan 2015 16:16:16 -0800, Salem Alqahtani wrote:

> import sys
> import array

> a=['salem','Ali','sultan']
> m = len(a)

> def Factorials(m):
> if m == 0:
> return 1
> else:
> print m
> return m * Factorials(m-1)

> def output():
> print a

> def main():
> print Factorials(m)
> output()

> main()

When I run the program, the output is:

3
2
1
6
['salem', 'Ali', 'sultan']

I'm not sure which output you think is wrong, or is not doing what you 
expect.

Observations:

a) There is no need to import array, you are only using a list.
b) If you try and index into a list using a number greater than the list 
length, you will receive an error "IndexError: list index out of range", 
hence if you have a list where len(list) is x items you will never be 
able to use x! as an index to the list.
c) To refer to a single member of a list, use list[n] where n is the zero 
indexed element you wish to refer to.
d) Note point b. l[len(l)!] (or l[Factorials(len(l))]) will always fail.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Terry Reedy

On 1/24/2015 4:51 PM, Marco Buttu wrote:

On 24/01/2015 20:24, Terry Reedy wrote:


On 1/24/2015 5:16 AM, Mario Figueiredo wrote:


Consider the following code at your REPL of choice



class Sub:
pass

foo = Sub()

Sub.__bases__
foo.__bases__

The last statement originates the following error:


This is an anomalous situation.


'This situation' being that Someclass.attro works but Someclass().attro 
raises.


  Normally, if a class has an attribute,

In other words, if 'Someclass.attro' evaluates to an object


instances have the same attribute


then 'Someclass().attro' *normally* evaluates to the same object


(unless overriden).


(unless 'Someclass().attro' has been bound to a different object)
because attribute lookup on an instance reverts to attribute lookup on 
the class and even its super classes (__bases__).  Someclass.__bases__ 
is special; it is not listed by dir(Someclass), and it is not accessible 
via an instance.



That is not true:


What I said, as I meant it to be understood, is true.

--
Terry Jan Reedy

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Rick Johnson
On Saturday, January 24, 2015 at 5:56:02 PM UTC-6, Mark Lawrence wrote:
> For at least the third time the PEP was written by three
> people, one of whom was the BDFL.  Why do you keep
> insisting that "he" is wrong, surely it should be "they" ?

TWO REASONS:

  (1) I don't know either of those people. And they have
  never attempted to contact me, or even participate in
  discussions on this list.
  
  BUT MORE IMPORTANTLY:
  
  (2) Final decisions for additions to Python are via GvR.
  Why should i waste my time "appealing for sanity" to
  numerous people, when i can focus my attention on the only
  one that matters? 

But why must Guido be sheltered from dissent? With power 
comes responsibility!
  
> A substantial number of people on both lists are perfectly
> happy to speak their mind, to the extent that Guido has
> been known to do u-turns. Nobody has any need to lick
> anybody's boots, and to suggest that this is the case I
> find highly insulting to the entire Python community.

Enough with the spin-doctoring of my words, only boot
lickers would be offended by what i said, and that is the
whole point of saying it! Do you think boot lickers are a
valuable resource of this (or any) community? Or could it 
be that you just cannot accept an inconvenient truth.

> You (singular) have to *EARN* respect, you do not deserve
> it.  If you were to stick to subjects that you have
> knowledge of, such as tkinter/IDLE, 

Oh i see. I'm allowed to participate so long as i don't step
on YOUR toes or offend YOUR delicate sensibilities? So long
as i volunteer to be locked in YOUR little rat cage, and do
exactly what YOU say. Sorry Mark, but YOUR secret
aspirations for tyrannical rule are not going to be
"entertained" by THIS community.

This character assassination of me has to stop, and your one
of the prolific assassins on this list. Show me one time
that i have *EVER* intentionally misled a noob on this
list? You may find a sample where i've made an honest
mistake, or mis-comprehended a question, but don't you
*DARE* question my morals! 

I am one of the most honest and trustworthy people in this
community. You may find my style to be annoying, (that is
your opinion), but you have no right (and no evidence) to
question my integrity.

You can call me any name in the book you want; you can curse
me; you can ridicule me; and all of it i can ignore; but i
will NOT allow you to paint me as dishonest. I hold honesty
as the most important of *ALL* virtues. 

You owe me an apology for slandering my integrity! 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hello World in Python

2015-01-24 Thread Terry Reedy

On 1/24/2015 6:53 PM, Christopher J. Pisz wrote:

I am trying to help a buddy out. I am a C++ on Windows guy. This buddy
of mine is learning Python at work on a Mac. I figured I could
contribute with non language specific questions and such.

When learning any new language, I said, the first step would be a Hello
World program. Let's see if we can get that to work.

So my buddy creates opens the IDE they gave at the workplace, creates a
new project, adds a demo.py file, writes one line : print "Hello World",
hits Run in the IDE and indeed the display is shown at the bottom when
it executes.

I say the next step would be to get that to run on the command line. So
(keep in mind I know nothing about macs) my buddy opens a "zsh?" window,
cd to the directory, and I say the command i most likely: python demo.py

It looks like it executes but there is no output to the command line
window.


It should.  In a Windows console, using 3.4:
C:\Programs\Python34>type tem.py  # cat on Mac?
print('Hello World!')

C:\Programs\Python34>python tem.py
Hello World!

> Can anyone explain why there is no output?

Without a copy of the file and command, as above, no.

> Can anyone recommend a good walkthrough of getting set up and doing 
basics?


Since you used 2.x  print syntax: https://docs.python.org/2.7/

"Python Setup and Usage
how to use Python on different platforms"

"Tutorial
start here"

> I'll probably end up learning python myself, just to help out.

You might possibly enjoy Python as a complement to C++.  Some people 
prototype in Python and rewrite time critical functions in C++.  One can 
access .dlls either directly (via the ctypes module) and write a wrapper 
file in C or C++.  I believe Python has also been used to write tests 
for C++ functions (I know this is true for Python and Java, via Jython).


--
Terry Jan Reedy

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


Re: Python simple Code

2015-01-24 Thread Terry Reedy

On 1/24/2015 7:16 PM, Salem Alqahtani wrote:

Hi Guys,

I just joined the group and I hope that I can help and be active.

I have a question about python. I wrote a code on python 2.7 and I want to 
choose from the list of names that I provide n!. I execute the code but the 
result or output is the numbers. I want the people names are the result.


Sincerely

import sys
import array
a=['salem','Ali','sultan']
m = len(a)
def Factorials(m):
 if m == 0:
 return 1
 else:
 print m
 return m * Factorials(m-1)
def output():
 print a
def main():
 print Factorials(m)
 output()
main()


When I copy, paste, and run this in Idle editor, I get the expected
>>>
3
2
1
6
['salem', 'Ali', 'sultan']

--
Terry Jan Reedy

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


Re: Delegation in Python

2015-01-24 Thread Terry Reedy

On 1/24/2015 5:57 PM, Brian Gladman wrote:

I would appreciate advice on how to set up delgation in Python.

I am continuously implementing a function to test whether a Python
Fraction is an integer


Since Fractions are reduced to lowest terms,
>>> from fractions import Fraction as F
>>> F(4, 2)
Fraction(2, 1)
>>> F(12, 3)
Fraction(4, 1)

the test is that the denominator is 1

>>> F(12,3).denominator == 1
True
>>> F(12,5).denominator == 1
False

it may not be worth the bother to define a function,

def fint(F): return F.denominator == 1


so I wanted to define a new class, based on
Fraction, that includes this new method.


but if you do, there is little need to make it a method.  You are not 
overriding an existing method or adding a new special method.  The math 
module has float and int functions that have *not* been turned into 
methods.  Ditto for cmath.  I would just leave the function a function. 
 Python is not Java.


--
Terry Jan Reedy

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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Ethan Furman
On 01/24/2015 11:55 AM, Chris Angelico wrote:
> On Sun, Jan 25, 2015 at 5:56 AM, Ethan Furman  wrote:
>> If the non-generic is what you're concerned about:
>>
>> # not tested
>> dispatch_table_a = {}
>> dispatch_table_b = {}
>> dispatch_table_c = {}
>>
>> class dispatch:
>>   def __init__(self, dispatch_table):
>> self.dispatch = dispatch_table
>>   def __call__(self, func):
>> self.dispatch[func.__name__] = func
>> return func
>>
>> @dispatch(dispatch_table_a)
>> def foo(...):
>>pass
> 
> That's still only able to assign to a key of a dictionary, using the
> function name. 

This is a Good Thing.  The def statement populates a few items, __name__ being 
one of them.  One of the reasons lambda
is not encouraged is because its name is always '', which just ain't 
helpful when the smelly becomes air borne!  ;)

--
~Ethan~



signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Benchmarking some modules - strange result

2015-01-24 Thread Dan Stromberg
Hi folks.

I've been benchmarking some python modules that are mostly variations
on the same theme.

For simplicity, let's say I've been running the suite of performance
tests within a single interpreter - so I test one module thoroughly,
then move on to the next without exiting the interpreter.

I'm finding that if I prune the list of modules down to just the best
performers, I get pretty different results - what was best no longer
is.  This strikes me as strange.

I'm forcing a garbage collection between tests with gc.collect(), but
even that yields the oddball results.

Is there something else I should do to restore the interpreter to a
known-pristine state for the sake of such tests?

BTW, there isn't much else going on on this computer, except some
possible small cronjobs.

I'm about ready to rewrite things to run each individual test in a
fresh interpreter. But is there a better way?

If I do the rewrite, I might run 1 run of module A, 1 run of module B,
1 run of module C, then another run of module A, another run of module
B, and another run of module C - to spread any possible timing
oddities more evenly.

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


Re: Benchmarking some modules - strange result

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 1:11 PM, Dan Stromberg  wrote:
> For simplicity, let's say I've been running the suite of performance
> tests within a single interpreter - so I test one module thoroughly,
> then move on to the next without exiting the interpreter.
> [chomp more details]

Do the modules import stuff that's staying imported? That could
majorly affect performance. What about .pyc files?

I don't know if you can truly reset the interpreter. Snapshotting
sys.modules and reinstating it afterwards would help, but there are
other concerns too. I would personally just restart the interpreter
each time, frankly; it's the easiest way to be sure.

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Steven D'Aprano
Tim Chase wrote:

> On 2015-01-25 04:31, Steven D'Aprano wrote:
>> Of course we don't have $1/3 dollar coins, but I do have a pair of
>> tin-snips and can easily cut a $1 coin into three equal pieces.
> 
> I'm impressed that you can use tin-snips to cut it into exactly three
> equal pieces with greater precision than the floating point numbers
> that you're cautioning against in Python.  I believe at that point,
> you're talking about at least the sub-sub-sub-atomic scale. :-)

They're really good quality tin-snips.



-- 
Steven

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


Re: Python is DOOMED! Again!

2015-01-24 Thread Mark Lawrence

On 25/01/2015 01:00, Rick Johnson wrote:

On Saturday, January 24, 2015 at 5:56:02 PM UTC-6, Mark Lawrence wrote:

For at least the third time the PEP was written by three
people, one of whom was the BDFL.  Why do you keep
insisting that "he" is wrong, surely it should be "they" ?


TWO REASONS:

   (1) I don't know either of those people. And they have
   never attempted to contact me, or even participate in
   discussions on this list.

   BUT MORE IMPORTANTLY:

   (2) Final decisions for additions to Python are via GvR.
   Why should i waste my time "appealing for sanity" to
   numerous people, when i can focus my attention on the only
   one that matters?

But why must Guido be sheltered from dissent? With power
comes responsibility!


A substantial number of people on both lists are perfectly
happy to speak their mind, to the extent that Guido has
been known to do u-turns. Nobody has any need to lick
anybody's boots, and to suggest that this is the case I
find highly insulting to the entire Python community.


Enough with the spin-doctoring of my words, only boot
lickers would be offended by what i said, and that is the
whole point of saying it! Do you think boot lickers are a
valuable resource of this (or any) community? Or could it
be that you just cannot accept an inconvenient truth.


You (singular) have to *EARN* respect, you do not deserve
it.  If you were to stick to subjects that you have
knowledge of, such as tkinter/IDLE,


Oh i see. I'm allowed to participate so long as i don't step
on YOUR toes or offend YOUR delicate sensibilities? So long
as i volunteer to be locked in YOUR little rat cage, and do
exactly what YOU say. Sorry Mark, but YOUR secret
aspirations for tyrannical rule are not going to be
"entertained" by THIS community.

This character assassination of me has to stop, and your one
of the prolific assassins on this list. Show me one time
that i have *EVER* intentionally misled a noob on this
list? You may find a sample where i've made an honest
mistake, or mis-comprehended a question, but don't you
*DARE* question my morals!

I am one of the most honest and trustworthy people in this
community. You may find my style to be annoying, (that is
your opinion), but you have no right (and no evidence) to
question my integrity.

You can call me any name in the book you want; you can curse
me; you can ridicule me; and all of it i can ignore; but i
will NOT allow you to paint me as dishonest. I hold honesty
as the most important of *ALL* virtues.

You owe me an apology for slandering my integrity!



You are now getting what I should have done some time ago as my patience 
with you has run out.


*plonk*

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

Mark Lawrence

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


Re: Alternative to multi-line lambdas: Assign-anywhere def statements

2015-01-24 Thread Yawar Amin
Hi Ethan,

On Saturday, January 24, 2015 at 9:00:12 PM UTC-5, Ethan Furman wrote:
> [...]
> __name__ being one of them.  One of the reasons lambda
> is not encouraged is because its name is always '', which just
> ain't helpful when the smelly becomes air borne!  ;)

Doesn't the traceback tell us exactly where the lambda was called from?

Regards,

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


Re: Benchmarking some modules - strange result

2015-01-24 Thread Dan Stromberg
On Sat, Jan 24, 2015 at 6:24 PM, Chris Angelico  wrote:
> On Sun, Jan 25, 2015 at 1:11 PM, Dan Stromberg  wrote:
>> For simplicity, let's say I've been running the suite of performance
>> tests within a single interpreter - so I test one module thoroughly,
>> then move on to the next without exiting the interpreter.
>> [chomp more details]
>
> Do the modules import stuff that's staying imported? That could
> majorly affect performance. What about .pyc files?

The modules are all imported up at the top of the script.  I haven't
verified this, but I'm guessing the .pyc's are created at the
beginning too.

> I don't know if you can truly reset the interpreter. Snapshotting
> sys.modules and reinstating it afterwards would help, but there are
> other concerns too. I would personally just restart the interpreter
> each time, frankly; it's the easiest way to be sure.

Maybe so ^_^
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Benchmarking some modules - strange result

2015-01-24 Thread Chris Angelico
On Sun, Jan 25, 2015 at 1:36 PM, Dan Stromberg  wrote:
> On Sat, Jan 24, 2015 at 6:24 PM, Chris Angelico  wrote:
>> On Sun, Jan 25, 2015 at 1:11 PM, Dan Stromberg  wrote:
>>> For simplicity, let's say I've been running the suite of performance
>>> tests within a single interpreter - so I test one module thoroughly,
>>> then move on to the next without exiting the interpreter.
>>> [chomp more details]
>>
>> Do the modules import stuff that's staying imported? That could
>> majorly affect performance. What about .pyc files?
>
> The modules are all imported up at the top of the script.  I haven't
> verified this, but I'm guessing the .pyc's are created at the
> beginning too.

Yeah, so it's probably not that. I should have known you'd have
covered the easy possibilities already :)

That's me out of ideas.

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


Re: apostrophe not considered with tkinter's wordstart and wordend

2015-01-24 Thread Rick Johnson
On Thursday, January 22, 2015 at 4:26:29 PM UTC-6, Christian Gollwitzer wrote:

> Well, it turns out you actually can. We don't have Guido's
> time machine, but still there is a configuration option in
> Tk, albeit a very obscure one: you have to set the global
> Tcl variables tcl_wordchars and tcl_nonwordchars after
> loading Tk to a regexp which defines the word boundaries:
> 
>   http://wiki.tcl.tk/1655
> 
> Strangely, there is a different preset for Windows and
> X11. The Windows preset - consider everything besides
> space as part of the word - makes more sense to me than
> the Unix default, which only counts letters, numbers and
> underscores as part of the word. To set the Windows
> preset, do this:
> 
> tk.eval('set tcl_wordchars {\S}');
> tk.eval('set tcl_nonwordchars {\s}');
> 
> (untested in Python, only tested directly from a wish shell)

Hmm. Thanks for posting this, but i could not get it to
work??? I tried all sorts of sensible patterns but
nothing works.

Below is a simple testing app with bindings which highlight the
word under the mouse like the OP requested. If you can modify
the word boundaries so that it captures the equivalent of this
pattern r"'\w+'", then i will write a wrapper method for the
Tkinter module for arbitrarily modifying the boundaries. 

Here is the code, happy hacking ;-)

## START CODE ##

import Tkinter as tk
from Tkconstants import YES, BOTH, END

SIDX = '1.0'
STR = """
My humble dictators,
ask not what the 'boot_lickers' can do for you,
ask what *YOU* can do to for *YOUR* community!
"""

class MyText(tk.Text):
def __init__(self, master, **kw):
tk.Text.__init__(self, master, **kw)
self.bind("", self.evtButtonOneDown)
self.tag_add('hit', END)
self.tag_config('hit', background='red')

def evtButtonOneDown(self, event):
sLC = self.index('current wordstart')
eLC = self.index('current wordend')
print 'hitspan from {0!r} to {1!r}'.format(sLC, eLC)
self.tag_remove('hit', SIDX, 'end')
self.tag_add('hit', sLC, eLC)

if __name__ == '__main__':
root = tk.Tk()
##root.eval("set tcl_wordchars {psst: over here!}")
##root.eval("set tcl_nonwordchars {psst: and here too!}")
et = MyText(root, undo=True)
et.insert(SIDX, STR)
et.pack(fill=BOTH, expand=YES)
root.mainloop()

## END CODE ##

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


Re: apostrophe not considered with tkinter's wordstart and wordend

2015-01-24 Thread ravas
We resolved it over at the comp.lang.tcl group.
It turns out what Christian suggested affects what is selected when you double 
click a word. He later discovered a different method for producing what I want.
Below is my test code that implements both of these things
(tested with Python 3.4 and PyCharm).

import tkinter
import tkinter.messagebox as messagebox

class Creator(object):

def __init__(self):

root = self.root = tkinter.Tk()
   
# Main Frame
f_main = tkinter.Frame(root, borderwidth=6, relief='flat')
f_main.grid(row=0, column=0, sticky='nsew')

# Text widget, its font and frame
f_txt = tkinter.Frame(f_main, borderwidth=2, relief="sunken")
f_txt.config(width=768, height=768)

f_txt.grid_propagate(False)  # ensures a consistent GUI size
f_txt.pack(padx=4, pady=4, side="bottom", fill="both", expand=True)

my_txt = tkinter.Text(f_txt, name='t')
my_txt.config(undo=True, wrap='word')
my_txt.grid(row=0, column=0, sticky="nsew")
self.text = my_txt

# Scrollbar and config
f_scroll = tkinter.Frame(root, borderwidth=4, relief="groove")
f_scroll.grid(row=0, column=1, sticky='nsew')
scrollbar = tkinter.Scrollbar(f_scroll, command=my_txt.yview)
scrollbar.pack(side='left', fill='y', pady=2, padx=0, expand=True)

my_txt.config(yscrollcommand=scrollbar.set)
scrollbar.columnconfigure(0, weight=1)

# Stretchable
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
f_main.columnconfigure(0, weight=1)
f_main.rowconfigure(0, weight=1)
f_txt.rowconfigure(0, weight=1)
f_txt.columnconfigure(0, weight=1)

my_txt.bind("", self.test)
my_txt.focus_set()

def test(self, event=None):
txt = str(self.text)
a = "::tk::TextPrevPos {} current tcl_wordBreakBefore".format(txt)
b = "::tk::TextNextPos {} current tcl_wordBreakAfter".format(txt)
ind1 = self.root.tk.eval(a)
ind2 = self.root.tk.eval(b)
x = self.text.get(ind1, ind2)
messagebox.showinfo('info', x)

# ===
# start up
# ===

GUI = Creator()
GUI.root.tk.eval("catch {tcl_endOfWord}")
GUI.root.tk.eval("catch {tcl_startOfPreviousWord}")
GUI.root.tk.eval("set tcl_wordchars {[[:alnum:]']}")
GUI.root.tk.eval("set tcl_nonwordchars {[^[:alnum:]']}")
GUI.root.mainloop()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __bases__ misleading error message

2015-01-24 Thread Steven D'Aprano
Mario Figueiredo wrote:

> But that begs the OT question: How does Python maps names to memory
> addresses in the interpreter?

It doesn't.

You are thinking of an execution model like C or Pascal, where variables are
best thought of as fixed memory addresses. But Python, like many modern
languages (Java, Ruby, Lua, ...) uses a name-binding model.

Semantically, the fixed memory address model means that each variable is
like a fixed-width bucket, where the size depends on the type. That's why
the compiler needs to associate a fixed type with each variable, so it
knows how much space to allocate and how to initialise the bytes:

m = []
n = []
x = [8FFF]

Assigning a value to a variable ("m = 42", hex 2A) results in the compiler
storing that value in the bucket; assignment makes a copy: "n = m" leads to
two independent buckets with the same value:

m = [002A]
n = [002A]

Values and variables are dependent on each other. You can't have a variable
with no value, and you can't have a value with no variable. (This is an
over-simplification, but mostly true.)

The name-binding model is different. Values (objects) and names are
independent. Values can exist even if they have no name (although the
garbage collector will delete them as soon as they are unused). The
compiler associates a name to a value. One good mental model is to think of
the compiler attaching a piece of string from the name to its associated
object. Assigning n = m means that both names end up tied to the same
object, and there can be objects with no associated name. (So long as
*something* refers to them, the garbage collector will leave them be.)


m -+--- 0x2A
n /
x - 1.2345
s -\"Hello world"
+-- "Goodbye now"


Under the hood, this is usually implemented using pointers. If you are
familiar with pointer semantics, you might think of these pieces of string
as pointers, except that you cannot do pointer arithmetic on them. But that
is merely the *implementation* of the language's variable model.

In Python, global variables use a dict, and there is a function to retrieve
that dict:


py> d = globals()
py> d['x'] = 23  # don't do this!
py> x
23


It's not *wrong* or forbidden to write to globals this way. It's just
unnecessary.


> "__main__"
> from module import a_name
> y = a_name + 1
> 
> How does python interpreter know how to map 'name' to the correct memory
> location, if this __main__ code is only ran after 'module' code?

When the statement `from module import a_name` executes, Python:

(1) imports module;
(2) looks up "a_name" in module's namespace (a dict);
(3) creates an entry "a_name" in the current namespace (assuming 
one doesn't already exist);
(4) and binds it to the object found in Step 2.

When it executes `y = a_name + 1`, Python:

(1) looks up the name "a_name" in the current namespace;
(2) creates the anonymous object 1, unbound to any name;
(3) calls + with those two objects;
(4) which (assuming it succeeds) creates a new object;
(5) creates an entry "y" in the current namespace;
(6) and binds it to the object returned in Step 4.



-- 
Steven

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


Re: Benchmarking some modules - strange result

2015-01-24 Thread Dan Stromberg
On Sat, Jan 24, 2015 at 6:37 PM, Chris Angelico  wrote:
> On Sun, Jan 25, 2015 at 1:36 PM, Dan Stromberg  wrote:
>> On Sat, Jan 24, 2015 at 6:24 PM, Chris Angelico  wrote:
>>> On Sun, Jan 25, 2015 at 1:11 PM, Dan Stromberg  wrote:
 For simplicity, let's say I've been running the suite of performance
 tests within a single interpreter - so I test one module thoroughly,
 then move on to the next without exiting the interpreter.
 [chomp more details]
>>>
>>> Do the modules import stuff that's staying imported? That could
>>> majorly affect performance. What about .pyc files?
>>
>> The modules are all imported up at the top of the script.  I haven't
>> verified this, but I'm guessing the .pyc's are created at the
>> beginning too.
>
> Yeah, so it's probably not that. I should have known you'd have
> covered the easy possibilities already :)

No problem!  Thanks for helping me make sure I covered the easy stuff.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >