Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

How would you improve Python?

Name: Anonymous 2007-07-09 12:37 ID:V5liB5dq

How would you improve Python? I want to picture the perfect practical, multi-paradigm language. I decided to start with Python because I think it's the easiest one to fix. Lua would be another good candidate. So this is what I'd do to Python:

- def and class become expressions and specifying a function class or name is optional. They still maintain the forced indentation of code, and can be used as follows:
function = def (x, y): #Indentation level = 0
    x + y #Indentation level = 4, inside the def
print... #Indentation back to 0, thus def ended, and assignment ended

tuple_of_functions = (def (x, y): #Indentation level = 0
    x + y #Indentation level = 4, inside the def
, lambda x: -x) #Indentation back to 0, thus def ended, assignment did not because of parens


(Note that you can wrap def and class around extra parens to use like braces if you don't like that comma there.)

- $ becomes shorthand notation for lambda, so $x: x + 1 is the same as lambda x: x + 1 . Furthermore, ${ ... } becomes a shorthand for def ():, and supports nested braces, e.g.:
f = ${
           x = 0 #The forced indentation of code begins at whatever column the contents of ${ start
           if x:
               do_something(${ ... })
     }, 1, 2, 3, ${ ... } #f is a tuple of <lambda>, 1, 2, 3, <lambda> 
The closing brace may appear anywhere. If you start the contents of ${} in the same line, as in ${ x + 1 }, you are limited to a single line.

- Besides the forced indentation of code, there's the forced tail call optimization in the language specification, so any interpreter must do it.

- if, while, for, with and try become expressions which return the latest expression they evaluated, and can be used anywhere. A def function returns the last expression evaluated, so the return keyword is optional when specified at the end of a function. break and continue become (special) expressions that return nothing and are only valid within while. print, import, exec and assert become functions. raise becomes a expression. del, return and yield become special expressions. global becomes an expression but it'll be deprecated. pass is deprecated, and becomes a synonym of None. Assignment statements will disappear in a later suggestion. Thus no statements remain. Introducing the forced expressions.

- New while-like expression: do: (forced indentation of code) ... (dedent) while condition (like C's do { } while ();)

- Assignment operations return the assigned value, as in C.

- ++ and -- operators, as in C. They call methods __inc__() and __dec__(), and return the original or the modified value depending on whether they appear before or after the variable.

- Incompatible change: if you assign to a variable in some way (like using = or def), you create a new variable in the local function, as you do in Python, but only if this variable doesn't exist in an outer lexical scope. If it does, then the outer variable is modified. To specify the forced creation of a local variable with the same symbol as an outer lexical scope, you use the local special expression, prefixing the variable name with "local" anywhere in the function, e.g.:
[code]def f():
    i, j = 1, 1
    (def ():
        i, local j = 2, 2
        #local j++ would have caused an exception, as j did not exist and ++ requires that it exists, like j += 1
    )()
    print i, j #Expected: 2, 1


- Braces quote strings like Perl's q{} operator. They can be nested, so {a{b}} is the same string as 'a{b}'.

- .. is a new operator. Used with ints, it generates xrange objects, e.g. 3..10 returns xrange(3, 11). Used with other objects, it calls __range__(other) or __rrange__(other).

- All the changes coming in Python 3000 regarding dictionary functions, deprecated functions, etc. should be applied too.


So, what do you think? Did I screw up somewhere? These changes would allow better functional programming with Python, and something close to macros or TCL commands, e.g. you could define an iff(c, t, f) macro which doesn't evaluate both t and f like:
def iff(c, t, f):
    t() if c() or f()


and you could use it like:

iff(${ x == 3 },
          ${ do_something... },
          ${ do_something_else... })


Assignment would work, there's multiline ${}, etc.

Name: Anonymous 2007-07-12 6:31 ID:0nchLgE3

Exactly what are the features of Python that aren't as nicely supported (or supported at all) in C++?

Too many to tell, here are just a few examples with Python code:


def CreateAdder(x): #Define a function
    return lambda y: x + y
    #The above lambda expression creates an anonymous closure.
    #It's a function which can access variables in outer scopes,
    #and it doesn't have a name because it's an expression, so
    #you either assign it somewhere or pass it somewhere.
    #It's a function of y, which returns the addition of x
    #(CreateAdder's parameter) and y (its own parameter).
    #Note that the function we build is different every time,
    #it depends on how you call CreateAdder.

inc = CreateAdder(1) #We bind the result of CreateAdder(1) to a variable.

print inc(3) #Prints 4
print CreateAdder(10)(5) #Prints 15

#But wait, did we really said this works with integers? NO!
#This does "+". "+" operates on anything that supports "+".

#ANY function or class is a template. And so far, I haven't
#wasted one second defining or specifying any data type anywhere.

#"+" is actually syntactic sugar for a method call.
#When we do object1 + object2, we're just doing
#object1.__add__(object2), so if object1 defines its __add__ and
#its __add__ knows how to add object2, whatever that is, then it works.

prefixfoo = CreateAdder('foo')
print prefixfoo('bar') #Prints foobar

#See how the str class also has an __add__ method. 'a' + 'b' is the same
#as 'a'.__add__('b'). But is __add__ a method? Yes, of course, but methods
#are no different than functions. str is the class holding the method,
#which is a function which receives its object and other parameters, so
#it would be the same to do str.__add__('a', 'b').

#Now let's play with lists
my_list = [1, 2, 3, 4, 5] #Built-in, native syntax
my_list = [5, 6, 7, 8, 9] #Garbage collection

#We can concatenate lists
my_list = my_list + my_list

#What if we compare them?
print my_list == my_list
#This prints True, not because they are the same reference, but because
#each of their values is equal when using == (which is just method __eq__)
#For reference comparison, we can use my_list is my_list

#And we can use list comprehensions to define a list we want to obtain:
[x * 10 for x in xrange(100)]
#We're building a list of x multiplied by 10 for all x in 0..99

#But that's too easy. Let's do something better:
[[x, y] for x in xrange(100) for y in xrange(100) if x < y]
#Ok. Now we obtain a list of lists [x, y] for all x in 0..99 and y in 0..99
#if x is lesser than y, so we obtain [[0, 1], [0, 2], ..., [7, 9], [8, 9]].

#Back to a simpler list...
my_list = [i[0] + i[1] for i in my_list] #We sum the couples of above

#Let's obtain a list that's the result of applying inc
#(our CreateAdder(1) function) to each of my_list elements.
#Would you waste your time iterating manually over it? No!

results = map(inc, my_list)

#Ok, so now we want to add all of the elements of my_list, applying a
#function to the accumulated result and the next list item successively

sum = reduce(int.__add__, my_list)

#Wait, that calls int's __add__. We want to add anything. Let's call a
#generic __add__

import operator as op #Somewhat like #include <operator>

sum = reduce(op.__add__, my_list)

#We could also define our own generic add function, like:
#sum = reduce(lambda x, y: x + y, my_list) #Same as op.__add__

#Now that's much better. The reduce works with any class that happens
#to implement __add__.

#By doing this, we obscured the sum() builtin which already does this
#reduction for us. We want to use sum again.

del sum #Delete our sum; now sum does not exist and a builtin is looked for

#Ok. Did you know about dictionaries? They are hash tables.

d = {'key': 'Value', 1: 100, False: 'Hehehe'}
print d['key'] #Prints 'Value'
d[-10] = 'Hello' #Sets key -10 (integer) to 'Hello'

for key in d: #Iterate over the dictionary
    print 'd[', key, '] = ', d[key]

#We can use keyword arguments for functions.
def lots_of_options(a=1, b=2, c=3, d=4, e=5):
    #5 parameters, with default values
    print a, b, c, d, e
lots_of_functions(c=100) #Just set c, use defaults for the rest
#With keyword arguments we don't need to remember their order

#We can also receive any arguments
def show_me(*args, **kwargs):
    print "I've received these unnamed arguments:"
    print args
    print "and these dictionary arguments:"
    print kwargs #kwargs is a dictionary

#We can also apply functions to lists or dictionaries so easily.
params = [1, 2, 3]
#Now my_function(1, 2, 3) could be called like my_function(*params)

#Now let's play with generators/coroutines.

def generator():
    #This is a function which returns values but remains active, with
    #its instruction pointer and local variables.
    a = 5
    yield a #Yield 5
    a = a + 1
    yield a #Yield 6
g = generator() #We use the g object to obtain its results
print g.next() #5
print g.next() #6
print g.next() #Raises StopIteration exception

#Now let's do some classes.
class C(object):
    '''This is a docstring. You can document Python code in a
    standard way, with introspection. You can obtain this string
    from Python itself. No external tools necessary.'''
    def lol(self): #Define a method
        '''Docstring'''
        #Methods receive the bound object ("this") by parameter
        print 'In lol'

class D(object):
    #We can override the default constructor
    def __init__(self, with_lol=False):
        #If this object is created with the with_lol option, we
        #inherit method lol from C
        if with_lol:
            self.lol = C.lol

Name: Anonymous 2007-07-12 6:33 ID:yY+3xYwv

Name: Anonymous 2007-07-12 6:56 ID:0nchLgE3

>>35
Thanks to the power of libraries you can make C++ (or any other language) do a backflip and eat apple pie.
So, can you make C++ do dynamic typing, first-class functions and classes, generators, list comprehensions, etc.? Yes, in fact you can. That library is called Python. You can embed Python in C (or C++) to do that.

>>37
As an aside: it's for this reason that I don't understand why Lisp seems stuck in the stone-age (hello Common Lisp!). They're all too busy wanking over their superiority to come up with a single canonical distro with a modern "batteries included" standard library.
Fucking truth. I'd also clean all the legacies Common Lisp has, and that 2-Lisp stupidity. Basically, I'd do what you say but start with Scheme, or even a clean Scheme, plus an awesome macro system and syntax for indexing arrays and dictionaries.

>>38
Ok, I'll try enumerating some features of Python that C doesn't have.

- Dynamic typing (AKA duck typing) with strict types
- Ubiquitous polymorphism (method calls are evaluated in real time, if a method with that name exists it's called, don't give a shit about classes)
- Garbage collection
- Built-in, real, properly defined Unicode support
- Built-in lists (and tuples, read-only lists)
- Built-in dictionaries (hash tables) which can use any immutable key (even tuples!)
- Built-in sets with set operations
- Powerful list slicing (like [a:b:c], to access elements from [a to b) step c)
- List comprehensions
- Functional programming tools
- First-class functions
- First-class classes
- Properties that look and feel like properties but are actually functions: forget that getter and setter faggotry
- Metaclasses
- Functions and classes are closures
- Anonymous functions/closures (AKA lambda expressions)
- Functions can return more than one value (tuples)
- Generators
- Coroutines
- Keyword arguments
- Function application with lists and dictionaries
- Introspection, giving access to object and types dictionaries, backtraces (tracebacks), stack frames, variable dictionaries and debugging facilities, all from the language
- Fully dynamic: *anything* you can do on write-time you can do on run-time, including defining new functions, classes, inheritance rules (mixins), etc., and you can also redefine functions to change or hot-upgrade a program's behaviour without restart
- Dynamic code evaluation: eval and exec execute Python code that's in a string
- Direct access to bytecode and AST editing (though it's fugly)

And I'm probably missing 10-15 awesome features C++ lacks.

If I were you, after reading all of these features C++ can't even dream of I'd start learning Python right now. You can do it in 2 days, then discover how to use all of this with experience as you use it here and there.

Name: Anonymous 2007-07-12 7:56 ID:UaR7NthL

>>43
You're an asshole, and I don't like you

Name: Anonymous 2007-07-12 8:06 ID:n+cPBsZm

>>43
Suddenly, dynamic language weenies!

Seriously get over yourselves. Dynamic languages are nothing more than executable hash tables. Yes they're generally preferable to languages such as C++ and Java but that's due largely to the godawful design of said languages, not the fact that they don't go out of their way to look up every symbol at runtime.

Name: Anonymous 2007-07-12 8:27 ID:RQ/JS02Q

>>43

Don't worry, many of those features are planned to be introduced in the new C2009 standard. It's not the C your grandma programmed.

Name: Anonymous 2007-07-12 8:30 ID:ID1PIpu/

So C2009 is pretty much D?

Name: Anonymous 2007-07-12 8:40 ID:RQ/JS02Q

>>47

It certainly shares some features with D, but unlike D is also backwards compatible with earlier C standards. (Most notably, D doesn't have a preprocessor.)

Name: Anonymous 2007-07-12 9:35 ID:0nchLgE3

>>44
Lol, ok

>>45
Suddenly, dynamic language weenies!
Lol

Dynamic languages are nothing more than executable hash tables.
And this is why they are so good/powerful/flexible/introspective. Lists and dictionaries are like violence. If they don't work, use more.

Also, answer how you would do all of what I said in >>43.

>>46
O RLY? Post which features.

Name: Anonymous 2007-07-12 11:57 ID:n+cPBsZm

Name: Anonymous 2007-07-13 5:13 ID:a9wj0xUM

>>50
Lol Haskellfag

Name: Anonymous 2007-07-13 5:15 ID:VPrZvah4

░▒▒▓▓███
░░▒▓████
░▒▓███▓▓
░░▒▓███▓
░▒▒▓▓███
░░▒▒▒▓▓█

Name: Anonymous 2007-07-13 6:15 ID:sJ8XSn9F

WHY THE JAVA HATE? WHAT IS WRONG WITH IT?

Name: Anonymous 2007-07-13 13:09 ID:TFJHzAwb

>>53
Java programmers are the erotic furries of programming.

Name: Anonymous 2007-07-13 14:49 ID:mxTdV/YU

★★★★★★★★★★★★★★★★★★★★★★★★★★
★★☆☆☆★★★☆☆☆☆★★★☆☆☆★★☆☆☆☆★★
★☆☆★☆☆★★★☆☆★★★☆☆★☆☆★☆☆★☆☆★
★☆☆★★★★★★☆☆★★★☆☆★★★★☆☆★☆☆★
★★☆☆☆★★★★☆☆★★★☆☆★★★★☆☆☆☆★★
★★★☆☆☆★★★☆☆★★★☆☆★★★★☆☆★★★★
★☆★★☆☆☆★★☆☆★★★☆☆★★★★☆☆★★★★
★☆☆★★☆☆★★☆☆★★★☆☆★☆☆★☆☆★★★★
★★☆☆☆☆★★☆☆☆☆★★★☆☆☆★★☆☆★★★★
★★★★★★★★★★★★★★★★★★★★★★★★★★

Name: Anonymous 2007-07-13 19:23 ID:gWKc8DPW

>>53
long fucking names (java.classes.forms.blablabla), no manual memory management, it's VERY platform dependent (needs a precompiled runtime) and ITS FUCKING SLOW.

Name: Anonymous 2007-07-13 19:32 ID:0Tapqcf2

no manual memory management
That's a good thing!

Java's problem is that it's a low-level language trying to be high level. Since it's low-level, the productivity sucks. Since it's trying to be high-level (aka hello VM) it's no good at low-level tasks either.

Name: Anonymous 2009-01-14 15:16

Optimize THIS

Name: Anonymous 2010-05-27 12:22

bbcode

Name: Anonymous 2010-05-27 12:23

bbcode

Name: Anonymous 2010-05-27 12:25

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Name: Anonymous 2010-05-27 12:25

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Name: Anonymous 2010-05-27 12:26

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Name: Anonymous 2010-05-27 12:26

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Name: Anonymous 2010-05-27 12:30

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Loading, please wait
|================|


|oooooooooo|
|oooooooooo|
|oooooooooo|
|oooooooooo|
|oooooooooo|

Name: Anonymous 2010-05-27 12:32

ǝpoɔqq buısn ʇɐ ʞɔns sʎnb noʎyou guys suck at using bbcode

Loading, please wait.
|==================|



|oooooooooo|
|oooooooooo|
|oooooooooo|
|oooooooooo|
|oooooooooo|

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List