Does python support to import package - python

I am using Python 2.7, and have following code strucure
model
__init__.py
order.py
cart.py
That is, I define a package named model, and in this package, I define a module order, and I define a class in order.py
class MyOrder(object):
def __init__(self, name):
self.name = name
def getname(self):
return self.name
In the cart.py, the code is:
import model
x = model.order.MyOrder("Book")
print x.getname()
When I run it, it complains that AttributeError: 'module' object has no attribute 'order',
But the following is correct:
import model.order
x = model.order.MyOrder("Book")
print x.getname()
It looks that I can't import package (like import model) ?

If you want to have model automatically import order so it's available, you should do that in __init__.py. Simply put the following inside model/__init__.py:
from . import order
After that, you should be able to access model.order with just import model.

Related

How to access constant with class pointer in python - AUTH_USER_MODEL = 'django_restframework_2fa.User'

I have defined AUTH_USER_MODEL = 'django_restframework_2fa.User' in the settings.py file of Django application.
django_restframework_2fa is the name of the package and it has module named models where class User is defined.
Now, I want to access that User() class using AUTH_USER_MODEL constant. How can this be done?
I tried to access it like this settings.AUTH_USER_MODEL(**data) which should be equivalent to User(**data) but it doesn't work.
In python module can be imported using import_module() method of import importlib. Then to get the attributes of that module use method getattr() which takes two arguments module and attribute name.
This is how I have accomplished it -
def get_class(module_class_string):
"""
:param module_class_string: full name of the class to create an object of
:return: class
"""
module_name, class_name = module_class_string.rsplit(".", 1)
module_name = module_name + '.models'
module = importlib.import_module(module_name)
return getattr(module, class_name)

Get name of class for Attribute usage in Python Astroid / Pylint

I have the following files:
# in models.py
class User(object):
def __init__(self, name):
self.name = name
# in util.py
def get_user():
return User(name="tom")
# in views.py
from util import get_user
get_user().name
I want to detect all Attribute usages for the name attribute on the User model. So get_user().name would be flagged as one such usage, since get_user returns a role User object.
Is there an easy way to do this using Astroid only preferably?

AttributeError: module has no attribute while avoiding cyclic reference error

I would like to create small app using M-VC pattern in python. I am using PyCharm and my folder structure looks like this.
To avoid problem with cyclic references I am using import not from ... import.
Program executes without error when my viewController.py looks like this:
import model
class ViewController:
def initialize(self, mod):
self.model = mod
Adding model.Model expression inside initialize method results with an error: AttributeError: module 'model' has no attribute 'Model' Why it works in model.py with viewController.ViewController? And what is wrong?
[new]viewController.py
import model
class ViewController:
def initialize(self, mod:model.Model):
self.model = mod
Back/__init_.py
import model
import viewController
mModel = model.Model()
mVC = viewController.ViewController()
mModel.initializeApp(mVC)
model.py
import viewController
class Model():
def initializeApp(self, viewContr: viewController.ViewController):
self.vc = viewContr
self.vc.initialize(self)

Import Python Module to Class Variable

I am trying to import a class in Python and after importing the class set a class variable as the imported class. I have searched Google as well as stackoverflow for an answer to this, but have not been able to find one.
For Example:
DB.py:
class DB:
def __init__(self):
#init sets up the db connection
def FetchAll():
#Fetchall fetches all records from database
Ex.py:
class Ex:
def __init__(self):
import DB.py as DB
self.db = DB.DB()
def FetchAll(self):
result_set = self.db.FetchAll()
I would like to be able to access the FetchAll() in the DB class from Ex class through a variable. I know in PHP this is possible by using "Protected" keyword in a class.
Thank you for any help you can offer.
Just
import DB
You provide a module name (that can be located given the current module search path), not a file name.
Check the tutorial for a beginner’s overview of how modules and imports work.
You can either just use the name of the class as the class variable:
import DB
class Ex:
# define methods
# call FetchAll with DB.FetchAll()
Or create a new class variable with the 'as' key:
import DB as x
class Ex:
# define methods
# call FetchAll with x.FetchAll()
And like the others are saying, import all modules at the top of the script.

Python class method throws AttributeError

I'm having issues getting a class method to run in Flask.
In models/User.py:
from mongoengine import *
class User(Document):
first_name = StringField()
last_name = StringField()
...
def __init__(self, arg1, arg2, ...):
self.first_name = arg1
self.last_name = arg2
...
#classmethod
def create(self, arg1, arg2, ...):
#do some things like salting and hashing passwords...
user = self(arg1, arg2, ...)
user.save()
return user
In the main application python file:
from models import User
...
def func():
...
#Throws "AttributeError: type object 'User' has no attribute 'create'"
user = User.create(arg1, arg2, ...)
Shouldn't I be able to call create on the User class without instantiating a User object? I'm using Python 2.7.2, and I also tried the non-decorator syntax of using create = classmethod(create), but that didn't work. Thanks in advance!
EDIT: I found one issue: that the models folder did not contain an __init__.py file, so it wasn't a module, so from models import User was not actually importing the file I wanted it to. It did not give me an error from before because I used to have a models.py module in the same directory as the application python script, but after deleting it I never deleted the corresponding .pyc file. Now, I'm getting the error AttributeError: 'module' object has no attribute 'create' instead of what I had before, but I'm certain it is importing the correct file now.
EDIT2: Solved. I then changed the import to from models.User import User and It's hitting the method now.
The issue was twofold:
The User.py file was in the models/ folder, meaning that my import was actually looking for the User class in the models.py file, which no longer existed but still was being imported without error because the models.pyc file was still around
The import was incorrect for importing within a directory. it should have been from models.User import User, so long as the models/ folder is a module, so all I needed to do then was touch models/__init__.py.
>>> class foo(object):
... def __init__(self):
... pass
... #classmethod
... def classmethod(cls):
... return 0
...
>>> a = foo()
>>> a.classmethod()
0
>>>

Categories

Resources