16

I've just read the What's New in Python 3.1 text (and I like many things). What's your idea of the thing that didn't go there but you would like to see in the future Python versions?

8

A module keyword for specifying module scope, analogous to self for class instance scope. It would eliminate I think all use cases for global.

Intead of:

sequenceNumber = 0

def increment():
    global sequenceNumber
    sequenceNumber += 1

It would be like:

sequenceNumber = 0

def increment():
    module.sequenceNumber += 1

Also, in the same vein, a package keyword to reference things defined in the __init__.py for the current submodule.

4

an or clause on loops to make empty iterable flags go away just like the else clause makes not found flags go away.

for item in iterable:
    if hasattr(item, 'foo') and getattr(item, 'foo') == value:
        break
or:
    raise Exception("You gave me an empty iterable :( ")
else:
    raise Exception("I didn't find what you're looking for :( ")
print("wOOt! I found what you're looking for! :) ")

That's just awesome. And it doesn't break any existing code. The else clause runs only if there is no or clause or there is an or clause and the iterable isn't empty.

4

Multithreading:

  • I'd like to see the check interval gone.
  • Progress towards abandoning the GIL.
  • Fast recursive locks would be a nice thing to have when proper threading is implemented, also.

More careful consideration of POSIX semantics. Some kinks remain to be fixed, such as pending signals being inherited by child processes (as in 9535).

Suspension of all language syntax and built-in changes and work towards preserving semantics, for at least one year. This can give time to alternative implementations to get caught up on new features, resolving bugs, aid in wide adoption of Python 3.x (don't forget that most distributions are still in 2.5, sadly), focus more on the libraries, standard or not (is re ever going to be rewritten?).

3

I think something similar to F#'s pipeline operator would be pretty useful.

2

The ability to specify that arguments can be passed only by keyword.

A dict.get() method that takes a callable instead of an object, the callable's result would be returned if the key doesn't exist.

2

I hope they get the reworked re module ready until then. The old one lacks quite a few features and has some subtle bugs/misfeatures.

2

Format Strings:

The ability to use PHP-style (etc) variables in strings activated with an initial character before the string, e.g:

content = 'the quick brown fox jumps over the lazy dog'
html = f'<span class="myclass">$(content)</span>'

rather than going

html = '<span class="myclass">%s</span>' % content
# or
html = '<span class="myclass">%(content)s</span>' % {'content': content}

as I think it's clear there are quite a few instances where code will be made shorter and easier to read because of it, especially when there are lots of variables in the strings.

String Methods:

A lot of text processing like the following is quite common:

s = 'spam [useful information] eggs'
info = s.split('[')[1].split(']')[0]

I think this could be replaced with a single function:

info = s.between('[', ']')

HTML Escaping and Unescaping:

I think it could be in the string methods, for example:

s.escape() # Escape normal HTML
s.escape('quotes') # Escape for "param" in <param="(text)">
s.escape('parenthesis') # Escape for "param" in <param='(text)'>

with an inverse unescape function.

Common File Shortcuts:

A couple of file-reading and writing functions I constantly use are as follows. A lot of the time I just want to read/write a file with as little code as possible:

def file_iter(path, mode='r', encoding='utf-8', errors='strict'):
    # Iterate through a file's contents with the 
    # benefits of `with` with less indentation
    with open(path, mode, encoding=encoding, errors=errors) as f:
        for line in f:
            yield line

def file_read(path, mode='r', encoding='utf-8', errors='strict'):
    # Return a file's contents as a string
    with open(path, mode, encoding=encoding, errors=errors) as f:
        return f.read()

def file_write(path, txt, mode='w', encoding='utf-8', errors='strict'):
    # Update a file's contents with a string
    with open(path, mode, encoding=encoding, errors=errors) as f:
        f.write(txt)

An example of use:

file_write('mypath', 'text')
text = file_read('mypath')

for line in file_iter('mypath'):
    print line

Support for using locale in multi-threaded web apps:

The locale module can currently only have a single locale at once and it's a major problem for multilingual web applications etc which require the various functions in it.


This is all highly subjective, feel free to disagree with me :-)

1
import invisible_pink_unicorn
1

A new keyword "override" that tells to the compiler that a function should override an existing function or raise a compilation error. This keyword is not mandatory to override a function.

class A():
    def MyFunction():
        pass

class B(A):
    def override MyFunction():
        pass

So if MyFunction is removed from class A, a compilation error is raised.

0

Call me crazy, but I would like to see some of the configurable GC and Thunk object space work going on in PyPy brought back into CPython. For example, the ability to declare an infinite list as lazy would be nicer than rigging it up so it appears lazy using an iterator and takewhile. To have this style of computation built in will eliminate much of the following code. In addition, I could possibly use this feature to write the following interator in a listcomp and take an arbitrary index.

from itertools import takewhile

class Fib(object):
    def __init__(self):
        self.n = 0
        self.n_1 = 1

    def __iter__(self):
        return self

    def next(self):
        next = self.n + self.n_1
        self.n = self.n_1
        self.n_1 = next
        return next


def fib_n(n):
    fib = Fib()
    return takewhile(lambda x: x < n, fib)

print list(x for x in fib_n(10))

I don't know, call me functional, but I like the ability to declare infinite data structures.

ps. More thought on this makes me think I can get some of what I want using existing methods in the stdlib, but I still would like it all to be in one standard module.

-3

the self argument is something people have been fretting about for almost as long as python exists. the solution discussed here (to require people to write def self.f():), however, is troublesome and not resolvable without more magic behind the scenes?this mainly because no self exists at class definition time. and i still have to write it out!

i would prefer a solution where self is taken out of the method definition and magically injected into the method namespace:

class X:
  def f( x, y, z ):
    return self.g( x * y * z )

the big advantage of this would be that method signatures will closely match function signatures; the big disadvantages are that (1) now it becomes a preset, not a choice of the developer, how to name their instance variable, and that (2) there might be pathological cases where this kind of magic causes troubles of the kind that riddle javascript?s magic this variable?which requires a PHD in computer science to use correctly. and i am very sure BDFL will come up with a whole bunch of more kinks that this solution has.

-5

Being able to define a class methods with:

def self.foo()

instead of

def foo(self)

-5

1) global variable declaration

global counter = 0
def IncrementCounter():
    counter += 1

2) Type declaration

def int GetAge(mx.DateTime birthDate):
    pass

Correction: If you want the current behavior (dynamic typing), just do :

def GetAge(birthDate):

But it will be difficult to know what your function expects as input and returns as output. And IDE auto-completion will be useless. Not talking about exceptions raised that force others to read your code to know exactly what your function needs and returns.

Comment : I don't understand how you do synthax highlighting.

Note: The editor don't works well.

Added comment : Do you prefer to make this for every function :

def GetAge(birthDate):
    if not isinstance(birthDate, mx.DateTime):
        raise InvalidParameter('birthDate', 'The birthDate parameter should be of type 'mx.DateTime')