Sunday, July 10, 2022

[SOLVED] Python if statement with string as condition

Issue

There's some code in virtualenv that's tripping me up. It's this:

path.decode("utf-8") if "__DECODE_PATH__" else path

from href="https://github.com/pypa/virtualenv/blob/aa81cc4ade0336743f79f2b7c22b83cfc1f23f81/src/virtualenv/activation/python/activate_this.py" rel="nofollow noreferrer">activate_this.py line 28.

How can if "__DECODE_PATH__" ever be false? It's possible it's a bug, but since it's in virtualenv and since activate_this.py is the means of activating virtualenv in the current interpreter, it's seems unlikely.

Also there is an issue where someone mentions having this problem but it then being resolved. No one mentions if "__DECODE_PATH__" looking incorrect.

Ultimately it means I get AttributeError: 'str' object has no attribute 'decode' when I try to use activate_this.py. However if I could convince the code to go down the else path it would work fine.

Note: using Python 3.8.10 in Linux Mint 20.3


Solution

From the code, it appears that file is just a template which contains some magic strings that are replaced. In other words, they are just template variables.

You can see the replacement in action in the ViaTemplateActivator base class.

Then in the PythonActivator class you can see that "__DECODE_PATH__" is one of those magic strings.



Answered By - Iguananaut
Answer Checked By - Katrina (WPSolving Volunteer)