Use JSON files as if they are Python modules
11–20 of 67 posts
Re: Use JSON files as if they are Python modules
#12> Disclaimer: Only do this if you hate yourself and the rest of the world. I'm curious why the author would do this. Just for the fun in it?
Re: Use JSON files as if they are Python modules
#13Why do all the comments act like this is bad? Seems fine to me. Explanation would be appreciated :)
Because it monkey patches the way imports work. The context manager isn't bad really, although there are probably more natural ways to create a python object with the same structure as a JSON file without abusing the import system.
Re: Use JSON files as if they are Python modules
#14As a JavaScript developer for the past 5 years or so, when jumping into Python I certainly miss the simple require( ) which this seems to replicate into Python pretty well! Having said that I don't think that I would use it for serious things since this isn't really the Python way and I would like my code to be most understood by others. Neat though!
Re: Use JSON files as if they are Python modules
#15Re: Use JSON files as if they are Python modules
#16it was fun I will check it tomorrow when I'm back from the pub
Re: Use JSON files as if they are Python modules
#17Why do all the comments act like this is bad? Seems fine to me. Explanation would be appreciated :)
You're changing the behavior of import. So if somebody else were to remove the seemingly unused `from jsonsempai import magic` the file would stop working as expected. Non obvious "magic" code like that tends to be frowned on in general, and especially in the python community
Re: Use JSON files as if they are Python modules
#18Re: Use JSON files as if they are Python modules
#19Earlier quoted context omitted.
You're changing the behavior of import. So if somebody else were to remove the seemingly unused `from jsonsempai import magic` the file would stop working as expected. Non obvious "magic" code like that tends to be frowned on in general, and especially in the python community
Is it be useful? Or there are some alternatives to import JSON as a module as easy as this one does?
import json
with open("foo.json") as f:
foo = json.load(f)
For strings: import json
bar = '{"foo": "bar"}'
foo = json.loads(bar)Re: Use JSON files as if they are Python modules
#20As a JavaScript developer for the past 5 years or so, when jumping into Python I certainly miss the simple require( ) which this seems to replicate into Python pretty well! Having said that I don't think that I would use it for serious things since this isn't really the Python way and I would like my code to be most understood by others. Neat though!
JSON stands for JavaScript Object Notation , not Python Object Notation. Furthermore "require" is "proprietary" to nodejs, ES2015 has a different module system and it will be the official js module system.