1

My program is a pipeline that processes files. I have a dict (P) which stores directory Path's. All of these directory Path's are are relative to a common ROOT Path from which they are generated. The dict works when I define ROOT outside of the dict as follows:

# WORKS
from pathlib import Path
    
ROOT = Path("/very/long/path/")
P = {
    "ROOT": ROOT,
    "FS_TO_IDX": ROOT / "docs/",
    "IDXD_FS": ROOT / "indexed_docs/",
}

This seems inelegant. Since ROOT is already an element of dict, I would prefer to use the ROOT value in generating the remaining dict values. However, I get "Undefined variable:P" when I do the following.

# FAILS    
from pathlib import Path

P = {
    "ROOT": Path("/very/long/path/"),
    "FS_TO_IDX": P["ROOT"] / "docs/",
    "IDXD_FS": P["ROOT"] / "indexed_docs/",
}

Is there a similar approach that would allow me to assign a dict value and then use that same key/value to define other values in the dict? For example, the walrus operator (:=) seems to provide similar behavior by allowing one to assign to variables within an expression and then use that variable.

user2514157
  • 545
  • 6
  • 24
  • which version of python are you using? – bigbounty Jul 20 '20 at 01:19
  • I am using Python 3.8. Will double check based on you response (confirmed not working). – user2514157 Jul 20 '20 at 01:22
  • Actually it's not working in python 3.7 also. My bad. Already there was a dict with name P – bigbounty Jul 20 '20 at 01:30
  • 1
    Does this answer - https://stackoverflow.com/questions/3738381/what-do-i-do-when-i-need-a-self-referential-dictionary? – bigbounty Jul 20 '20 at 01:46
  • https://stackoverflow.com/questions/3738381/what-do-i-do-when-i-need-a-self-referential-dictionary is a heavier solution than I anticipated. It also raises an issue I overlooked. I assume the expressions within the dict are evaluated once during dict creation. If ROOT changes, the remaining Path's will not be correct if they are not manually updated. Ideally, this would need to be a "frozendict" to prevent inconsistent changes (or else update values according to the referenced answer). – user2514157 Jul 20 '20 at 02:14

0 Answers0