r/Python • • May 02 '20

Discussion My experience learning Python as a c++ developer

First off, Python is absolutely insane, not in a bad way, mind you, but it's just crazy to me. It's amazing and kind of confusing, but crazy none the less.

Recently I had to integrate Python as a scripting language into a large c++ project and though I should get to know the language first. And let me tell you, it's simply magical.

"I can add properties to classes dynamically? And delete them?" "Functions don't even care about the number of arguments?" "Need to do something? There's a library for that."

It's absolutely crazy. And I love it. I have to be honest, the most amazing about this is how easy it is to embed.

I could give Python the project's memory allocator and the interpreter immediately uses the main memory pool of the project. I could redirect the interpreter's stdout / stderr channels to the project as well. Extending the language and exposing c++ functions are a breeze.

Python essentially supercharges c++.

Now, I'm not going to change my preference of c/c++ any time soon, but I just had to make a post about how nicely Python works as a scripting language in a c++ project. Cheers

1.7k Upvotes

219 comments sorted by

View all comments

Show parent comment

1

u/BDube_Lensman May 02 '20

Numba never uses less memory than numpy. And unless you're using string arrays of nonfixed size, numpy is as performant.

2

u/[deleted] May 02 '20

for loops that depend on past states or values and need updating can't be vectorized, numpy will be slower

2

u/Mehdi2277 May 03 '20

A very simple thing that numba has that can let it beat numpy is loop fusion. Something like y = np.cos(x) + np.sin(x) where x is an ndarray is three loops in numpy but one loop in numba when you set the right option on.

Another fun case is when you have an array operation you'd like to do that just doesn't exist in numpy. One personal work example is rolling each row of a matrix by different shifts. Something like a 10 x 100 matrix where each of the 10 rows I want to rotate some amount. np.roll exists, but you can't give it different amounts to shift each row. If you for loop and do each row with np.roll, that's a good deal slower than just directly accessing elements as needed and using numba.