Re: Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

2016-07-02 Thread dieter
Ben Finney  writes:
> ...
> Rather, the motivation was that a complex thing, with many moving parts,
> has an unexplained implementation: a nested set of functions without
> names to explain their part in the pattern.

In a previous reply, I have tried to explain (apparently without success)
that the "thing" is not "complex" at all but a simple signature
transform for a decorator definitition and that the nested function
implementation is natural for this purpose.

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


Re: super and mix-in class: how exactly is the search order altered?

2016-07-02 Thread dieter
"Veek. M"  writes:
> ...
> I'm reading this article: 
> https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
>
> He's trying to explain the purpose of a 'mix-in class' and he says
>
> We did not alter the source code for LoggingDict. Instead we built a 
> subclass whose only logic is to compose two existing classes and control 
> their search order.
>
> class LoggingOD(LoggingDict, collections.OrderedDict):
> pass
>
> My question is this: in the above article context, is he talking about 
> the LoggingDict's search order that is being manipulated? Or he is 
> talking about manipulating the LoggingOD search order?

Likely, his language has been a bit sloppy.

Likely, his setup is as follows:

 * He has an existing class ("collections.OrderDict")
   which the base functionality he needs

 * He has an additional requirement (over that of "collections.OrderDict")
   -- logging modifications

 * He wants to implement his requirements (the base ones and the
   the additional one) without modifying the existing class in any way

 * His idea to implement the additional requirement is to define
   a derived class ("LoggingOD") and lets its modifying methods perform
   the logging and then call the corresponding methods of the
   base class.

 * He recognizes that this logging feature might be interesting
   not only for "collections.OrderDict" but also for other
   dictionary like base classes.
   Therefore, instead of implementing it directly in
   "LoggingOD", he implements it in the mixin class "LoggingDict".

 * Because "LoggingDict" was explicitely designed to be used
   as mixin class to enhance a base class, it knows that
   some methods ("__setitem__") of the base class need to be called
   in its own implementation of the corresponding method.

 * The integrator (the one combining "LoggingDict" with the base
   class) must ensure (by an appropriate inheritance order)
   that the combining class ("LoggingOD" in the example)
   calls the "LoggingDict"'s methods (which know about that of the
   base class) rather than the base class's methods (which do not
   know about the mixin class's methods).

   Therefore, he uses the inheritance order "LoggingDict" followed
   by the base class (and not vice versa).


Python clearly defines in what order attributes of an object
and of the construct "super(,)" are looked up.

The essential concept is the so called "MRO" ("method resolution order")
(in fact, it is an attribute resolution order).

In simple cases (no common base classes), the MRO of
a definition "class C(B_1, ..., B_n): ..."
is defined by a left to right lookup: i.e. first in "C", then "B_1",
then "B_2", ...

The rules are a bit more complicated when the "B_i" have a (or more)
common base classes.

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


Re: JAR files into python

2016-07-02 Thread dieter
Joaquin Alzola  writes:
> ...
> The error that it throws is the following one (which is logical because I do 
> not load the jar files):
> py4j.protocol.Py4JJavaError: An error occurred while calling o29.load.
> : java.lang.ClassNotFoundException: Failed to find data source: 
> org.apache.spark.sql.cassandra. Please find packages at 
> http://spark-packages.org
>
> Is there a way to load those jar files into python or the classpath when 
> calling sqlContext.read.format("org.apache.spark.sql.cassandra")?

Apparently, you are using a Python-Java bridge (looks like "pyspark"
is such a thing). I expect that such a bridge provides
ways to make JAR files known to the activated Java runtime.
Consult its documentation.

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


Re: Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

2016-07-02 Thread Ben Finney
dieter  writes:

> Ben Finney  writes:
> > ... Rather, the motivation was that a complex thing, with many
> > moving parts, has an unexplained implementation: a nested set of
> > functions without names to explain their part in the pattern.
>
> In a previous reply, I have tried to explain (apparently without
> success) that the "thing" is not "complex" at all

Your explanation was clear. I disagree with it; the code is not at all
obvious in its intention or operation.

Naming the parts descriptively, and writing a brief synopsis docstring
for each function, is a way to address that. Which is my motivation for
this thread.

> but a simple signature transform for a decorator definitition

You're making my case for me: To anyone who doesn't already know exactly
what's going on, that is not at all obvious from the code as presented
in the first message.

> and that the nested function implementation is natural for this
> purpose.

The nested function implementation is not the problem, as I hope I've
made clear elsewhere in this thread.

-- 
 \ “People's Front To Reunite Gondwanaland: Stop the Laurasian |
  `\  Separatist Movement!” —wiredog, http://kuro5hin.org/ |
_o__)  |
Ben Finney

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


Re: Descriptor: class name precedence over instance name

2016-07-02 Thread Veek. M
Ben Finney wrote:

> "Veek. M"  writes:
> 
>> Trying to make sense of this para:
> 
> At the risk of being ruse, I am trying to make sense of some
> paragraphs in the messages you write here. Could you take a little
> more time to write clearly, as a way of communicating in this forum?
> 
>> Is he say that Descriptors are a special case where Foo is checked
>> first, then what - Base classes..? or does he hop back to look in the
>> instance? How is C3 Linearization altered?
> 
> I really have no idea what this paragraph means. Can you please write
> again assuming we don't know already what you are trying to say?
> 

Sorry about that, I found it hard to read too (when I came back to it). 

I was trying to figure out the order in which attributes are looked up. 
Beazley's a great book, but sometimes he kills me and mounts my head on 
a pike - page 127 - Descriptors section, last para.

He says that descriptor-attribute-names in a class, take precedence in a 
attribute lookup wrt instance attributes.

When you do an x.a, python goes on a hunt for 'a' - the whole binding 
idea; typically, that is, Instance Name Space -> Class NS -> BaseClasses
(C3 Linearization algorithm)

Therefore, I was wondering how he could start the search at the 
instance-Class, instead of the instance. When you print __mro__ you get 
a list of classes that are traversed but there's no explicit mention 
within the __mro__ that the instance is searched first. So I wanted to 
know if there was any implications to C3/__mro__

So essentially from what Ian said:
data_descriptor_in_instance -> instance_attribute -> non-
data_descriptor_in_instance -->__mro__

is how the search takes place. Correct?
--

Regarding part2 of the Q, :) Ian hasn't explained it, so I'm not sure 
how to explain it better :) but i'll try given that he has clarified 
part of the answer.

Basically Beazley has a TypedProperty descriptor class, and in class Foo
he instantiates:
 name = TypedProperty
Then he does f = Foo()

Thanks to Ian, we now know that any lookup on 'f' eg: f.name would 
cause.. well.. the f.name(TypedProperty-descriptor) to gain precedence 
thus hiding the f.name attribute! Therefore he needs to name-decorate or 
in this example append an '_' for whatever stupid reason.

I think i've got the jist down pat so :p
Here's the image:
http://storage1.static.itmages.com/i/16/0702/h_1467451175_7972040_b5037f6b46.png

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


Re: Getting back into PyQt and not loving it.

2016-07-02 Thread Sibylle Koczian

Am 27.06.2016 um 22:14 schrieb codewiz...@gmail.com:

On Sunday, June 26, 2016 at 5:45:18 PM UTC-4, Michael Torrie wrote:


Qt's a fantastic toolkit, and the most mature of any of them, and the
most portable, but man the bindings are not Pythonic at all.


Enaml feels pretty Pythonic to me:

https://github.com/nucleic/enaml


But:

Enaml is a Python framework and requires a supported Python runtime. 
Enaml currently supports Python 2.6 and Python 2.7. Python 3.x support 
may be added in the future, but is not currently a high priority item.


http://nucleic.github.io/enaml/docs/get_started/installation.html



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


Re: Lost in descriptor land

2016-07-02 Thread Ankush Thakur
On Friday, July 1, 2016 at 7:07:09 AM UTC+5:30, Ian wrote:

> First of all, do you understand what descriptors are? This is a fairly
> advanced Python concept. For a general tutorial, I would point you to
> https://docs.python.org/3/howto/descriptor.html

I understand what descriptors try to accomplish, but that link is pretty scary! 
:P I found your explanation to be much better. The other tutorials would simply 
ignore "owner", offer no explanation, and provide complete working programs -- 
this made me go crazy!
 

> The owner argument is the class that this Celsius instance is a
> descriptor of. Normally that is just type(instance); however it is
> possible to invoke the __get__ method on the class object itself
> rather than on an instance, in which case owner is (still) the class
> object but instance is None.

This is the golden explanation I will always be thankful for! :)

> It's not clear to me what alternative you're proposing. The reason
> celsius is declared on the class is because it's a descriptor, and
> descriptors implement properties of classes. Setting an instance
> attribute to a descriptor won't accomplish anything.

The alternative I'm proposing is indeed what you said: Make `celcius` a 
per-object attribute and set it up in __init__(). Why will it not accomplish 
the same thing as setting it on a class-level? Please bear with me a little 
more and explain. :P 

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


Re: Lost in descriptor land

2016-07-02 Thread Ankush Thakur
On Friday, July 1, 2016 at 9:03:44 AM UTC+5:30, Lawrence D’Oliveiro wrote:
> Every time I feel unsure, I go back to the horse’s mouth: here 
> 
>  is GvR himself with all the details on “new-style” classes, including the 
> clearest explanation I have come across about descriptors.

Well, that's certainly a very interesting link (and blog!) but my current 
priority is to just understand this damn thing! :D

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


Re: Lost in descriptor land

2016-07-02 Thread Ankush Thakur
On Friday, July 1, 2016 at 9:13:19 AM UTC+5:30, Lawrence D’Oliveiro wrote:
> 
> > Shouldn't we be instead using self.celcius in, say, __init__() and then
> > everything will work fine?
> 
> I guess it might. But this way, using descriptors, all the setup is done once 
> at class definition, rather then every time in class instantiation.

So you're saying the (sole) reason to instantiate descriptor classes at 
class-level is performance?

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


[ANN] aioxmpp 0.6 released

2016-07-02 Thread Jonas Wielicki
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA512

Dear subscribers,

I am pleased to announce the release of aioxmpp 0.6. The current release can 
be obtained from GitHub [1] (check out the v0.6.0 tag or the master branch) or 
PyPI [2]. The HTML documentation can be found at [3]. Examples can be found in 
the GitHub repository, in the examples subdirectory.


aioxmpp is a Python library based on asyncio. It implements the client side of 
the XMPP protocol (RFC 6120 and others). For a more detailed description of 
the package, please review the README of the package on GitHub [1] or on PyPI 
[2]. For more information on XMPP, please see [10]. It is licensed under the 
terms of the General Public License Version 3.0.


Highlights of this release include partial Publish/Subscribe support 
[XEP-0060], several bugfixes in the existing Multi-User-Chat implementation 
[XEP-0045], increased robustness against broken servers and clients, as well 
as support for XMPP-over-TLS (in addition to the existing STARTTLS support) 
[XEP-0368].

Also to mention are the two new dependencies, multidict [4] and optionally 
aioopenssl [5]. The latter has been extracted from aioxmpp by request of a 
user. aioxmpp however ships with its own version of aioopenssl which it uses 
when aioopenssl is not installed.

Bugs, feature requests, patches and questions can be directed to either the 
aioxmpp mailing list [6], the GitHub issue tracker [7] or the XMPP Multi-User 
chat [8], whatever floats your boat. Please direct security-relevant issue 
reports directly to me (jo...@wielicki.name), preferrably encrypted using my 
GPG public key [9].

best regards and happy-asyncio-ing,
Jonas Wielicki


   [1]: https://github.com/horazont/aioxmpp
   [2]: https://pypi.python.org/pypi/aioxmpp
   [3]: https://docs.zombofant.net/aioxmpp/0.6/
   [4]: https://github.com/aio-libs/multidict/
   [5]: https://github.com/horazont/aioopenssl
   [6]: https://lists.zombofant.net/mailman/listinfo/aioxmpp-devel
   [7]: https://github.com/horazont/aioxmpp/issues
   [8]: aiox...@conference.zombofant.net
   [9]: https://sks-keyservers.net/pks/lookup?op=get&search=0xE5EDE5AC679E300F
AA5A 78FF 508D 8CF4 F355  F682 E5ED E5AC 679E 300F
   [10]: https://xmpp.org/
   [XEP-0045]: https://xmpp.org/extensions/xep-0045.html
   [XEP-0060]: https://xmpp.org/extensions/xep-0060.html
   [XEP-0368]: https://xmpp.org/extensions/xep-0368.html
-BEGIN PGP SIGNATURE-
Version: GnuPG v2

iQIcBAEBCgAGBQJXd8TbAAoJEMBiAyWXYliKUnoP/0mEvfNrk+kL9scljIKyjSHF
47gkQBgvNMPAEUMSi5UVMkXworeVDKEpCB+P3kE4Z7XsRLxFgFSUGywYN7WL0w/s
rpiUnJrOzPrsKiqmPTu2eOGDeuKNCz/ZSZqyl1Ic8Mj42cS9DjGh+PUwEpWBnskS
Dg4onj4clWpDsZGizR8YXkFkc8rmsUhHwvqQt29tOZ89qQnmOY4pCKyoTbxYLQKv
UerfiNG4AWFFuyetZJFUORdVhWEgFvivqJuES5g7NijgRmEOZV8tcYj0YAtggEP0
GQX5mE/KqHzHErR1/AAVnv2hXlqBBxc3diSXT6k+95wLkXz0n2YmPFCFPSl235Ru
uiUiW0xbQqJgjJ+B20NsuIMd+t1M/lnDw4cZgLkMUCsl6gsZEhL0mUf5iK9UDCH9
HbXsoMuz71t+Z8XN8GnibxDFPvCBERNqvIU+onjt63rT/yB/i/7XTbS4zQExCGhF
z4qVF8dY2q+d4EsIvd1dxLkP7dRFW7VK1FxiuutS5OTNEBsocROaXPDOjRyzdXGx
mSH3P/IuXxEil9kKHkXNZRQwSgl6J4PvAeySn58d3bpmHi8hu2J83ZoeFLdxHMoe
qOhkBB/v4QRbEgjXIqF8OmtGtNO9hXlM7EN6ouc9pvCJ1XGnBU9Z9FX4AkQMQUu/
AfDKZ8VFptxvQh1dtCD1
=ir6C
-END PGP SIGNATURE-

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


Re: Descriptor: class name precedence over instance name

2016-07-02 Thread Ian Kelly
On Sat, Jul 2, 2016 at 3:34 AM, Veek. M  wrote:
> So essentially from what Ian said:
> data_descriptor_in_instance -> instance_attribute -> non-
> data_descriptor_in_instance -->__mro__
>
> is how the search takes place. Correct?

Close, but I would write it as:
data_descriptor_in_class_including_mro -> instance_attribute ->
non_data_descriptor_or_class_attribute_including_mro

In either case the class dict search is in __mro__ order. You can find
the actual implementation here:

https://hg.python.org/cpython/file/30099abdb3a4/Objects/object.c#l1326

Roughly, the algorithm is this:

tp = type(obj)

# This call searches the MRO.
descr = _PyType_Lookup(tp, name)

if descr != NULL and is_data_descriptor(descr):
return descr.__get__(obj, tp)

if name in obj.__dict__:
return obj.__dict__[name]

if descr != NULL and is_non_data_descriptor(descr):
return descr.__get__(obj, tp)

if descr != NULL:
return descr

raise AttributeError(name)

> --
>
> Regarding part2 of the Q, :) Ian hasn't explained it, so I'm not sure
> how to explain it better :) but i'll try given that he has clarified
> part of the answer.
>
> Basically Beazley has a TypedProperty descriptor class, and in class Foo
> he instantiates:
>  name = TypedProperty
> Then he does f = Foo()
>
> Thanks to Ian, we now know that any lookup on 'f' eg: f.name would

Not *any* lookup, only one for which there is a declared descriptor.
So in this example f.name or f.num would resolve according to the
descriptor's __get__ method, but any other attribute lookup would just
return whatever value is set on the instance (if any).

> cause.. well.. the f.name(TypedProperty-descriptor) to gain precedence
> thus hiding the f.name attribute! Therefore he needs to name-decorate or
> in this example append an '_' for whatever stupid reason.

Right, if the "name" descriptor tried to store the value in the
unmangled "name" instance attribute, then its getattr call would just
recur back to the descriptor and you'd have an infinite loop.

In my opinion the mangling should be a bit heavier than what's done in
this example, to avoid collisions between the descriptor and the class
that's using it. I like to follow the pattern of __foo name mangling,
so I would have instead used:

self.name = "_TypedProperty__" + name
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which one is the best XML-parser?

2016-07-02 Thread Stefan Behnel
Random832 schrieb am 24.06.2016 um 15:09:
> On Fri, Jun 24, 2016, at 02:39, dieter wrote:
>> You want an incremental parser if the XML documents are so huge that
>> you must process them incrementally rather than have a data structure
>> representing the whole document (in memory). Incremental parsers
>> for XML are usually called "SAX" parsers.
> 
> You know what would be really nice? A "semi-incremental" parser that can
> e.g. yield (whether through an event or through the iterator protocol) a
> fully formed element (preferably one that can be queried with xpath) at
> a time for each record of a document representing a list of objects.
> Does anything like that exist?

http://lxml.de/parsing.html#incremental-event-parsing

https://docs.python.org/3/library/xml.etree.elementtree.html#pull-api-for-non-blocking-parsing

Stefan


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


Re: Namespaces are one honking great idea

2016-07-02 Thread Kevin Conway
> staticmethod isn't technically required to use a method through the class
(or subclasses), it simply provides the appropriate magic to allow it to be
called through instances.

For example, the following code covers all described use cases of the
proposed namespace. Methods are invoked without creating instances and
state is managed on the class object directly.

class CustomNs:

stateful_data = 1

@staticmethod
def echo(text):
print(text)

@classmethod
def mutate(cls):
cls.stateful_data += 1
print(cls.stateful_data)

CustomNs.echo("test")
print(CustomNs.stateful_data)
CustomNs.mutate()
print(CustomNs.stateful_data)

For the proponents of namespace, what is deficient in the above example
that necessitates a language change?

On Sat, Jul 2, 2016, 00:02 Random832  wrote:

> On Fri, Jul 1, 2016, at 21:50, Kevin Conway wrote:
> > I believe the namespace object you are referring to is exactly a
> > class. IIRC, classes came about as a "module in a module".
>
> No, because classes have instances. And conceptually they seem like they
> *should* have instances. Just using the term "class" carries
> expectations.
>
> More to the point, what modules do that classes do not is provide a
> global namespace for functions defined within them, so that variables
> within them can be used (well, read - writing them requires a
> declaration) by the functions without extra qualification.
>
> > Regardless, all use cases you've listed are already satisfied by use
> > of the static and class method decorators. Methods decorated with
> > these do not require an instance initialization to use.
>
> staticmethod isn't technically required to use a method through the
> class (or subclasses), it simply provides the appropriate magic to allow
> it to be called through instances.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: subprocess startup error

2016-07-02 Thread Terry Reedy

On 7/1/2016 11:43 PM, Veek. M wrote:

Shweta Dinnimani wrote:


hi

hello, I'm begineer to python programming.. I had installed python
3.5.1 version on my windows 7 system. I was fine earlier and now when
i was trying the programs on string i'm facing the subprocess startup
error. IDLE is not connecting. And python shell is also not opening. I
tried uninstalling and installing the python shell but Im facing the
problem.Please do help me


In my answer to 
https://stackoverflow.com/questions/37997715/idles-subprocess-didnt-make-a-connection-either-idle-cant-start-or-personal/38001829#38001829

I list all the possible reasons I know of.

A file of yours with the same name as a stdlib file is at least as 
common reason as antivirus/firewall software.



You need to post/screen-capture the whole error message/traceback.


If you start IDLE from Command Prompt with 'python -m idlelib', you 
might get more information.


--
Terry Jan Reedy

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


Re: subprocess startup error

2016-07-02 Thread matej123cekk
try to download pywin 
(i think that pywin will working ok)



url to download https://sourceforge.net/projects/pywin32/files/pywin32/
-- 
https://mail.python.org/mailman/listinfo/python-list


Starting Out and Need Help with Basics.

2016-07-02 Thread CHM Lyrics
I am in fifth year at secondary school (senior years in high school). We've 
been doing basic programs in Python at school, but we're now on a 6 week 
holiday (Summer Holidays). So I decided I would try and download Python and 
learn a bit more while I'm not doing anything. I have now downloaded it, 
however, I have immediately noticed something.

For example, what I know is, is that if you were to type:
print "Welcome to Python!"
And nothing else, it would ask you to save the program, which I'd do, but then 
it just says there's an invalid syntax. I've tried adding a colon after 'print' 
and I've tried adding brackets around "Welcome to Python!". But nothing is 
working, can someone give me a hand please.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Starting Out and Need Help with Basics.

2016-07-02 Thread Chris Angelico
On Sun, Jul 3, 2016 at 7:13 AM, CHM Lyrics  wrote:
> I am in fifth year at secondary school (senior years in high school). We've 
> been doing basic programs in Python at school, but we're now on a 6 week 
> holiday (Summer Holidays). So I decided I would try and download Python and 
> learn a bit more while I'm not doing anything. I have now downloaded it, 
> however, I have immediately noticed something.
>
> For example, what I know is, is that if you were to type:
> print "Welcome to Python!"
> And nothing else, it would ask you to save the program, which I'd do, but 
> then it just says there's an invalid syntax. I've tried adding a colon after 
> 'print' and I've tried adding brackets around "Welcome to Python!". But 
> nothing is working, can someone give me a hand please.
>

Did you use the right brackets? It should look like this:

print("Welcome to Python!")

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


Re: Lost in descriptor land

2016-07-02 Thread Ian Kelly
On Sat, Jul 2, 2016 at 5:32 AM, Ankush Thakur  wrote:
> On Friday, July 1, 2016 at 9:13:19 AM UTC+5:30, Lawrence D’Oliveiro wrote:
>>
>> > Shouldn't we be instead using self.celcius in, say, __init__() and then
>> > everything will work fine?
>>
>> I guess it might. But this way, using descriptors, all the setup is done 
>> once at class definition, rather then every time in class instantiation.
>
> So you're saying the (sole) reason to instantiate descriptor classes at 
> class-level is performance?

Performance might be part of it (it also saves some checks when
looking up attributes), but in my opinion a big reason for it is
separation of responsibilities. Classes define object behavior;
instances contain object state. For example, you can't define a method
on an instance (though you can certainly store a function there and
call it).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-02 Thread Ethan Furman

On 07/02/2016 08:34 AM, Kevin Conway wrote:


For the proponents of namespace, what is deficient in the above example
that necessitates a language change?


Adding a new widget is not changing the language.

--
~Ethan~

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


Help with subclasses and classes

2016-07-02 Thread cadenmrice
When i run the code I get this error :
Traceback (most recent call last):
  File "C:/Python25/chapter2", line 18, in 
bank=InterestAccount(5,1000,0.5)
NameError: name 'InterestAccount' is not defined

I can't find the issue, any help?


class BankAccount:
def __init__(self,numb,bal):
self.numb = numb
self.bal = bal
def showbal(self):
print "Your balance is", self.bal
def withdraw(self,wa):
self.bal-=wa
print("Your balance is now", self.bal)
def deposit(self,da):
bal+=da
print("Your balance is now", self.bal)
class InterestAccount():
def BankAccount__init__(self,numb,bal,intrate):
self.intrate=intrate
def addintrest(self):
self.bal = self.bal * self.intrate
bank=InterestAccount(5,1000,0.5)
bank.addintrest()
bank.showbal()
  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lost in descriptor land

2016-07-02 Thread Lawrence D’Oliveiro
On Saturday, July 2, 2016 at 11:31:02 PM UTC+12, Ankush Thakur wrote:
> On Friday, July 1, 2016 at 9:03:44 AM UTC+5:30, Lawrence D’Oliveiro wrote:
>> Every time I feel unsure, I go back to the horse’s mouth: here
>> 
>> is GvR himself with all the details on “new-style” classes, including the
>> clearest explanation I have come across about descriptors.
> 
> Well, that's certainly a very interesting link (and blog!) but my current
> priority is to just understand this damn thing! :D

Haste makes waste, as they say. At least read the relevant part of the article.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with subclasses and classes

2016-07-02 Thread Bob Gailer
On Jul 2, 2016 9:00 PM,  wrote:
>
> When i run the code I get this error :
> Traceback (most recent call last):
>   File "C:/Python25/chapter2", line 18, in 
> bank=InterestAccount(5,1000,0.5)
> NameError: name 'InterestAccount' is not defined
>
> I can't find the issue, any help?

Following is voice dictated therefore not actually correct but you'll get
the point . interest account is a nested class inside of class bank account
you're trying to refer to it outside of class
>
>
> class BankAccount:
> def __init__(self,numb,bal):
> self.numb = numb
> self.bal = bal
> def showbal(self):
> print "Your balance is", self.bal
> def withdraw(self,wa):
> self.bal-=wa
> print("Your balance is now", self.bal)
> def deposit(self,da):
> bal+=da
> print("Your balance is now", self.bal)
> class InterestAccount():
> def BankAccount__init__(self,numb,bal,intrate):
> self.intrate=intrate
> def addintrest(self):
> self.bal = self.bal * self.intrate
> bank=InterestAccount(5,1000,0.5)
> bank.addintrest()
> bank.showbal()
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-02 Thread Steven D'Aprano
On Sat, 2 Jul 2016 11:50 am, Kevin Conway wrote:

> I believe the namespace object you are referring to is exactly a class.

Yes, a namespace is exactly like a class, minus inheritance, instantiation,
the implied "is-a" relationship, and the whole Java "utility class"
anti-pattern.

In other words, exactly not like a class *wink*

Classes and modules are both namespaces: "an abstract container or
environment created to hold a logical grouping of unique identifiers or
symbols (i.e. names)", to quote Wikipedia:

https://en.wikipedia.org/wiki/Namespace

But classes provide much more functionality, over and above mere namespace:
inheritance, instantiation, etc. I'm not anti-classes or opposed to OOP,
these features are great when they are wanted. But when they aren't wanted,
they're a nuisance.

Modules also provide more than just an abstract namespace: they provide
scope, but that's exactly what I want for my Namespace entity: it should be
a namespace, and it should be a scope for functions. In other words, it
should be a module. I just don't want to have to place the source code in a
separate file, because sometimes that's annoying and overkill.

Modules are good for information hiding and encapsulation, just like
classes, but without inheritance etc. But because you cannot put more than
one module inside a single file, the developer has to make a choice between
information hiding and encapsulation:

(1) You can keep your functions encapsulated inside a single module/file,
but you cannot hide some of them from parts of the module that don't care
about them.

(2) You can hide those functions from the parts of the module that don't
care about them, but only by breaking encapsulation, moving them to another
file, and exposing another name in the file system namespace.


The "namespace" feature offers an alternative.

Namespaces in C#, C++ and PHP:

https://msdn.microsoft.com/en-us/library/z2kcy19k.aspx
https://msdn.microsoft.com/en-us/library/5cb46ksf.aspx
http://php.net/manual/en/language.namespaces.php



> IIRC, classes came about as a "module in a module".

I'm pretty sure they did not. Object oriented programming (and hence
classes) came about from simulating real world objects, hence the name:

http://www.exforsys.com/tutorials/oops-concepts/the-history-of-object-oriented-programming.html

In languages like Pascal, you can nest functions and procedures inside
others, providing something like a namespace functionality, except that
Pascal strictly enforces information hiding. There's no way for code to
peer inside a Pascal function and see nested functions.


> Regardless, all use cases you've listed are already satisfied by use of
> the static and class method decorators. Methods decorated with these do
> not require an instance initialization to use.

And are significantly less easy to use, as the functions MUST refer to each
other by their dotted names.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Namespaces are one honking great idea

2016-07-02 Thread Steven D'Aprano
On Sun, 3 Jul 2016 01:34 am, Kevin Conway wrote:

> staticmethod isn't technically required to use a method through the class
> (or subclasses), it simply provides the appropriate magic to allow it to
> be called through instances.
> 
> For example, the following code covers all described use cases of the
> proposed namespace. 

It really doesn't. Here's your class:

> Methods are invoked without creating instances and 
> state is managed on the class object directly.
> 
> class CustomNs:
> 
> stateful_data = 1
> 
> @staticmethod
> def echo(text):
> print(text)
> 
> @classmethod
> def mutate(cls):
> cls.stateful_data += 1
> print(cls.stateful_data)


The class scope is not "first class" (pun intended), as you cannot refer to
class-level variables without prefixing them with the class, even from
within the class.

Although the class *may* be used without instantiating, this violates the
user's expectations and may be confusing.

I acknowledge that my own namespace has a similar problem, as it uses the
class keyword, but the use of an explicit Namespace decorator or metaclass
gives a hint that something is different. And if you try calling the
Namespace, as if to instantiate it, you get a TypeError.


[...]
> For the proponents of namespace, what is deficient in the above example
> that necessitates a language change?

It's not a language change. Although I'd like a new keyword, to avoid
the "but it looks like a class" problem, its not necessary.


Try getting this behaviour from within a class:


class Food(metaclass=Namespace):

# (1) no special decorators required
def spam(n):
return ' '.join(['spam']*n)

# (2) can call functions from inside the namespace
breakfast = spam(5)

# (3) no "cls" or "self" argument
def lunch():
# (4) can access variables using their undotted name
return breakfast + ' and eggs'

def supper():
# (5) likewise functions (a special case of #4)
return lunch() + ' and a fried slice of spam'

def mutate(n):
# global inside the namespace refers to the namespace,
# not the surrounding module
global breakfast
breakfast = spam(5)



Everything written inside the namespace object could have started as top
level module code. I select the code, hit my editor's "Indent" command, and
insert a single line at the top to turn it into a namespace.

If I decide to move the code into a separate file, I just copy the block,
excluding the "class ... metaclass" header line, past into a new file,
select all, and Dedent. Done.

Can you do all of that with an ordinary class?





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Making Classes Subclassable

2016-07-02 Thread Lawrence D’Oliveiro
Some of the classes in Qahirah, my Cairo binding 
 I found handy to reuse elsewhere, for example 
in my binding for Pixman . Subclassing is 
easy, but then you need to ensure that operations inherited from the superclass 
return instances of the right class. This means that superclass methods must 
never refer directly to the class by name for constructing new objects; they 
need to obtain the current class by more indirect means.

(“isinstance” checks on the superclass name are fine, since they will succeed 
on subclasses as well.)

For example, consider the qahirah.Matrix class. Here is how I define the 
multiplication operator:

def __mul__(m1, m2) :
"returns concatenation with another Matrix, or mapping of a Vector."
if isinstance(m2, Matrix) :
result = m1.__class__ \
  (
xx = m1.xx * m2.xx + m1.xy * m2.yx,
yx = m1.yx * m2.xx + m1.yy * m2.yx,
xy = m1.xx * m2.xy + m1.xy * m2.yy,
yy = m1.yx * m2.xy + m1.yy * m2.yy,
x0 = m1.xx * m2.x0 + m1.xy * m2.y0 + m1.x0,
y0 = m1.yx * m2.x0 + m1.yy * m2.y0 + m1.y0,
  )
elif isinstance(m2, Vector) :
result = m2.__class__ \
  (
x = m2.x * m1.xx + m2.y * m1.xy + m1.x0,
y = m2.x * m1.yx + m2.y * m1.yy + m1.y0
  )
else :
result = NotImplemented
#end if
return \
result
#end __mul__

The idea behind this is that you can do “matrix * matrix” to do matrix 
multiplication, or “matrix * vector” to transform a Vector by a Matrix.

In Pixman, the corresponding class names are Transform instead of Matrix, and 
Point instead of Vector (following the usual pixman terminology). But the 
inherited multiplication operation still works on them.

For another example, consider the qahirah.Vector.from_tuple method, which 
allows easy passing of a simple pair of (x, y) coordinates wherever a Vector is 
wanted, with only a little extra work:

@classmethod
def from_tuple(celf, v) :
"converts a tuple of 2 numbers to a Vector. Can be used to ensure that" 
\
" v is a Vector."
if not isinstance(v, celf) :
v = celf(*v)
#end if
return \
v
#end from_tuple

The key thing here is to avoid staticmethods and use classmethods instead, so 
you get passed the class object and can use it to construct new instances.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta decorator with parameters, defined in explicit functions

2016-07-02 Thread Ian Kelly
On Sat, Jul 2, 2016 at 12:40 AM, Lawrence D’Oliveiro
 wrote:
> On Saturday, July 2, 2016 at 5:10:06 PM UTC+12, Ian wrote:
>> You should use functools.wraps instead of clobbering the decorated
>> function's name and docstring:
>
> Where am I doing that?

Using the implementation you posted:

>>> @decorator_with_args
... def my_decorator(func, *args, **kwargs):
... """Returns func unmodified."""
... return func
...
>>> my_decorator.__doc__
'generates a decorator which applies my_decorator to the given arguments'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Find a file

2016-07-02 Thread tdsperth
Hi 

Thanks for your suggestions - I did get it to work with some os.path calls and 
using flask get files.

Cheers

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


Re: Namespaces are one honking great idea

2016-07-02 Thread Ethan Furman

On 07/02/2016 08:44 PM, Steven D'Aprano wrote:


Try getting this behaviour from within a class:


class Food(metaclass=Namespace):

 # (1) no special decorators required
 def spam(n):
 return ' '.join(['spam']*n)

 # (2) can call functions from inside the namespace
 breakfast = spam(5)

 # (3) no "cls" or "self" argument
 def lunch():
 # (4) can access variables using their undotted name
 return breakfast + ' and eggs'

 def supper():
 # (5) likewise functions (a special case of #4)
 return lunch() + ' and a fried slice of spam'

 def mutate(n):
 # global inside the namespace refers to the namespace,
 # not the surrounding module
 global breakfast
 breakfast = spam(5)



Can you do all of that with an ordinary class?


You can get #2 already, but not the rest (without your spiffy code ;) :

Python 3.5.1+ (3.5:f840608f79da, Apr 14 2016, 12:29:06)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Huh:
...   def blah(text):
... print('blah blah %s blah blah blah' % text)
...   blah('whatever')
...
blah blah whatever blah blah blah

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


Re: Meta decorator with parameters, defined in explicit functions

2016-07-02 Thread Lawrence D’Oliveiro
On Sunday, July 3, 2016 at 4:49:15 PM UTC+12, Ian wrote:
>
> On Sat, Jul 2, 2016 at 12:40 AM, Lawrence D’Oliveiro wrote:
>>
>> On Saturday, July 2, 2016 at 5:10:06 PM UTC+12, Ian wrote:
>>>
>>> You should use functools.wraps instead of clobbering the decorated
>>> function's name and docstring:
>>
>> Where am I doing that?
> 
> Using the implementation you posted:
> 
 @decorator_with_args
> ... def my_decorator(func, *args, **kwargs):
> ... """Returns func unmodified."""
> ... return func
> ...
 my_decorator.__doc__
> 'generates a decorator which applies my_decorator to the given arguments'

That is a function that I am generating, so naturally I want to give it a 
useful docstring. Am I “clobbering” any objects passed in by the caller, or 
returned by the caller? No, I am not.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with subclasses and classes

2016-07-02 Thread Terry Reedy

On 7/2/2016 8:58 PM, cadenmr...@gmail.com wrote:

When i run the code I get this error :
Traceback (most recent call last):
  File "C:/Python25/chapter2", line 18, in 
bank=InterestAccount(5,1000,0.5)
NameError: name 'InterestAccount' is not defined

I can't find the issue, any help?


class BankAccount:
def __init__(self,numb,bal):
self.numb = numb
self.bal = bal
def showbal(self):
print "Your balance is", self.bal
def withdraw(self,wa):
self.bal-=wa
print("Your balance is now", self.bal)
def deposit(self,da):
bal+=da
print("Your balance is now", self.bal)
class InterestAccount():
def BankAccount__init__(self,numb,bal,intrate):
self.intrate=intrate
def addintrest(self):
self.bal = self.bal * self.intrate


InterestAccount should not be nested.  It should subclass BankAccount. 
You should write the subclass init as shown. Do put spaces after commas.


class InterestAccount(BankAccount):
def __init__(self, numb, bal, intrate):
BankAccount(self, numb, bal)
self.intrate=intrate
def addintrest(self):
self.bal = self.bal * self.intrate


bank=InterestAccount(5, 1000, 0.5)
bank.addintrest()
bank.showbal()


I believe the above will not do as you expect.


--
Terry Jan Reedy

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