Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[generic] add functools to eval scope #3780

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

[generic] add functools to eval scope #3780

wants to merge 3 commits into from

Conversation

Jaid
Copy link

@Jaid Jaid commented Mar 15, 2023

I have a pretty complex eval expression to clean the title metadata variable. It applies a list of RegEx subtitutions to the string. Currently, I have to use nested function calls for this, like re.sub(re.sub(re.sub(re.sub(re.sub(re.sub()))))) which is hard to read and maintain. I would prefer executing this from left to right using functools.reduce, making my filename expression in config.json look like this:

(as json)

{
  "extractor": {
    "filename": {
      "'num' in locals() and bool(num) and 'title' in locals() and bool(title)": "\fE str(num).zfill(2) + ' – ' + functools.reduce(lambda text, subArguments: re.sub(subArguments[0], subArguments[1], text), [[\"'\", '’'], ['\\.{3}', '…'], ['\\s+', ' '], ['\"(.*?)\"', '“\\g<1>”'], ['[^-\\w,–()[\\]#&:;’„”“… ]+', '_'], ['(^[_\\s]+|[_\\s]+$)', ''], ['^((.{80}).).*$', '\\g<2>…']], title) + '.' + extension",
      "'num' in locals() and bool(num)": "\fE str(num).zfill(2) + '.' + extension",
      "'title' in locals() and bool(title)": "\fE functools.reduce(lambda text, subArguments: re.sub(subArguments[0], subArguments[1], text), [[\"'\", '’'], ['\\.{3}', '…'], ['\\s+', ' '], ['\"(.*?)\"', '“\\g<1>”'], ['[^-\\w,–()[\\]#&:;’„”“… ]+', '_'], ['(^[_\\s]+|[_\\s]+$)', ''], ['^((.{80}).).*$', '\\g<2>…']], title) + '.' + extension",
      "": "{id}.{extension}"
    }
  }
}

(as eval expression)

functools.reduce(lambda text, subArguments: re.sub(subArguments[0], subArguments[1], text), [["'", '’'], ['\.{3}', '…'], ['\s+', ' '], ['"(.*?)"', '“\g<1>”'], ['[^-\w,–()[\]#&:;’„”“… ]+', '_'], ['(^[_\s]+|[_\s]+$)', ''], ['^((.{80}).).*$', '\g<2>…']], title)

I can run this off my fork, but I still would like to see this merged in case anyone else needs functools in their eval expressions.

Signed-off-by: Jaid <jaid.jsx@gmail.com>
@mikf
Copy link
Owner

mikf commented Mar 15, 2023

I'll merge this, I think, but since the latest release (1.25.0) you can use the globals option to "add" (#3773) anything to eval scope without having to touch the actual code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants