Skip to content
Advertisement

Override python open function when used with the ‘as’ keyword to print anything

How can I override the built in open function such that when I call it like so…

JavaScript

The contents variable is any string I want?

EDIT: To clarify, I want to be able to just provide a string to the open function rather than a file path that will be read.

JavaScript

The above should print foobar.

I am aware this is defeating the purpose of open etc but it is for testing purposes.

Advertisement

Answer

You can create your own file-like type and override the builtin open with your own open function.

JavaScript

You can add whatever behavior or additional logic needed to adjust the return value of read() inside File.read itself, or override the behavior entirely from a subclass of File.


Simplified for the particular case in question:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement