joannajanssen
joannajanssen

Reputation: 83

When using ctypes in Python, why must CDLL be called in capital letters?

I'm trying to load some proprietary DLLs of a piece of hardware I want to control via a Python script. For this, I'm using the CDLL module from the ctypes package. I encountered this weird issue that for calling CDLL, it must be capitalized or else the function call does not work.

Doing the following throws an error:

from ctypes import CDLL

mcldll = cdll(r'C:\Program Files\Mad City Labs\NanoDrive\Madlib.dll')    # using lower case


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-4ef065672c09> in <module>
      1 from ctypes import CDLL
      2 
----> 3 mcldll = cdll(r'C:\Program Files\Mad City Labs\NanoDrive\Madlib.dll')

TypeError: 'LibraryLoader' object is not callable

But doing this works fine:

from ctypes import CDLL

mcldll = CDLL(r'C:\Program Files\Mad City Labs\NanoDrive\Madlib.dll')    # using upper case

This is the first time I've encountered an issue with case sensitivity when importing or calling modules in Python. What causes this behavior?

Upvotes: 0

Views: 819

Answers (1)

William
William

Reputation: 421

All of Python is case-sensitive. What it seems like you're noticing is that it's unusual for python classes or functions to be in all caps.

Per Python PEP guidelines (https://www.python.org/dev/peps/pep-0008/#class-names) "Class names should normally use the CapWords convention."

In the source code for ctypes, we can see that CDLL is just a class definition

#line 318 of ctypes/__init__.py
class CDLL(object):
    """An instance of this class represents a loaded dll/shared
    library, exporting functions using the standard C calling
    convention (named 'cdecl' on Windows).

So perhaps it seems unusual. I guess the question is how to properly CapWords the word "C DLL". So they just happened to choose "CDLL".

Also, CDLL is a class name, not a module name (which would be all lowercase https://www.python.org/dev/peps/pep-0008/#package-and-module-names)

Edit: In response to comment below, there does seem to be an all lowercase object cdll within ctypes. I am not an expert with ctypes, but it appears to be a different method of loading libraries.

I am not entirely sure of the API differences, but the lowercase cdll is intended to be used with the following syntax:

from ctypes import cdll # lowercase
cdll.LoadLibrary("libc.so.6")

More info at the full docs (https://docs.python.org/3/library/ctypes.html)

Upvotes: 1

Related Questions