Search code examples
pythonlinuxsockets

Socket can't find AF_UNIX attribute


I'm using an Arch Linux machine and trying to run the following code from a Python file.

import socket
import sys

    
if __name__ == "__main__":
    print(sys.platform)
    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

and it keeps telling me that

AttributeError: module 'socket' has no attribute 'AF_UNIX'

Things tried

  • Some posts claim this error occurs on Windows but obviously that isn't the case.
    • sys.platform prints linux
  • Code works on my Mac which was running Python3.9
    • Downgraded from Python3.12 to Python3.9 on the Linux machine and still no luck
  • socket.AF_INET has the same issue
  • running python -c "import socket; socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) returns the same error
  • error when using system binary python, conda python and venv python
  • running it in the interactive shell has no issue however.

Solution

  • The error is caused by an unlucky choice of variable name. The variable socket shadows the module of the same name.

    The first time the line is run, it works fine:

    import socket
    
    socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    # works fine, but now socket points to the object returned by the socket.socket() call
    socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    # error!
    

    Solution: use a different variable name, e.g. sock:

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)