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: 
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.
If you want to explicitly specify that something is a closure variable, not a local or global, you use the [`nonlocal`](http://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement) statement. So:

```
def foo():
    nonlocal x  
    x += 1
    return x

```

In Python 2.x, there is no `nonlocal` statement. Your best bet is to upgrade to a modern version of the language. If you can't do that, there are ways to fake it, which are explained in the FAQ, and in [PEP 3104](http://www.python.org/dev/peps/pep-3104/) (which introduced `nonlocal`).