its_me
its_me

Reputation: 15

Python: trying to use exec(), pathlib and __file__ in combination fails

I'm trying to use the __file__ variable within a Class with exec() and pathlib in Python 3.11.2

...which I haven't managed to do so far. The response to my attempts has always been None or an error message.

The example code I try to run:

import pathlib

class Exec_and_Path_problem:
    EXEC_STRING = "pathlib.Path(__file__).with_name(filename)"

    def __init__(self, filename):
        self.filename = filename

    def the_full_filepath(self):
        return exec(Exec_and_Path_problem.EXEC_STRING, \
                    {'pathlib': pathlib, '__file__': __file__}, {'filename': self.filename})


where_is = Exec_and_Path_problem('myfile.txt')
print(where_is.the_full_filepath(), '?')

The main problem a bit simpler:

print(exec(f"pathlib.Path('{__file__}')", {'pathlib': pathlib}, {'__file__': __file__})) # --> None

My goal is a string (EXEC_STRING) that can be specified as a class global variable. After some time of trying, I'm now running out of ideas how to make it work.

Any better(!) idea?

Upvotes: 1

Views: 29

Answers (1)

Lubomyr Pryt
Lubomyr Pryt

Reputation: 123

exec just runs code and not saves unused values. If you need to save a result of executed code then save it inside that code.

Try this:

import pathlib

class Exec_and_Path_problem:
    EXEC_STRING = "self.path = 
pathlib.Path(__file__).with_name(filename)"

    def __init__(self, filename):
        self.filename = filename

    def the_full_filepath(self):
        exec(Exec_and_Path_problem.EXEC_STRING)
        return self.path



where_is = Exec_and_Path_problem('myfile.txt')
print(where_is.the_full_filepath(), '?')

Or this:

exec(f"path = pathlib.Path('{__file__}')")
print(path)

Edit: Or just use eval.

Upvotes: 0

Related Questions