Re: is_ as method or property?

2014-12-15 Thread Mateusz Loskot
On 13 December 2014 at 12:24, Steven D'Aprano
 wrote:
> Mateusz Loskot wrote:
>
>> On 12 December 2014 at 12:26, Chris Angelico  wrote:
>>> On Fri, Dec 12, 2014 at 10:21 PM, Mateusz Loskot 
>>> wrote:
>>>> I've got several cases which are not obvious to me.
>>>> For instance, class Foo has a boolean attribute, read-write,
>>>> which I see a couple of realisations for possible:
> [...]
>> I mentioned, setting the new value involves more changes to Foo()
>> instance, so i's not possible to capture it with just an assignment.
>> Hence, the discussion between property vs method.
>
> If the calculation is cheap and fast and "feels like" getting/setting an
> attribute, then use property.
>
> If the calculation is expensive, or might fail, then use explicit
> getter/setter methods.
>
> I'm afraid that there is no objective way to tell when something "feels
> like" an attribute. That depends partly on the class you are dealing with,
> and partly on personal taste.

That confirms my now updated, thanks to this thread, understanding of
that issue.

Thanks all!

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: is_ as method or property?

2014-12-12 Thread Mateusz Loskot
On 12 December 2014 at 22:14, Chris Angelico  wrote:
> On Sat, Dec 13, 2014 at 8:03 AM, Mateusz Loskot  wrote:
>> On 12 December 2014 at 12:26, Chris Angelico  wrote:
>>> On Fri, Dec 12, 2014 at 10:21 PM, Mateusz Loskot  wrote:
>>>> I've got several cases which are not obvious to me.
>>>> For instance, class Foo has a boolean attribute, read-write,
>>>> which I see a couple of realisations for possible:
>>>>
>>>
>>> 0) Attribute only.
>>>
>>> class Foo:
>>> pass
>>>
>>> Foo().default = True
>>>
>>> Unless you need something more than this, go with this style. Much simpler.
>>
>>
>> Agreed, in general, but if the question was related to such simple case,
>> I wouldn't bother asking it.
>>
>> I mentioned, setting the new value involves more changes to Foo()
>> instance, so i's not possible to capture it with just an assignment.
>> Hence, the discussion between property vs method.
>
> It's still worth mentioning, for completeness.

Of course, very good point.

> Plenty of people come from C++

That's me.

> or Java and simply don't realize that direct attribute access
> makes fine sense. Your statement here talks about a read-write boolean
> attribute, so starting off with the simplest way of doing that - an
> actual attribute - emphasizes the commonness of this.

Yes, I see your point now.

> So, your subsequent design decisions are based around the fact that
> you cannot simply assign to .default and have it do the right thing.
> Are you even able to set default to False?

Right. The particular case (with is_default and make_default members)
I'm discussing is similar to this:

class Window:
   def close(self):
  # operate window so it gets closed

   @property
   def is_closed(self)
  # query state of window

> For instance, you might
> have a system where there must always be one "default", and so you
> can't make this one not-default, but you could make a different one
> the default, which will un-default-ify this one as a side effect. In
> that case, a "make_default()" method makes the most sense. But if you
> can independently and cheaply set any instance's default flag, you
> could have the actual attribute, and then a set_default() method,
> which updates it. Plenty of Python classes recommend not arbitrarily
> altering certain attributes.

Yes, makes sense. Thanks for brainstorming those ideas deeper.

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: is_ as method or property?

2014-12-12 Thread Mateusz Loskot
On 12 December 2014 at 12:26, Chris Angelico  wrote:
> On Fri, Dec 12, 2014 at 10:21 PM, Mateusz Loskot  wrote:
>> I've got several cases which are not obvious to me.
>> For instance, class Foo has a boolean attribute, read-write,
>> which I see a couple of realisations for possible:
>>
>
> 0) Attribute only.
>
> class Foo:
> pass
>
> Foo().default = True
>
> Unless you need something more than this, go with this style. Much simpler.


Agreed, in general, but if the question was related to such simple case,
I wouldn't bother asking it.

I mentioned, setting the new value involves more changes to Foo()
instance, so i's not possible to capture it with just an assignment.
Hence, the discussion between property vs method.

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: is_ as method or property?

2014-12-12 Thread Mateusz Loskot
On 11 December 2014 at 19:20, Chris Angelico  wrote:
> On Fri, Dec 12, 2014 at 4:34 AM, Mateusz Loskot  wrote:
>> If a class member function simply tests something and
>> returns a b::oolean call it
>>
>> def is_():
>>  pass
>>
>> like 'is_even'.
>>
>> Should I define it as a classic method
>>
>> def is_even(self):
>> pass
>>
>> or as a property
>>
>> @property
>> def is_even(self):
>> pass
>
> A property should be used if what you're creating is "virtually an
> attribute". If it would make sense to have an attribute is_even, then
> a property is_even makes sense. If in doubt, go with a method.

Thanks for the advise.

I've got several cases which are not obvious to me.
For instance, class Foo has a boolean attribute, read-write,
which I see a couple of realisations for possible:

1) properties only
class Foo:
  @property
  def is_default(self):
pass

  @is_default.setter
  def is_default(self, current):
pass

2) property + method mix
class Foo:
  @property
  def is_default(self):
pass

  def make_default(self, current):
pass

3) methods only
class Foo:
  def is_default(self):
pass

  def make_default(self, current):
pass

>From one angle, that is is_default is known and does not need to be
calculated upon every query, the option 1) fits well.
It is aligned with Ethan's suggestion in the other post.

>From other point, let's assume updating it takes a little bit of changes of
state of Foo instance, then perhaps methods-only option 3) fits best.

Looks like "if in doubt, go with a method" is the safest bet.
'Statistics' from Python codebase also seem to suggest that.

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net
-- 
https://mail.python.org/mailman/listinfo/python-list


is_ as method or property?

2014-12-11 Thread Mateusz Loskot
Hi,

I have been looking at various places to answer this dilemma:

If a class member function simply tests something and
returns a b::oolean call it

def is_():
 pass

like 'is_even'.

Should I define it as a classic method

def is_even(self):
pass

or as a property

@property
def is_even(self):
pass

The question above is based on similar question I found [1],
but that one is specifically about naming.
I'm trying to solve the aspect of implementation of such predicate.

I've looked into the Python 3.4 libs and most of such functions is
realised as a classic method, but in several cases they are
defined with @property decorator, for example:
email.message.MIMEPart.iis_attachment
ipaddress._BaseNetwork.is_multicast
ipaddress._BaseNetwork is_reserved
and a few more.

So, a classic method or a property, which one is the Pythonic 3 way for
such member predicates?

[1] *Naming Conventions* by Thorsten Kampe
https://mail.python.org/pipermail/python-list/2007-June/438156.html

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Format of datetime dump

2012-10-19 Thread Mateusz Loskot
Hi,

I'm not sure if this list is the right place to ask question about PyYAML,
but the yaml-core seems to be too general and quiet.
So, I decided to forward my question here.

I asked on yaml-core the following question, would anyone have any insights?

Mat

-- Forwarded message --
From: Mateusz Loskot 
Date: 19 October 2012 13:58
Subject: Format of datetime dump
To: yaml-c...@lists.sourceforge.net


Hi,

Given this snippet:

yaml.dump({'date':datetime.datetime.now()})
"{date: !!timestamp '2012-10-19 01:32:41.674322'}\n"

Could anyone enlighten me why the ISO8601 format -MM-DDThh:mm:ssTZD
is not used here, by default?
Is there any mean to make yaml.dump generating datetime in ISO8601?

Best regards,
--
Mateusz Loskot, http://mateusz.loskot.net


-- 
Mateusz Loskot, http://mateusz.loskot.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Read-only attribute in module

2012-02-09 Thread Mateusz Loskot
Hi,

I'm implementing Python 3 extension using the Python C API.
I am familiar with defining new types, implementing get/set for attributes, etc.

I'm wondering, is there any mean to implement attribute in module
scope which is read-only?

So, the following

import xyz
print(xyz.flag)  # OK
xyz.flag = 0# error due to no write access

Best regards,
-- 
Mateusz Loskot, http://mateusz.loskot.net
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I tell "incomplete input" from "invalid input"?

2012-01-11 Thread Mateusz Loskot
Hi,

I have been trying to figure out a reliable way to determine
incomplete Python script
input using Python C API. (Apology if it is OT here, I'm not sure where my post
belongs, perhaps to cplusplus-sig list.)

Apparently, most pointers lead to the Python FAQ [1] question:
How do I tell "incomplete input" from "invalid input"?

Unfortunately, this FAQ is either old or incomplete thus incorrect.

First, the proposed testcomplete() function uses internal symbols
which are not available to Python C API users. So, "whoever wrote that FAQ
should be given 20 lashes with a short piece of string" [2].

The second solution is incomplete or incorrect. It does not handle correctly
multi-line input longer than two lines with more flow control statements.
For example:

##
>>> n = 10
>>> if n > 0:
...if n < 100:
  File "", line 2
if n < 100:
  ^
IndentationError: expected an indented block
>>>
##

or

##
>>> for n in range(0, 5):
... if n > 2:
  File "", line 2
if n > 2:
^
IndentationError: expected an indented block
>>>
##

I have attached a slightly modified C++ version of the second program
from the FAQ question [1],
file faq_incomplete_input.cpp  which is also available from my GitHub repo [3]
In this program, I added several FIX comments with proposed corrections.
The idea is to additionally check for
PyErr_ExceptionMatches (PyExc_IndentationError)
and
strcmp (msg, "expected an indented block")
and
prompt is sys.ps2, means more code expected.

And, ignore errors until user confirms the input is finished,
so the whole input is eventually sent to the Py_CompileString
and then all exceptions are not ignored, but considered
as real result of compilation.

I simply wanted to achieve similar semantic to codeop._maybe_compile()
(called by codeop.compile_command) which performs some sort of dirty
hack in the following line:

if not code1 and repr(err1) == repr(err2):

So, the test in action for multi-line multi-statement input gives:

##
>>> c = codeop.compile_command("for n in range(0, 3):", "test", "single")
err1 SyntaxError('unexpected EOF while parsing', ('test', 1, 22, 'for
n in range(0, 3):\n'))
err2 IndentationError('expected an indented block', ('test', 2, 1, '\n'))
comparison.err1 SyntaxError('unexpected EOF while parsing', ('test',
1, 22, 'for n in range(0, 3):\n'))
comparison.err2 IndentationError('expected an indented block',
('test', 2, 1, '\n'))
code None
code1 None
>>> c = codeop.compile_command("for n in range(0, 3):\n\tif n > 0:", "test", 
>>> "single")
err1 IndentationError('expected an indented block', ('test', 2, 11,
'\tif n > 0:\n'))
err2 IndentationError('expected an indented block', ('test', 3, 1, '\n'))
comparison.err1 IndentationError('expected an indented block',
('test', 2, 11, '\tif n > 0:\n'))
comparison.err2 IndentationError('expected an indented block',
('test', 3, 1, '\n'))
code None
code1 None
>>>
##

So, I reckon it make sense to use the same logic to when calling
Py_CompileString.

Does it sound as reasonable solution?

Basically, there seem to be no canonical solution anywhere presented
on how to perform incomplete input tests in reliable manner, how to perform
parsing/compilation in subsequent steps against Python code given line-by-line.

The C API used by Python function compile() is not publicly available.

There is PyRun_InteractiveLoop mechanism but it is tightly coupled to
FILE-based I/O which is not always available when Python is embedded,
so the loop is useless in number of situations.

Have I overlooked any other obvious solution?

Finally, it would be helpful if the Python FAQ is up to date.


[1] 
http://docs.python.org/py3k/faq/extending.html#how-do-i-tell-incomplete-input-from-invalid-input
[2] http://mail.python.org/pipermail/python-list/2004-August/887195.html
[3] https://github.com/mloskot/workshop/blob/master/python/

Best regards,
-- 
Mateusz Loskot, http://mateusz.loskot.net
//
// A quick and dirty C++ version of the C program presented in Python FAQ:
// http://docs.python.org/py3k/faq/extending.html#how-do-i-tell-incomplete-input-fr

Re: PyEval_EvalCodeEx return value

2011-09-24 Thread Mateusz Loskot


John Pinner-3 wrote:
> 
> I assume that you have read the documentation at
> http://docs.python.org/c-api/veryhigh.html,
> and I agree that it's sparse, but the entry for the next entry,
> PyEval_EvalCodeEx, tells you a little more, as does that for
> PyEval_EvalFrameEx.
> 

It does help, but only a bit.


John Pinner-3 wrote:
> 
> Obviously, it's returning a pointer to a PyObject, and Looking at the
> source code, that may be NULL, to throw an exception, or an execution
> frame, or a generator,etc, etc, depending on the code it's been given.
> I guess that you should be able to inspect the PyObject to see what it is.
> 

Yes, that's one possibility. I tried to investigate others.


John Pinner-3 wrote:
> 
> What I'm wondering is, why are you eval-ing code ? A favourite device
> of C programmers coming to Python (and mea culpa in the past), it's
> fraught with potential problems and even security risks, and is
> difficult to debug, and maybe you should be using introspection instead.
> 

My application accepts Python scripts from user and executes using embedded
Python interpreter.
So, I use this particular API.

Could you elaborate on the "using introspection"?


John Pinner-3 wrote:
> 
> And maybe you should be working in Python, and not C++ at this point,
> do the dynamic stuff in the language best suited, and then return to C++
> when needed.
> 

My application in C++ interacts with Python programs provided by users.
Depending on what these programs request, various PyObject objects are
created and returned back, etc.

I understand it's difficult to discuss it without long essays or without
providing the code, etc.
So, I can only discuss and investigate building blocks I use.
Anyway, thanks for your comments.

Best regards,

-
-- 
Mateusz Loskot
http://mateusz.loskot.net
-- 
View this message in context: 
http://old.nabble.com/PyEval_EvalCodeEx-return-value-tp32501833p32503908.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: PyEval_EvalCodeEx return value

2011-09-23 Thread Mateusz Loskot

On 23/09/11 00:47, Mark Hammond wrote:

On 20/09/2011 8:34 PM, Mateusz Loskot wrote:


I'm trying to dig out details about what exactly is the return
value the of PyEval_EvalCodeEx function in Python 3.x
The documentation is sparse, unfortunately.

Perhaps I'm looking at wrong function.
My aim is simple, I need to execute Python code using Python interpreter
embedded in my C++ application.
The Python code is a simple script that always returns single value.
For example:

#! /usr/bin/env python
def foo(a, b):
return a + b
f = foo(2, 3)

But, f can be of different type for different script: one returns
numeric value, another returns a sequence, so the type is not
possible to be determined in advance.

I know how to capture Python stdout/stderr.

I also know how to access the "f" attribute using
PyObject_GetAttrString and then I can convert "f" value to C++ type
depending on PyObject type.

However, I guess there shall be a way to access "f" value
directly from PyEval_EvalCode return object:

PyObject* evalRet = ::PyEval_EvalCode(...);

But, I can't find any details what the "evalRet" actually is.


Eval is to eval an expression. If you simply eval the expression "f" in
the context of the module you should get the result returned. Obviously
though it is designed to eval more complex expressions and in your
specific example, doing the getattr thing will also work fine.


Hi Mark,

So, the result of PyEval_EvalCode strictly depends on the code being 
evaluated. It makes sense.


Thanks for help!

Best regards,
--
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org
Member of ACCU, http://accu.org
--
http://mail.python.org/mailman/listinfo/python-list


PyEval_EvalCodeEx return value

2011-09-20 Thread Mateusz Loskot

Hi,

I'm trying to dig out details about what exactly is the return
value the of PyEval_EvalCodeEx function in Python 3.x
The documentation is sparse, unfortunately.

Perhaps I'm looking at wrong function.
My aim is simple, I need to execute Python code using Python interpreter 
embedded in my C++ application.

The Python code is a simple script that always returns single value.
For example:

#! /usr/bin/env python
def foo(a, b):
   return a + b
f = foo(2, 3)

But, f can be of different type for different script: one returns 
numeric value, another returns a sequence, so the type is not

possible to be determined in advance.

I know how to capture Python stdout/stderr.

I also know how to access the "f" attribute using
PyObject_GetAttrString and then I can convert "f" value to C++ type
depending on PyObject type.

However, I guess there shall be a way to access "f" value
directly from PyEval_EvalCode return object:

PyObject* evalRet = ::PyEval_EvalCode(...);

But, I can't find any details what the "evalRet" actually is.

Any pointers would be helpful.

Best regards,
--
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org
Member of ACCU, http://accu.org
--
http://mail.python.org/mailman/listinfo/python-list


Why PyImport_ExecCodeModule takes char*?

2011-08-26 Thread Mateusz Loskot

Hi,

I'm wondering, why PyImport_ExecCodeModule function takes char*
instead of const char*?

Best regards,
--
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org
Member of ACCU, http://accu.org
--
http://mail.python.org/mailman/listinfo/python-list