Python for Decision Makers and Business Leaders Transcripts
Chapter: Python vs.
Lecture: Python with C++
0:00 So far, it's been versus. This or that.
0:03 Python or MATLAB.
0:04 Which one do you want?
0:06 But when it comes to C and C++
0:08 Python was actually built with C.
0:11 If you look at the thing you download
0:13 it's actually called CPython
0:15 because it is written in C.
0:18 It happens to run Python
0:19 but the implementation that makes it go is C.
0:21 So Python integrates really well with C and C++.
0:25 There's a couple of ways you can do it.
0:27 You can make libraries in C++
0:29 and here's the extension story on how you do that.
0:32 You can import Python.h into your C++ file
0:36 and off you go.
0:37 There's a library called CFFI or the C types module
0:40 that lets you plug these two things together
0:42 so you can write a core low level bit in C or C++
0:45 maybe it's taking to hardware or whatever
0:48 and then it's very easy to turn that into
0:50 a Python function or class that you can just work with
0:53 as you've seen so far.
0:54 So this is a cool story but it goes further than that.
0:57 There's also this thing called Cython
0:59 CPython, drop the P, Cython
1:03 and it looks like pure Python.
1:05 Here's a silly little math function
1:07 where we're going along and just adding up the distance
1:09 or computing the distance over and over
1:11 and kind of throwing that away.
1:12 It doesn't really do anything useful
1:13 but that's not the point.
1:15 Notice how we put type information on the variables.
1:18 Do math start which is an integer
1:20 and number which is an integer. That's normal Python.
1:23 We haven't done it yet. It's a newer feature.
1:25 We could have done it all along and it's fine
1:28 but if you do this, you can actually run Cython against this
1:32 and what it will do is compile it to C
1:34 and then at C, then it will compile the machine instructions
1:36 and it's as if you had written this directly in C or C++.
1:41 Moreover, you can actually in this world
1:44 in this Cython world, you can start importing
1:46 and working with C functions and classes and so on
1:50 so you can directly create this boundary
1:52 where C and Python touch each other
1:54 but you still write Python code.
1:56 So here's another way in which Python and C and C++
2:00 come together.
2:01 Finally, if you want to look a little more into this
2:03 check out this article over here on realpython.com
2:06 Building a Python C Extension Module.
2:08 It takes you step by step of what you actually have to do
2:11 to make C work with Python.
2:14 It's actually not that complicated.
2:16 Well that does it for our versus round.
2:18 Hopefully those comparisons were meaningful
2:21 and gave you a good sense of what some of the trade offs are
2:24 between all these different programming languages
2:26 and technologies.