Category: Language Specific

  • How to Use C Functions in Python

    How to Use C Functions in Python

    Did you know you can write functions in C and then call them directly from Python? Isn’t that cool? Let’s skip all the background and the “why would I ever need to do this” for now and just dive on in to the code!

    Read more: How to Use C Functions in Python

    Originally posted here on dev.to

    First, the C Function

    To demonstrate, we’re going to write a program in C to find the factorial of a number. If you don’t remember factorials from high school, here’s an example:

    4! (read four factorial) = 4 * 3 * 2 * 1

    That is what our C program is going to do. Fire up a text editor and lets crank this function out:

    long factorial(int user_input) {
      long return_val = 1;
      if (user_input <= 0) {
        return -1;
      else {
        for (long i = 1; i <= user_input; i++) {
          return_val *= i;
        }
      }
      return return_val;
    }
    
    int main() {
      return 0;
    }

    We are defining a function called “factorial” which will return a “long.” We’re using long instead of int because factorial functions can return some pretty big numbers.

    Next, we’re declaring and initializing return_val which we’ll use to return the value of the calculation.

    Now, the if statement is ensuring the number passed in by the user is positive, and if not, to return the value of -1. We’re returning -1 because later, when we wrap this function in Python, we’re going to know that getting -1 back from the C function probably means there was bad input.

    If the number returned is greater than 0, we enter our loop in which we use an iterator, i, and multiply our return_val variable by it until i is equal to the number passed in by the user. Basically, this loop is saying:
    n! = 1 * 2 * 3 * 4 ... * n

    The final part, with the int main() is to appease the C compiler when we turn this into a .so file. I may be mistaken, but I’m pretty sure this part is necessary even though it doesn’t do anything. If anyone knows any better, please feel free to mention so.

    The Pre-Python Part

    Now that our C is written we have a couple things to do before we write the Python bit. First, save the .c file. I called mine cfactorial.c. Now, we have to turn this into a “shared object” file. In Linux, the command to do so is this:

    $ cc -fPIC -shared -o cfactorial.so cfactorial.c

    This particular command will make a cfactorial.so out of my cfactorial.c file. Now, to the actual Python

    The Python Part

    Almost done! Fire up that text editor again and lets script out some Python. First, we need to import the ctypes module. Then, if you’re anything like me, you’ll want to put the absolute path of the .so file into its own variable. So the top of my pyfactorial.py looks like this:

    from ctypes import *
    
    so_file = '/home/ewhiting/cstuff/cfactorial.so'

    The next thing we want to do is create our cdll object out of our previously created .so file. So, after the so_file variable assignment, put:

    cfactorial = CDLL(so_file)

    Now, technically at this point you can start messing with calling the C function in the Python script by running python in the command line but lets be a little responsible first. Before we play with it some more, lets wrap our C function in a Python function. After creating the cfactorial variable, create the following function:

    def factorial(num):
      c_return = cfactorial.factorial(num)
      if (c_return != -1):
        return c_return
      else:
        return "C Function failed, check inputs"

    Save this file as pyfactorial.py. Altogether, it should look like this:

    from ctypes import *
    
    so_file = '/home/ewhiting/cstuff/cfactorial.so'
    cfactorial = CDLL(so_file)
    
    def factorial(num):
      c_return = cfactorial.factorial(num)
      if (c_return != -1):
        return c_return
      else:
        return "C Function failed, check inputs"

    Note, the way to call functions inside the imported C shared object file is by saying <CDLL Object>.<function name from C code>(<parameter>). Easy!

    So basically, any time we want to use that C function within Python, we call the factorial function which will run the C function with the parameter passed in by the user and evaluate the result. If the C function returns -1 (remember we put that in there), the Python script knows that there was a problem. Otherwise, it will return the number. Lets try it out! Fire up your terminal and start python

    >>> import pyfactorial as pf
    >>> pf.factorial(5)
    120
    >>> pf.factorial(10)
    3628800
    >>> pf.factorial(-4)
    'C Function failed, check inputs'

    Ta-da!! That’s the basic idea behind using C functions in Python. This is definitely a tool worth having. Apply all your other programmerly knowledge to making awesome functions and features, and let me know if you have any questions.

    For my of my writing on C, check out my series on pointers starting with a gentle introduction. If you want reasons to not ever write C in your life, check out my article about why you shouldn’t learn C.

  • How to Debug Code (with Python Examples)

    How to Debug Code (with Python Examples)

    Often in your programming career, you will inadvertently write flawed code that introduces some fault into your codebase. These faults are called bugs and the activity of fixing bugs is called “debugging.” Of course, as developers, we try to write correct code every time, but writing bugs is simply a fact of life for programmers. The ability to diagnose and fix bugs is the mark of an experienced and talented developer and is foundational for advanced troubleshooting. In this article, we’ll go over some techniques for effective debugging and introduce you to PDB, the Python debugger. At the end of this article, you’ll be ready to not only troubleshoot and fix your own code, but to diagnose and debug existing code as well.

    (more…)
  • Python Exception Handling and Customization

    Python Exception Handling and Customization

    Like bugs, exceptions are inevitable when developing software, especially as the complexity of that software increases. Sometimes exceptions are surprising, other times we can anticipate them coming. How a program responds to the occurrence of exceptions is called exception handling, and as programmers, we can define and customize exception handling. In this chapter, we’ll learn what exceptions are, how to handle them, and how to make our own.

    (more…)
  • Test-Driven Development with Python: a Primer

    Test-Driven Development with Python: a Primer

    Making sure the software we build works the way we (and our customers) want it to work is called, unsurprisingly, software testing. Software testing is an enormous topic; indeed, there are entire books, courses, conferences, academic journals, and more about the topic. One can even make a career out of testing software. We couldn’t possibly scratch the surface of the complexity involved in software testing in this article, so we’ll only focus on a topic most relevant to us as programmers: test-driven development.

    (more…)
  • Delegate and Decorate in Python: Part 3 – Reusable Decorators

    Delegate and Decorate in Python: Part 3 – Reusable Decorators

    Note: This is not about Python’s language feature called decorators (with the @ symbol), but about the design patterns called “decorator” and “delegate.”

    In the final installment of this series, we will take the universal concepts of delegation and decoration and put them into a base Decorator class. Doing so will allow us to abstract the universal functionality these patterns to be inherited by more specific decorator classes, maximizing code reuse. Let’s dive in.

    (more…)
  • Delegate and Decorate in Python: Part 2 – The Decorator Pattern

    Delegate and Decorate in Python: Part 2 – The Decorator Pattern

    Note: This is not about Python’s language feature called decorators (with the @ symbol), but about the design patterns called “decorator” and “delegate.”

    In the previous article, we learned how to implement the Delegation pattern in Python. With this knowledge, we’ll now learn about the Decorator pattern, which will make use of delegation. We’ll learn about when we might use it and implement a couple of examples.

    (more…)
  • Delegate and Decorate in Python: Part 1 – The Delegation Pattern

    Delegate and Decorate in Python: Part 1 – The Delegation Pattern

    Note: This is not about Python’s language feature called decorators (with the @ symbol), but about the design patterns called “decorator” and “delegate.”

    In this series we’re going to learn two very useful design patterns: the delegation pattern and the decorator pattern. Each pattern is useful in that they help us enforce the single responsibility principle of object oriented programming. Getting these patterns to work as expected in Python requires a relatively deep dive into Python syntax as well as the always scary technique of metaprogramming. Let’s jump in!

    (more…)
  • Stop Worrying About Which Programming Language to Learn First

    Stop Worrying About Which Programming Language to Learn First

    I remember when I first decided I wanted to learn to write code, my google search history would look like this:

    • Best first programming language
    • What programming language should I learn
    • How to avoid Ebola (unrelated)
    • Python good first language?

    Ultimately, this time I spent was a waste and I’ll tell you why.

    (more…)
  • Why You Shouldn’t Learn C

    Why You Shouldn’t Learn C

    Knowledge of the C programming language is often touted as the mark of a “true” programmer. You don’t really know programming unless you know this language, or so the wisdom goes. Many aspiring programmers have been advised by gatekeepers senior developers to learn C to up their skills and bring them to the next level. That’s what this blog is all about, leveling up, so let’s discuss why learning C might be a waste of your time.

    (more…)
  • C Pointers 101: Part 3 – Pointer Arithmetic

    C Pointers 101: Part 3 – Pointer Arithmetic

    In part 1, we learned the basics of pointers. In part 2, we learned what it meant to pass a variable by value or reference. Remember in part 2 I said that when C passes an array to a function, it passes the pointer to the first element of the array and then pointer arithmetic takes care of the rest? Let’s find out what I mean.

    (more…)