Augmented Assignment Python Car

General Questions¶

Is there a source code level debugger with breakpoints, single-stepping, etc.?¶


The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is . You can also write your own debugger by using the code for pdb as an example.

The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger.

PythonWin is a Python IDE that includes a GUI debugger based on pdb. The Pythonwin debugger colors breakpoints and has quite a few cool features such as debugging non-Pythonwin programs. Pythonwin is available as part of the Python for Windows Extensions project and as a part of the ActivePython distribution (see

Boa Constructor is an IDE and GUI builder that uses wxWidgets. It offers visual frame creation and manipulation, an object inspector, many views on the source like object browsers, inheritance hierarchies, doc string generated html documentation, an advanced debugger, integrated help, and Zope support.

Eric is an IDE built on PyQt and the Scintilla editing component.

Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at and DDD can be found at

There are a number of commercial Python IDEs that include graphical debuggers. They include:

How can I create a stand-alone binary from a Python script?¶

You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as . It converts Python byte code to C arrays; a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.

It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.

Obviously, freeze requires a C compiler. There are several other utilities which don’t. One is Thomas Heller’s py2exe (Windows only) at

Another tool is Anthony Tuininga’s cx_Freeze.

Core Language¶

Why am I getting an UnboundLocalError when the variable has a value?¶

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

This code:

works, but this code:

results in an UnboundLocalError:

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to , the compiler recognizes it as a local variable. Consequently when the earlier attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

You can do a similar thing in a nested scope using the keyword:

>>> x=10>>> defbar():... print(x)>>> bar()10
>>> x=10>>> deffoo():... print(x)... x+=1
>>> foo()Traceback (most recent call last):...UnboundLocalError: local variable 'x' referenced before assignment
>>> x=10>>> deffoobar():... globalx... print(x)... x+=1>>> foobar()10
>>> deffoo():... x=10... defbar():... nonlocalx... print(x)... x+=1... bar()... print(x)>>> foo()1011

What are the rules for local and global variables in Python?¶

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring for assigned variables provides a bar against unintended side-effects. On the other hand, if was required for all global references, you’d be using all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the declaration for identifying side-effects.

Why do lambdas defined in a loop with different values all return the same result?¶

Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.:

This gives you a list that contains 5 lambdas that calculate . You might expect that, when called, they would return, respectively, , , , , and . However, when you actually try you will see that they all return :

This happens because is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of is , so all the functions now return , i.e. . You can also verify this by changing the value of and see how the results of the lambdas change:

In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global :

Here, creates a new variable local to the lambda and computed when the lambda is defined so that it has the same value that had at that point in the loop. This means that the value of will be in the first lambda, in the second, in the third, and so on. Therefore each lambda will now return the correct result:

Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.

>>> squares=[]>>> forxinrange(5):... squares.append(lambda:x**2)
>>> squares[2]()16>>> squares[4]()16
>>> x=8>>> squares[2]()64
>>> squares=[]>>> forxinrange(5):... squares.append(lambdan=x:n**2)
>>> squares[2]()4>>> squares[4]()16

How do I share global variables across modules?¶

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

x=0# Default value of the 'x' configuration setting

What are the “best practices” for using import in a module?¶

In general, don’t use . Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space.

It’s good practice if you import modules in the following order:

  1. standard library modules – e.g. , , ,
  2. third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.
  3. locally-developed modules

It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:

Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.

In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.

It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in .

Why are default values shared between objects?¶

This type of bug commonly bites neophyte programmers. Consider this function:

The first time you call this function, contains a single item. The second time, contains two items because when begins executing, starts out with an item already in it.

It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and , are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use as the default value and inside the function, check if the parameter is and create a new list/dictionary/whatever if it is. For example, don’t write:


This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:

# Callers will never provide a third parameter for this function. def expensive(arg1, arg2, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result

You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.

deffoo(mydict={}):# Danger: shared reference to one dict for all calls...computesomething...mydict[key]=valuereturnmydict
deffoo(mydict=None):ifmydictisNone:mydict={}# create a new dict for local namespace

How can I pass optional or keyword parameters from one function to another?¶

Collect the arguments using the and specifiers in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using and :


What is the difference between arguments and parameters?¶

Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:

foo, bar and kwargs are parameters of . However, when calling , for example:

the values , , and are arguments.


Why did changing list ‘y’ also change list ‘x’?¶

If you wrote code like:

you might be wondering why appending an element to changed too.

There are two factors that produce this result:

  1. Variables are simply names that refer to objects. Doing doesn’t create a copy of the list – it creates a new variable that refers to the same object refers to. This means that there is only one object (the list), and both and refer to it.
  2. Lists are mutable, which means that you can change their content.

After the call to , the content of the mutable object has changed from to . Since both the variables refer to the same object, using either name accesses the modified value .

If we instead assign an immutable object to :

we can see that in this case and are not equal anymore. This is because integers are immutable, and when we do we are not mutating the int by incrementing its value; instead, we are creating a new object (the int ) and assigning it to (that is, changing which object refers to). After this assignment we have two objects (the ints and ) and two variables that refer to them ( now refers to but still refers to ).

Some operations (for example and ) mutate the object, whereas superficially similar operations (for example and ) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return to help avoid getting the two types of operations confused. So if you mistakenly write thinking it will give you a sorted copy of , you’ll instead end up with , which will likely cause your program to generate an easily diagnosed error.

However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, mutates lists but not tuples or ints ( is equivalent to and mutates , whereas and create new objects).

In other words:

  • If we have a mutable object (, , , etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.
  • If we have an immutable object (, , , etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

If you want to know if two variables refer to the same object or not, you can use the operator, or the built-in function .

>>> x=[]>>> y=x>>> y.append(10)>>> y[10]>>> x[10]
>>> x=5# ints are immutable>>> y=x>>> x=x+1# 5 can't be mutated, we are creating a new object here>>> x6>>> y5

How do I write a function with output parameters (call by reference)?¶

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.

  1. By returning a tuple of the results:

    This is almost always the clearest solution.

    deffunc2(a,b):a='new-value'# a and b are local namesb=b+1# assigned to new objectsreturna,b# return new valuesx,y='old-value',99x,y=func2(x,y)print(x,y)# output: new-value 100
  2. By using global variables. This isn’t thread-safe, and is not recommended.

  3. By passing a mutable (changeable in-place) object:

    deffunc1(a):a[0]='new-value'# 'a' references a mutable lista[1]=a[1]+1# changes a shared objectargs=['old-value',99]func1(args)print(args[0],args[1])# output: new-value 100
  4. By passing in a dictionary that gets mutated:

    deffunc3(args):args['a']='new-value'# args is a mutable dictionaryargs['b']=args['b']+1# change it in-placeargs={'a':' old-value','b':99}func3(args)print(args['a'],args['b'])
  5. Or bundle up values in a class instance:

    There’s almost never a good reason to get this complicated.

    classcallByRef:def__init__(self,**args):for(key,value)inargs.items():setattr(self,key,value)deffunc4(args):args.a='new-value'# args is a mutable callByRefargs.b=args.b+1# change object in-placeargs=callByRef(a='old-value',b=99)func4(args)print(args.a,args.b)

Your best choice is to return a tuple containing the multiple results.

How do you make a higher order function in Python?¶

You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define which returns a function that computes the value . Using nested scopes:

Or using a callable object:

In both cases,

gives a callable object where .

The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

Object can encapsulate state for several methods:

Here , and act like functions which share the same counting variable.

classexponential(linear):# __init__ inheriteddef__call__(self,x):returnself.a*(x**self.b)

How can my code discover the name of an object?¶

Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; The same is true of and statements, but in that case the value is a callable. Consider the following code:

class A: pass B = A a = B() b = a print(b) <__main__.A object at 0x16D07CC> print(a) <__main__.A object at 0x16D07CC>

Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance’s name is a or b, since both names are bound to the same value.

Generally speaking it should not be necessary for your code to “know the names” of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care – so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)...

....and don’t be surprised if you’ll find that it’s known by many names, or no name at all!

What’s up with the comma operator’s precedence?¶

Comma is not an operator in Python. Consider this session:

Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:


The same is true of the various assignment operators (, etc). They are not truly operators but syntactic delimiters in assignment statements.

>>> "a"in"b","a"(False, 'a')

Is there an equivalent of C’s ”?:” ternary operator?¶

Yes, there is. The syntax is as follows:

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the form.


Is it possible to write obfuscated one-liners in Python?¶

Yes. Usually this is done by nesting within . See the following three examples, due to Ulf Bartelt:

Don’t try this at home, kids!

fromfunctoolsimportreduce# Primes < 1000print(list(filter(None,map(lambday:y*reduce(lambdax,y:x*y!=0,map(lambdax,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))# First 10 Fibonacci numbersprint(list(map(lambdax,f=lambdax,f:(f(x-1,f)+f(x-2,f))ifx>1else1:f(x,f),range(10))))# Mandelbrot setprint((lambdaRu,Ro,Iu,Io,IM,Sx,Sy:reduce(lambdax,y:x+y,map(lambday,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambdayc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,Sx=Sx,Sy=Sy:reduce(lambdax,y:x+y,map(lambdax,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,i=i,Sx=Sx,F=lambdaxc,yc,x,y,k,f=lambdaxc,yc,x,y,k,f:(k<=0)or(x*x+y*y>=4.0)or1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy))))(-2.1,0.7,-1.2,1.2,30,80,24))# \___ ___/ \___ ___/ | | |__ lines on screen# V V | |______ columns on screen# | | |__________ maximum of "iterations"# | |_________________ range on y axis# |____________________________ range on x axis

Numbers and strings¶

How do I specify hexadecimal and octal integers?¶

To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase “o”. For example, to set the variable “a” to the octal value “10” (8 in decimal), type:

Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:

>>> a=0o10>>> a8
>>> a=0xa5>>> a165>>> b=0XB2>>> b178

Why does -22 // 10 return -3?¶

It’s primarily driven by the desire that have the same sign as . If you want that, and also want:

then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate need to make have the same sign as .

There are few real use cases for when is negative. When is positive, there are many, and in virtually all of them it’s more useful for to be . If the clock says 10 now, what did it say 200 hours ago? is useful; is a bug waiting to bite.


How do I convert a string to a number?¶

For integers, use the built-in type constructor, e.g. . Similarly, converts to floating-point, e.g. .

By default, these interpret the number as decimal, so that and raises . takes the base to convert from as a second optional argument, so . If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex number.

Do not use the built-in function if all you need is to convert strings to numbers. will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass which would erase your home directory.

also has the effect of interpreting numbers as Python expressions, so that e.g. gives a syntax error because Python does not allow leading ‘0’ in a decimal number (except ‘0’).

How do I convert a number to a string?¶

To convert, e.g., the number 144 to the string ‘144’, use the built-in type constructor . If you want a hexadecimal or octal representation, use the built-in functions or . For fancy formatting, see the String Formatting section, e.g. yields and yields .

How do I modify a string in place?¶

You can’t, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an object or the module:

>>> importio>>> s="Hello, world">>> sio=io.StringIO(s)>>> sio.getvalue()'Hello, world'>>>>>> sio.write("there!")6>>> sio.getvalue()'Hello, there!'>>> importarray>>> a=array.array('u',s)>>> print(a)array('u', 'Hello, world')>>> a[0]='y'>>> print(a)array('u', 'yello, world')>>> a.tounicode()'yello, world'

How do I use strings to call functions/methods?¶

There are various techniques.

  • The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

    defa():passdefb():passdispatch={'go':a,'stop':b}# Note lack of parens for funcsdispatch[get_input()]()# Note trailing parens to call function
  • Use the built-in function :

    Note that


I’m assuming you already know a fair bit about neural networks and regularization, as I won’t go into too much detail about their background and how they work. I am using Keras with TensorFlow backend as a ML framework and a couple of dependancies like , and . You may want to check out code of the final solution I am describing in this tutorial, however keep in mind that if you would like to follow along, you may as well need a machine with a CUDA-capable GPU.

Training a model to drive a car in a simulator is one of the assignments in Udacity Self-Driving Car Nanodegree program, however the concepts described here should be easy to follow even without that context.


The provided driving simulator had two different tracks. One of them was used for collecting training data, and the other one — never seen by the model — as a substitute for test set.

Data collection

The driving simulator would save frames from three front-facing “cameras”, recording data from the car’s point of view; as well as various driving statistics like throttle, speed and steering angle. We are going to use camera data as model input and expect it to predict the steering angle in the range.

I have collected a dataset containing approximately 1 hour worth of driving data around one of the given tracks. This would contain both driving in “smooth” mode (staying right in the middle of the road for the whole lap), and “recovery” mode (letting the car drive off center and then interfering to steer it back in the middle).

Balancing dataset

Just as one would expect, resulting dataset was extremely unbalanced and had a lot of examples with steering angles close to (e.g. when the wheel is “at rest” and not steering while driving in a straight line). So I applied a designated random sampling which ensured that the data is as balanced across steering angles as possible. This process included splitting steering angles into bins and using at most frames for each bin:

Histogram of the resulting dataset looks fairly balanced across most “popular” steering angles.

Dataset histogram

Please, mind that we are balancing dataset across absolute values, as by applying horizontal flip during augmentation we end up using both positive and negative steering angles for each frame.

Data augmentation

After balancing ~1 hour worth of driving data we ended up with 7,698 samples, which most likely wouldn’t be enough for the model to generalise well. However, as many pointed out, there a couple of augmentation tricks that should let you extend the dataset significantly:

  • Left and right cameras. Along with each sample we receive frames from 3 camera positions: left, center and right. Although we are only going to use central camera while driving, we can still use left and right cameras data during training after applying steering angle correction, increasing number of examples by a factor of 3.
  • Horizontal flip. For every batch we flip half of the frames horizontally and change the sign of the steering angle, thus yet increasing number of examples by a factor of 2.
  • Vertical shift. We cut out insignificant top and bottom portions of the image during preprocessing, and choosing the amount of frame to crop at random should increase the ability of the model to generalise.
  • Random shadow. We add a random vertical “shadow” by decreasing brightness of a frame slice, hoping to make the model invariant to actual shadows on the road.

We then preprocess each frame by cropping top and bottom of the image and resizing to a shape our model expects (, RGB pixel intensities of a 32×128 image). The resizing operation also takes care of scaling pixel values to .

To make a better sense of it, let’s consider an example of a single recorded sample that we turn into 16 training samples by using frames from all three cameras and applying aforementioned augmentation pipeline.

Original frames

Augmented and preprocessed frames

Augmentation pipeline is applied in using a Keras generator, which lets us do it in real-time on CPU while GPU is busy backpropagating!


I started with the model described in Nvidia paper and kept simplifying and optimising it while making sure it performs well on both tracks. It was clear we wouldn’t need that complicated model, as the data we are working with is way simpler and much more constrained than the one Nvidia team had to deal with when running their model. Eventually I settled on a fairly simple architecture with 3 convolutional layers and 3 fully connected layers.

Model architecture

This model can be very briefly encoded with Keras.

I added dropout on 2 out of 3 dense layers to prevent overfitting, and the model proved to generalise quite well. The model was trained using Adam optimiser with a learning rate = and mean squared error as a loss function. I used 20% of the training data for validation (which means that we only used 6,158 out of 7,698 examples for training), and the model seems to perform quite well after training for ~20 epochs — you can find the code related to training in .


The car manages to drive just fine on both tracks pretty much endlessly. It rarely goes off the middle of the road, this is what driving looks like on track 2 (previously unseen).

Driving autonomously on a previously unseen track

You can check out a longer highlights compilation video of the car driving itself on both tracks.

Clearly this is a very basic example of end-to-end learning for self-driving cars, nevertheless it should give a rough idea of what these models are capable of, even considering all limitations of training and validating solely on a virtual driving simulator.

Follow @navoshtaStarForkDownload


Leave a Reply

Your email address will not be published. Required fields are marked *