I want to write a custom json module for my team,
First I created a 'json.py' file under the folder(namespace) 'dqa_fileio/config'
so when others want to use my module, it should be called by import dqa_fileio.config.json
Then, I want to creates a read_file method to load a json file
But I got AttributeError: 'module' object has no attribute 'load'
I think that because the file_name is called json.py,
But I want to keep the filename, is there anyway like Ruby that I can open a class to extend it's ability ? But it seems the json is a folder(namespace) not a class ? Please correct me if any wrong concept. Thanks
json.py (under the namespace dqa_fileio/config)
import json
class Json(object):
def __init__(self):
pass
def read_file(self, file_name):
return json.load(open(file_name, 'r'))
if __name__ == '__main__':
Json().read_file(sys.argv[1])
That won't work because how do you think python is supposed to know which one to choose?
You have to pick a different name, as long as you want import json to import the correct module.
Look here for more information on the same type of question.
The only other thing I would suggest is to use a package.
Put your json.py module in some kind of package.
e.g:
common
|-__init__.py
|-json.py
Put common in your PYTHONPATH and/or package it up nicely with an appropriate setup.py which your team can install and use in their projects.
Then import it like:
from common import json
See: https://docs.python.org/2/tutorial/modules.html
The problem is that python thinks import json is just importing itself, and your class has no load method. The only way to get around this is to change your file name, or use some very unpythonic circular imports.
Related
I have defined several classes in a single python file. My wish is to create a library with these. I would ideally like to import the library in such a way that I can use the classes without a prefix (like mylibrary.myclass() as opposed to just myclass() ), if that's what you can call them, I am not entirely sure as I am a beginner.
What is the proper way to achieve this, or the otherwise best result? Define all classes in __init __? Define them all in a single file as I currently have like AllMyClasses.py? Or should I have a separate file for every class in the library directory like FirstClass.py, SecondClass.py etc.
I realize this is a question that should be easy enough to google, but since I am still quite new to python and programming in general I haven't quite figured out what the correct keywords are for a problem in this context(such as my uncertainty about "prefix")
More information can be found in the tutorial on modules (single files) or packages (when in a directory with an __init__.py file) on the python site.
The suggested way (according to the style guide) is to spell out each class import specifically.
from my_module import MyClass1, MyClass2
object1 = MyClass1()
object2 = MyClass2()
While you can also shorten the module name:
import my_module as mo
object = mo.MyClass1()
Using from my_module import * is recommended to be avoided as it can be confusing (even if it is the recommended way for some things, like tkinter)
If it's for your personal use, you can just put all your classes Class1, Class2, ... in a myFile.py and to use them call import myFile (without the .py extension)
import myFile
myVar1 = myFile.Class1()
myVar2 = myFile.Class2()
from within another script. If you want to be able to use the classes without the file name prefix, import the file like this:
from myFile import *
Note that the file you want to import should be in a directory where Python can find it (the same where the script is running or a directory in PYTHONPATH).
The _init_ is needed if you want to create a Python module for distribution. Here are the instructions: Distributing Python Modules
EDIT after checking the Python's style guide PEP 8 on imports:
Wildcard imports (from import) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools
So in this example you should have used
from myFile import Class1, Class2
I'm building a Python module for a fairly specific purpose. What I'd like to do with this is get more functionality behind importing things from it.
I'd like to have a setup by which saying from my_module import foo would run a function and pass the string "foo". This function would return the object that should be imported.
For example, maybe I want to make a cloud-based import system. I'd like to store community scripts in the cloud, and then download them when a user tries to import them.
Maybe I use the code from cloud import test_module. This would check a cache to decide whether test_module had been downloaded. If so, it would return that module. If not, it would download the module before importing it.
How can I accomplish something like this in Python, by which a dynamic range of submodules could be seamlessly imported from the cloud?
Full featured support for what you ask probably requires a bunch of complicated code using importlib and hooking into various parts of the import machinery. However, a more limited solution can be implemented with just a single custom class that pretends to be a module.
When you import a module, Python first checks in the sys.modules dictionary to see if the module is a key. If so, it returns the value associated with the key. It does this regardless of what the value is, so you can put any kind of object in sys.modules and Python will treat it like a module. A module's code can even replace its own entry in sys.modules, and the replacement will be used even the first time it is imported!
So, to implement your fancy module that downloads other modules on demand, replace the module itself with an instance of a custom class, and write that class a __getattr__ or __getattribute__ method that does the work you want.
Here's a trivial example module that returns a string for any attribute you look for in it. The string will always be the same as the requested attribute name. In your code, you'd want to do your fancy web-cache lookups and downloading, and then return the fetched module object instead of just returning a string.
class FakeModule(object):
def __getattribute__(self, name):
return name
import sys
sys.modules[__name__] = FakeModule()
On my system I've saved that as fakemodule.py. Now if I do from fakemodule import foo, I get foo with the value 'foo' in my local namespace.
Note that this only works for one level deep imports. If you do from fakemodule.subpackage import name it will not work because there's no fakemodule.subpackage entry in sys.modules.
I have a dictionary of addresses with their usernames and passwords listed that looks something like this:
address_dict = {'address1':{'username':'abc', 'password':'123'}, 'address2':{'username':'xyz', 'password':'456'}}
Is there a way to make this dictionary accessible for multiple scripts to read from and possibly write to? Like save it as seperate python file and import it or something?
Yes, you can do just that:
# module.py
address_dict = {'address1':{'username':'abc', 'password':'123'}, 'address2':{'username':'xyz', 'password':'456'}}
# main.py
import module
print(module.address_dict)
If you don't like the module. prefix, you could import the dictionary like so:
from module import address_dict
print(address_dict)
To access it and modify it at runtime, you can just define it in a module and then import it. But if you want your changes to be persistent (i.e. see the changed version next time you run the script) you need something else, like a database.
The simplest to use in this case would probably be the shelve module, which is based on pickle. You can also use pickle itself if you wish.
take a look at pickle :)
http://docs.python.org/2/library/pickle.html
You can use it to dump objects to files and also to read them back in with any other python script.
I have a situation where users can pick another method from another clases and use it in thier own class using the .im_func. i give an example below
import foo1
import foo2
foo1.ClassX.methodX = foo2.ClassX.methodX.im_func
Where methodX could be implemented differently in both modules.
When i instantiate the object say foo1.Class(), methodX from modulefoo2` is used.
My problem is how to save the changes made maybe as foo3.py to a new source code file.
saving it as new py could be a problem but you can easily use serialization for it (pickle module)
see: http://docs.python.org/library/pickle.html
The source code can be retrieved with inspect module. However, the problem with that is, that it's the original source code, not source code of dynamically modified object.
Have you considered using parser combined with the aforementioned inspect to do this? In this situation it might be better to simply go with text processing rather than attempting to use imported modules.
EDIT: An example of using the parser to print the file:
with open('foo1.py','r') as fh:
st = parser.suite(fh.read())
src1 = parser.st2list(st)
with open('foo2.py','r') as fh:
st = parser.suite(fh.read())
src2 = parser.st2list(st)
You'd have to then do some tricky programming to merge the methods from the source code and write it to a file. But then again I have the strange feeling I'm not quite understanding the question...
im working on some basic python stuff within the google app engine and I was unable to figure out the correct way to structure my handlers.
/main.py
/project/handlers/__init__.py
/project/handlers/AccountHandler.py
the AccountHandler is basically a class
class AccountHandler(webapp.RequestHandler):
when im using from project.handlers import AccountHandler
python always give me a
TypeError: 'module' object is not callable
how do i have to name/import/structure my classes?
cheers,
Martin
To quote from the docs:
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
The AccountHandler you are importing is the module /project/handlers/AccountHandler.py in this case. The file AccountHandler.py is not callable, and the interpreter tells you this. To call the class you defined in your file just use:
from project.handlers.AccountHandler import AccountHandler
# Alternately
# from project.handler import AccountHandler
# AccountHandler.AccountHandler() # will also work.
You need to rename init.py to __init__.py