When to use threading.get_ident() and when threading.get_native_id()

Hello,

I struggle to understand the difference between threading.get_ident and threading.get_native_id.
Both return a non-negative integer where get_ident() returns a python internal integer unique to a thread and get_native_id() returns the thread-id also unique to a thread from the os.
What is the use case for get_ident()?
Why would it be preferred to return an python internal integer per thread?

I’ve found this post which even mentions that get_ident() does not always return a thread unique identifier which is contrary to the docs and confuses me even more…

Thank you for your help!

get_ident is an identifier for the python ThreadState. This is an object that carries the threadlocal data needed to execute python code. However, these thread states can be executed from different native threads and the same native thread can run different python threads.

AFAIK this kind of thread shifting doesn’t happen in normal python execution and will only happen if external code is manually starting and stopping python’s execution.

Which you use depends on what you are doing. If you are calling C APIs that are tied to OS threads use get_native_id. If you are only working within python use get_ident (or one of the higher level APIs). If you rely on both and want to write resilient code, use both and detect mismatches and handle them (e.g. by raising an exception).

1 Like

Thank you for your thorough reply. I think I understand the difference a little bit better.

I have an application which runs code provided by its users. Sometimes (unfortunately) these users start threads and interact with the application from one of those threads.
I’m trying to figure out if my code is run from a thread or not.

Since my application is a normal python application my idea was to get the thread-id during startup and compare it the thread-id when the user calls my code.
If I understand your example correctly this would both work with get_ident and get_native_id since these are threads that are started from python code - correct?