Question: In javascript I can write function with closure like this

```
function getUniqueIDfunction() { 
    var id = 0;                          
    return function() { return id++; }; 
};

```

And then use it

```
uniqueID = getUniqueIDfunction();
uniqueID(); //return 0
uniqueID(); //return 1
...

```

Can I perform the same in Python (if it depends with different version let me know) ?

```
def getUniqueIDfunction():
    x = -1
    def foo():
        #And I know that it doesn't work with row bellow and without it    
        #global x  
        x += 1
        return x
    return foo

```

It's just a sample. I want know about closure in Python.

Answer: 
Python 3 introduced this kind of scoping behavior with [PEP 3104](http://www.python.org/dev/peps/pep-3104/) and the `nonlocal` statement:

```
>>> def uniqueId ():
        x = -1
        def inner ():
            nonlocal x
            x += 1
            return x
        return inner

>>> f = uniqueId()
>>> f()
0
>>> f()
1
>>> f()
2

```

Other than that, in previous versions, closures do exist, but you have only a read-only access. So changing `x` will not work. What you can do however is use a mutable object, like a list, and change that one:

```
>>> def uniqueId ():
        x = [-1]
        def inner ():
            x[0] += 1
            return x[0]
        return inner

>>> f = uniqueId()
>>> f()
0
>>> f()
1

```

As you can make any kind of object callable, you can also do something more fancy by defining your own type that has a `__call__` method:

```
>>> class UniqueId:
        def __init__ (self):
            self.x = -1
        def __call__ (self):
            self.x += 1
            return self.x

>>> f = UniqueId()
>>> f()
0
>>> f()
1

```
If all you want is a unique ID, just use the following:

```
def uniqueID():
    x = 0
    while True:
        yield x  
        x += 1

id = next(uniqueID)

```

You can rewrite this with a closure (as [poke mentions in his answer](https://stackoverflow.com/a/19799468/558592)), if you wish to:

```
def getUniqueIDfunction():
    x = -1
    def uniqueID():
        nonlocal x
        x += 1
        return x
    return uniqueID

uniqueID = getUniqueIDfunction()
id = uniqueID()

```

This has the caveat that it only works in Python 3+. For Python 2, you can simulate this behavior by attaching the value `x` to a class.