'Pythonic way to pass input variables to fstrings in another file
I have a project for my company where I need to go to an internal website that downloads an excel file with factory data. I have two files link_file.py that stores the links to the websites and main.py. This script compares two factories to each other and I need to input different factory codes for each run so I was wondering, what is the most pythonic way to get variables from the main.py file to the dynamic http addresses?
Currently I have fstrings in the main.py file but it looks cluttered with all of the links:
#main.py
import webbrowser
link1 = f"www.factorycode.com/{factory_code1}"
link2 = f"www.factorycode.com/{factory_code2}"
factory_code1 = "abc"
factory_code2 = "xyz"
webbrowser.open(link1)
webbrowser.open(link2)
I tried a solution using os and .format() but it still looks cluttered.
# link_file.py
link1 = f"www.factorycode.com/{factory_code1}"
link2 = f"www.factorycode.com/{factory_code2}"
# main.py
import link_file
import webbrowser
import os
factory_code1 = "abc"
factory_code2 = "xyz"
link_file.link1.format(factory_code1= factory_code1)
link_file.link2.format(factory_code2= factory_code2)
webbrowser.open(link1)
webbrowser.open(link2)
Solution 1:[1]
Try
# link_file.py
link_prefix = "www.factorycode.com/"
# main.py
from link_file import link_prefix
import webbrowser
factory_code1 = "abc"
factory_code2 = "xyz"
link1 = f'{link_prefix}{factory_code1}'
link2 = f'{link_prefix}{factory_code2}'
webbrowser.open(link1)
webbrowser.open(link2)
Solution 2:[2]
This is what functions are for.
def open_link(code):
link = f"www.factorycode.com/{code}"
webbrowser.open(link)
codes = ['abc', 'xyz', 'def', 'jkl']
for code in codes:
open_link(code)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jagerber48 |
| Solution 2 | tzaman |
