The title is quite exhaustive: is there a way to retrieve the desktop environment name (e.g. Gnome, Unity, XFCE, LXDE, KDE...) from the command line or using Python?
The question is rather broad... I think it all depends on what you are trying to accomplish. I would check for the running desktop-session / wm / desktop-shell and only use environment variables as a complement, if at all.
should return the current user running session. With so many forks (and forks on forks) the user might be using a different shell with that particular DE so you would have to check that too, e.g.:
Then, some people use different WMs with those DEs. Some don't use a fully-fledged DE and opt for minimalist desktop managers or WMs on top of
But even then, you would still miss some stuff (e.g. mutter). Again, it all depends on your goals (ideally, you'd have to get familiar with the particulars of each DE+shell/WM in order to be able to get the expected result).