As a social scientists trying to help other social scientists move from
language like R, Stata, and Matlab into Python, one of the behaviors I've
found unnecessarily difficult to explain is the "file.open()/file.close()"
idiom (or, alternatively, context managers). In normal operating systems,
and many high level languages, saving is a one-step operation.
I understand there are situations where an open file handle is useful, but
it seems a simple `to_file` method on strings (essentially wrapping a
context-manager) would be really nice, as it would save users from learning
Apparently there's something like this in the Path library (
but I suspect most people have no idea about that method (I've been doing
python for years and this has always been a personal frustration, and I've
asked several others for better options and no one had one to offer), and
it seems like it would make much more sense as a string method. If someone
has a string they want to save to disk, I can't imagine anyone looking in
the Path library.
I respect the desire to avoid bloat -- the context manager or open/close
idiom has just felt unnecessarily complicated (dare I say unpythonic?) for
a common task.
(Resending to correct list. Sorry about that.)
On Fri, Apr 1, 2016 at 11:25 AM, Ian Kelly <ian.g.kelly(a)gmail.com> wrote:
> On Fri, Apr 1, 2016 at 11:14 AM, Matthias welp <boekewurm(a)gmail.com> wrote:
>>> An example of the transformation would help here
>> An example, that detects cycles in a graph, and doesn't do an update if
>> the graph has cycles.
>> class A(object):
>> def __init__(self, parent):
>> self.parent = parent
> I think you'll find that this doesn't work. Properties are members of
> the class, not of instances of the class.
>> This would prevent cycles from being created in this object A, and would
>> some highly reusable code. The same can be done for @not_none, etc, to
>> some states which may be unwanted.
> But you could accomplish the same thing with "self.parent =
> prevent_cycles(parent)". So I'm still not seeing how the use of the
> decorator syntax eliminates repetition.
---------- Forwarded message ----------
From: Mahan Marwat <mahanmarwat(a)gmail.com>
Date: Thu, Mar 31, 2016 at 9:09 PM
Subject: Make parenthesis optional in parameterless functions definitions
I have an idea of making parenthesis optional for functions having no
def greet: # note the missing parenthesis
The less awkward characters we have, the more readable our code will be
(Beautiful is better then ugly). Some people argued that function
definition with parenthesis seems to them natural. But actually it seems to
us natural, because we have been used to it a-lot. IMHO parenthesisless
functions definitions are natural and readable.
In Python we have already adopted this. i.e parenthesis are optional in
`if` statements, in class definition, in tuple etc
if x == 1: # parenthesis are optional here
class Greet: # now we don't explicitly inherit from `object`
Tuple = 1, 2, 3 # parenthesis are optional here too
Please, give your opinion.
Thanks, Adnan Khan
tldr: Using three method declarations or chaining method calls is ugly, why
not allow variables and attributes to be decorated too?
Currently the way to create variables with custom get/set/deleters is to
use the @property decorator or use property(get, set, del, doc?), and this
must be repeated per variable. If I were able to decorate multiple
properties with decorators like @not_none or something similar, it would
take away a lot of currently used confusing code.
Feedback is appreciated.
The current ways to define the getter, setter and deleter methods for a
variable or attribute are the following:
""" docstring """
var = property(getter, setter, deleter, docstring)
These two methods are doable when you only need to change access behaviour
changes on only one variable or property, but the more variables you want
to change access to, the longer and more bloated the code will get. Adding
multiple restrictions on a variable will for instance look like this:
var = decorator_a(decorator_b(property(value)))
or even this
I propose the following syntax, essentially equal to the syntax of function
var = some_value
which would be the same as
var = decorator(some_value)
and can be chained as well:
var = some_value
which would be
var = decorator(decorator_2(some_value))
var = decorator(decorator_2())
var = some_value
The main idea behind the proposal is that you can use the decorator as a
standardized way to create variables that have the same behaviour, instead
of havng to do that using methods. I think that a lot can be gained by
specifying a decorator that can decorate variables or properties.
Note that many arguments will be the same as for function decorators (PEP
0318), but then applied to variable/property/attribute declaration.
So, let's start a new thread about how to deal with pathlib.Path
objects, involving how/whether to convert between str and Path.
On Fri, Mar 25, 2016 at 7:14 PM, Sven R. Kunze <srkunze(a)mail.de> wrote:
>> On 24.03.2016 22:06, Koos Zevenhoven wrote:
>> Or even better, that you could do p"filename.txt", which would give you a
>> Path string object. Has this been discussed?
> Interesting. I had this thought half a year ago. Quite recently I mentioned
> this to Andrew in a private conversation.
Yeah, I first thought about this at some point last summer when I had
written the little np package for creating numpy arrays as np[3,4,5]
(which I am planning to polish and maybe advertise), probably also
inspired by the f-string discussions on this list. And now that you
asked me about dealing with Paths...
Anyway, as you say, if different people have thought about this
independently, maybe its worth discussing.
> p'/etc/hosts' would make a perfect path which subclassed from str.
Yeah, and regarding the "`to_file()` method for strings" thread, one
could simply do
using the write_text method introduced to Path objects in 3.5. [And of
course there's also read_text(), write_bytes(...) and read_bytes()]
One downside to p-strings like this is that they don't help you when
you have the path in a plain str variable (i.e. not a literal), which
has led me to think Path perhaps should be in builtins. But one thing
that just occured to me now is that, for instance in interactive
sessions, you could do
p"" / path_as_str
instead of `import pathlib; pathlib.Path(path_as_str)`. Not sure if
this is the most beautiful thing ever seen, but it would work for
quick scripting at least.
> The p-string idea has not been discussed in the PEP I think. The subclassing
> thing however was and I think its resolution was a mistake. The explanation,
> at least from my point of view, is a bit weird.
Yeah, having Path subclass str would immediately solve a lot of
compatibility issues. One question is how large a part of those issues
would be solved by just making the builtin open(...) and a few places
here and there in the stdlib accept Path objects. Maybe there are
implementation issues too, although having them lead to bad decisions
would be sad.
Anyway, I think the question of whether Path should subclass str is
partly separate from the p-string concept. After all, b'byte strings'
are not subclassed from str either.
> An example of the transformation would help here
An example, that detects cycles in a graph, and doesn't do an update if
the graph has cycles.
This uses nodes that point to only one other node: if there is a
in the current subgraph, it will detect that within O(n)
def __init__(self, value):
self._value = None
def setter(self, value):
if not turtle_and_hare(value):
self._value = value
raise Exception("cycle detected, shutting down")
def turtle_and_hare(self, other):
Generic turtle and hare implementation. true if cycle, false if
Returns True if cyclic from this point, false if it is not.
turtle = other
hare = other
fieldname = self.__name__
# this assuming that properties have access to their name, but that
# would also be the same as a function.
if hare is None:
hare = getattr(hare, fieldname)
if hare is None:
if hare is turtle:
hare = getattr(hare, fieldname)
turtle = getattr(turtle, fieldname)
if hare is turtle:
def __init__(self, parent):
self.parent = parent
This would prevent cycles from being created in this object A, and would
some highly reusable code. The same can be done for @not_none, etc, to
some states which may be unwanted.
Python's exception handling system is currently badly brokeTypeError:
unsupported operand type(s) for +: 'NoneType' and 'NoneType'n. Therefore,
with the recent news of the joyous release of Python 8 (
have decided to propose a revolutionary idea: safe mock objects.
A "safe" mock object (qualified name
Java-style naming was adopted for readability purposes; comments are now no
longer necessary) is a magic object that supports everything and returns
itself. Since examples speak more words than are in the Python source code,
here are some (examples, not words in the Python source code):
a = 1
b = None
c = a + b # Returns a
print(c) # Prints the empty string.
d = c+1 # All operations on
return a new one.
e = d.xyz(1, 2, 3) # `e` is now a
assert 0 # Causes the function to return a
raise 123 # Does the same thing.
print(L) # L is undefined, so it becomes a
Safe mock objects are obviously the Next Error Handling Revolution ™.
errors now simply disappear and return more
As for `try` and `catch` (protest the naming of `except`!!) statements,
be completely ignored. The `try`, `except`, and `finally` bodies will all be
executed in sequence, except that printing and returning values with an
statement does nothing:
xyz = None.a # `xyz` becomes a
print(123) # Does nothing.
return None # Does nothing.
return xyz # Returns a
Aggressive error handling (as shown in PanicSort [https://xkcd.com/1185/])
that does destructive actions (such as `rm -rf /`) will always execute the
destructive code, encouraging more honest development.
In addition, due to errors simply being ignored, nothing can ever quite go
All discussions about a safe navigation operator can now be immediately
since any undefined attributes will simply return a
Although I have not yet destroy--I mean, improved CPython to allow for this
amazing idea, I have created a primitive implementation of the
I hope you will all realize that this new idea is a drastic improvement
over current technologies and therefore support it, because we can Make
Python Great Again™.
[ERROR]: Your autotools build scripts are 200 lines longer than your
program. Something’s wrong.