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

Incorrect File Resolution #5

Open
lishaduck opened this issue Dec 1, 2023 · 0 comments
Open

Incorrect File Resolution #5

lishaduck opened this issue Dec 1, 2023 · 0 comments

Comments

@lishaduck
Copy link

Issue

When loading the game and the current working directory isn't the root directing of the repo (Where BipoleV.py is located), the game fails to load. This is because the files passed to open() are resolved relative to the CWD rather than the __file__.

Solution

Note

I'd fixed this in #1, but I figured it'd be best to file an issue because it (thankfully) didn't get merged (Thankfully because it didn't fully work and was way too big to be properly reviewed.).

Switch over to pathlib rather than using string concatenation for paths, which has the side benefit of making it support more platforms (due to differences between path separators, and, also, I think, case sensitivity.).

Example

Old

with open("data.csv", "r") as file:
    content = file.read()
    print(content)

New

from pathlib import Path

p = Path(__file__).parent
file_path = Path.resolve(p / "data.csv")

with file_path.open() as file:
    content = file.read()
    print(content)

data.csv

bipole,is,cool

Diff

1c1,6
< with open("data.csv", "r") as file:
---
> from pathlib import Path
> 
> p = Path(__file__).parent
> file_path = Path.resolve(p / "data.csv")
> 
> with file_path.open() as file:

Yes, the code is more verbose, but half of the code only needs to be included once—the import and the definition of p. The centralization of paths is optional but makes for easier refactoring in the future. If you'd rather, you could write the following instead:

Decentralized path resolution

from pathlib import Path

p = Path(__file__).parent

with Path.resolve(p / "data.csv").open() as file:
    content = file.read()
    print(content)

Diff

4d3
< file_path = Path.resolve(p / "data.csv")
6c5
< with file_path.open() as file:
---
> with Path.resolve(p / "data.csv").open() as file:

This version minimizes churn, though I doubt you care much about that, @infinityJKA.

If one really wanted to go crazy, they could also switch to trio for asynchronous effects, but that seems really unreasonable for a mostly unmaintained game. Speaking of which, how's BipoleVI coming along?

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

No branches or pull requests

1 participant