Python module and __all__ - python

I trying to understand how to manage module with __all. For example, I have following structured code:
main.py
|=> /database
|=> __init__.py
|=> engine (with variables engine, session, etc.)
now I want to be able to import session and engine instances directly from database module like:
from database import session
I tried to add line __all__ = ['session'] or __all__ = ['engine.session'] to __init__py but when I trying to do import I've got an exception AttributeError: 'modile' object has not attribute 'engine.session'.
Is there any way to achieve wanted behavior?

Listing names in __all__ does not, by itself, import items into a module. All it does is list names to import from that module if you used from database import * syntax.
Import session into database/__init__.py:
from .engine import session

Related

How to mock an import within an import

So I am trying to test an api lookup with my mock data.
I am testing a method within transform.py that imports a module lookup
import lookup
col = lookup.ColFinder()
url = "xyz"
if col.is_present(url):
do this
lookup.py
import secdata
class ColFinder():
def is_present(url):
if url in secdata.CUSTOM_STUFF:
return secdata.CUSTOM_STUFF[url]
secdata.py
secdata.CUSTOM_STUFF=load("some_file")
I want to mock the JSON (file being loaded within secdata.CUSTOM_STUFF)
I have tried mocking using the unittest.mock with some custom config within tests/resources
CUSTOM_CONFIG = secdata.load(os.path.join(os.path.dirname(__file__),'/resources/custom_config.json'))
import mock
#mock.patch("transform.lookup.secdata.CUSTOM_STUFF" , return_value=CUSTOM_CONFIG)
def test_blah_blah(self, *_):
but this doesn't seem to load the file I am trying to reference. Please can someone help me mock this, point out what am I doing wrong.
Thank you in advance.

cannot import the module in Python

I have the following folder structure.
check_site
- test_site
-- views.py
- app2
- app3
- modules
-- url.py
-- usability.py
module ulr.py contains one class inside - Url.py
class URL:
...
module usability.py contains one class that inherit URL class
from url import URL
class Usability(URL):
...
And then I have a view.py where I neen to import class Usability
from modules.url import URL
from modules.usability import Usability
And here is a problem. It gives me an error
from url import URL
ModuleNotFoundError: No module named 'url'
I've tried to change the import in usability.py to
from modules.url import URL but in this case it gives the error in the usability.py
Unable to import modules.url
I've also tried
from .url import URL and from check_site.modules.url import URL But these also don't work
If someone knows how to fix it, please help
Well, the problem lies here because by default Python searches for the file in the current directory but the file u want to import is not in the same directory as your program.
You should try sys.path
# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')
import file
This should work in most cases.

Pylint reporting Cyclic Import on file without imports

So Pylint (1.4.3) is reporting a Cyclic Import and it doesn't make much sense.
First of all, the file that's report has no import statements.
Second of all no files import the reference file. a __init__.py file loads configuration values from development_config (file in question) but no files
import said file.
So why is Pylint giving me this warning?
Pylint warning
************* Module heart_beat.development_config
R: 1, 0: Cyclic import (heart_beat -> heart_beat.views -> heart_beat.models) (cyclic-import)
R: 1, 0: Cyclic import (heart_beat -> heart_beat.views) (cyclic-import)
development_config
""" -------------------------- DATA BASE CONFINGURATION --------------------"""
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
SQLALCHEMY_ECHO = False
""" -------------------------- Flask Application Config --------------------"""
THREADS_PER_PAGE = 8
VERSION = "0.1"
__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
#from register_assets import register_all
app = Flask(__name__, static_url_path='/static')
# the environment variable LIMBO_SETTINGS is set in runserver, run_unit_tests
# or limbo.wsgi.
def load_configs():
"""Take all configs found in development_config.py."""
app.config.from_pyfile("development_config.py", silent=False)
load_configs()
# global SQLAlchemy configuration
db = SQLAlchemy(app)
#Create and register all static asset bundles.
#register_all(app)
#NOTE: DON'T LISTEN TO YOUR IDE! heart_beat.views is used and required.
import heart_beat.views # views contains all URL routes, Importing sets routes.
def setup_db():
"""Database creation in a file rather then a statement for easier tests."""
db.create_all()
def teardown_db():
"""Database deletion in a file rather then a statement for easier tests."""
db.drop_all()
setup_db()
views.py
from flask import request
from . import app
from . import db
from . import models
from . import exceptions as ex
models.py
import datetime
from . import exceptions
from . import db
from . import app
I believe this is currently a bug in pylint. Things that require analysis over multiple modules (for example cyclic-import and duplicate-code detection) get thrown as refactors into the last-parsed module file. For me, this ended up being an empty __init__.py file that had both of these dropped into it.
Both of these refactor messages though contain the actual module names which are problematic:
For cyclic-import, the problematic modules are listed in the parenthesis
For duplicate-code, the problematic modules are listed on the following lines starting with ==
The grouping of these is not limited to the print-out of modules, it also effects the summary report % errors / warnings by module in which that final parsed file gets the counts for the refactors and none of the modules it actually concerns get any counts from them.

Reference another class in python

I'm just starting out with Python for Google App Engine. I have a file notifications.py, and in here, I will be creating User entities, which are specified in users.py. How can I do this? I've tried import users, but I get an error: NameError: global name 'User' is not defined
Oh, I just had this problem too! After you do:
import users
to get User you have to type users.User
Alternatively you could import it like:
from users import User
then reference it as just User but if you do it this way you'll have to list every bit from users that you want in the following format:
from users import User, Somthingelse, Somthing
If you're feeling super lazy and you don't want to type in any prefixes or list all the things you want, just type
from users import *
Instead of
import users
do
from users import User
# module.py
foo = "bar"
# main.py
import module
print foo # This will cause error because foo is not located in the current namespace
print module.foo # this will print "bar"
from module import foo # But you can import contents of module "module" in the current namespace
http://docs.python.org/tutorial/modules.html

Django - importing dynamically

I'm trying to do a dynamic import of a python module in django. I have two different apps that I want to import from, and I want to replace these import statements:
from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:
globals()[form]()
I tried following some of the instructions in this post: Dynamically import class by name for static access
and so I tried doing this:
theModule = __import__("app1.forms.App1ProfileForm")
but I'm getting an error that says No module named App1ProfileForm
EDIT:::
Ok I tried this code:
theModule = __import__("app1")
print theModule
theClass = getattr(theModule,'forms')
print theClass
theForm = getattr(theClass,'App1ProfileForm')
print theForm
theForm.initialize()
but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'
You don't want to do this. Imports are done when the relevant code is first executed - in the case of module-level imports, it's when the module itself is imported. If you're depending on something in the request, or some other run-time element, to determine what class you want, then this will not work.
Instead, just import them both, and get the code to choose which one you need:
from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
forms = {'app1': App1ProfileForm,
'app2': App2ProfileForm}
relevant_form = forms[whatever_the_dependent_value_is]
I don't quite know how you're generting the string to import. I'll assume you generate the whole "path". Try this:
def import_from_strings(paths):
ret = []
for path in paths:
module_name, class_name = path.rsplit('.', 1)
module = __import__(module_name, globals(), locals(), [class_name], -1)
ret.append(getattr(module, class_name))
return ret
Aren't you trying to import a class, and not a module ? I'm not an expert, but I think you must import the module using __import__, then select it's App1ProfileForm class with something like yourmodule.App1ProfileForm
I figured it out. Here's how to do it:
theModule = __import__(module_name+".forms") # for some reason need the .forms part
theClass = getattr(theModule,'forms')
theForm = getattr(theClass,form_name)
then to initialize:
theForm() or theForm(request.POST)

Categories