Why am I now unable to write a file after importing pymem.process?

Question:

This may have a simple explanation but I’m tired and frustrated. I really just need to be able to use pymem and write a file at the same time. Here’s what I’m running into:

f = open("file.txt", "w")
f.write("")

This works fine and the file is created as expected.

However:

from pymem.process import *

f = open("file.txt", "w")
f.write("")

Gives me the error:

Traceback (most recent call last):
  File "c:GitHubmificatcreate_file_test.py", line 3, in <module>
    f.write("")
AttributeError: 'NoneType' object has no attribute 'write'

I looked at the methods imported with pymem.process and I think a method I’m importing is probably interfering with open() but I’m not sure, and not sure how to work around it. I was expecting to simply be able to output a file as usual while using pymem.

Asked By: auburnbit

||

Answers:

pymem.process has its own open method. This is one reason that

from foo import *

is an antipattern: pymem.process.open is included with from pymem.process import *, and it shadows the built-in open function. Essentially, open becomes pymem.process.open.

Instead, import just what you need:

from pymem.process import foo, bar

Or, import the module and qualify your calls:

import pymem.process

pymem.process.foo()

If you want to use pymem.process.open and don’t want to have to qualify it, you can import it with a different name:

from pymem.process import open as pymem_open

pymem_open(...)

(Note that the upstream library can specify what should be included in *, choosing to omit open if they wish. But it looks like they aren’t doing that.)

Answered By: Chris

pymem.process has its own open method. You should never import something like

from pymem.process import *

This is considered a bad practice. Always state explicitly what methods you want to import, like this:

from pymem.process import list_processes

or you can do this:

from pymem import process

and then use it like this:

process.list_processes()

in case you want to use list_processes() method from pymem.process

Answered By: Azan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.