Jun-29-2018, 06:10 PM
(This post was last modified: Jun-29-2018, 07:16 PM by ichabod801.)
(Jun-29-2018, 04:05 PM)volcano63 Wrote: How about writing proper Python code?
How about not being an arrogant [CENSORED BY MOD]? If you have nothing nice to say, get off of my thread. I don't need people like you spreading negativity. I started coding Python two days ago. I'm still learning.
(Jun-29-2018, 03:30 PM)ichabod801 Wrote: For one thing, you're testing original within the loop. I would think it would be faster to check original once, and only loop if it's a dict. Also, is it common or rare that it's not a dict? If it's common, and if statement is generally faster; if it's rare, a try/except block is generally faster. And (not familiar with yaml) what is it if it's not a dict? Could testing for that be faster? The same applies for your index error. I would guess not creating a separate variable fro num would be faster, but probably not significantly.
Great questions. So, let me give some examples. Let's say we have a .YML with random data.
If someone uses the read function as such:
read("date")
then our job is pretty simple. All we need to do is return yaml.safe_load(raw).get("date")
However, let's say that I want to get python-version. I would need to do: yaml.safe_load(raw).get("settings.python-version")
. Unfortunately, this does not work by default. So, how can we get around this? I begin by splitting their input: value.split(".")
and assigning this array to the variable separate
. We loop through the array. If the current looped element is not of type dict
, then we are finished and we can return. Otherwise, we must append the function like such: yaml.safe_load(raw).get("settings").get("python-version")
Using your advice, I changed the try/catch to an if-statement. This now makes the code look much cleaner. So thanks. :)# Reading data from a file. def read(value): with open(file) as raw: reader = yaml.safe_load(raw) separate = value.split(".") original = reader.get(separate[0]) for v, value in enumerate(separate, 1): if v == len(separate): return original original = original.get(separate[v]) return original