1

Can we implement source() function in Python?

Python has import statement but the source is executed in the scope of the module.

R's source() reads a script and just runs it in the global scope.

I have a candidate.

def source(filename, code=False):
    print(f'* source("{filename}")')
    if not (filename and os.path.isfile(filename)):
        print('! invalid filename or file does not exist')
        return None
    else:
        with open(filename, encoding = 'UTF-8') as f:
            lns = f.read()
        if code:
            print(lns)
        exec(lns, globals(), globals())
        return True

Can you think of any side effects or negative result from this?

KH Kim
  • 1,155
  • 1
  • 7
  • 14
  • Have you looked at [runpy](https://docs.python.org/3/library/runpy.html)? – constantstranger Apr 16 '22 at 17:10
  • What is your use case? Why is module scope not appropriate for your needs? This post reads like the [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please provide fuller detail of your *X* problem not *Y* solution of Python equivalent of R's `source`. – Parfait Apr 16 '22 at 20:19
  • Can't you do **exec(open("path/to/myscript.py").read())**? – Stéphane Laurent Apr 16 '22 at 20:37
  • @constantstranger I just have. Seems good except for [any functions and classes defined by the executed code are not guaranteed to work correctly after a runpy function has returned.](https://docs.python.org/3/library/runpy.html) And that's exactly what I have questioned! Will my code work as intended? – KH Kim Apr 16 '22 at 22:18
  • @Parfait use case is the same as R's `source()` function. you might want to split the long scripts into two for brevity. – KH Kim Apr 16 '22 at 22:20
  • @Stéphane Laurent Seems good. except for the fact that it's not user-friendly and I want to reuse my knowledge of R... :) – KH Kim Apr 16 '22 at 22:23
  • Please provide an example. Very curious to know why Python's modular scoping cannot work. You can set up another .py script to run on `import` call. But ideally, only functions should be sourced. You should [avoid `exec` in Python](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided). Even [`source` is not advisable in R but instead packages should be used](https://r-pkgs.org/r.html?q=source()#understand-when-code-is-executed) (counterpart to Python modules). – Parfait Apr 16 '22 at 23:22
  • @Parfait one comment there says "+1 for telling that use of eval() is totally okay in home-grown scripts." I have not met any one who disagree with `source()`. Maybe I haven't met enough people. Anyhow I totally disagree with "abandon source, just use package" policy because packaging is not a simple or easy task. One use case for `source()` might be when someone need "globally" global(or across module) variable): https://stackoverflow.com/questions/13034496/using-global-variables-between-files – KH Kim Apr 17 '22 at 19:43

0 Answers0