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
Related
I would like to import a constant from an external file. I have two files in one directory.
constants.py file:
SOME_CONSTANT = 'something'
And import this into settings.py
import constants
someVariable = constants.SOME_CONSTANT
But pylint write that Module 'constants' has no 'SOME_CONSTANT' member
Can't really tell how you made your constants, but ideally you'd want to store them in your class.
#Constants.Py
class Province:
CITY = 'Toronto'
#Settings.Py
from Constants import Province
someVariable = Province.CITY
>>> 'Toronto'
Imagine I have a .env file that looks like this.
EARTH_SYNONYM1 = "World"
EARTH_SYNONYM2 = "Planet"
EARTH_SYNONYM3 = "Globe"
I've managed to load it into a namespace.
import json
from pathlib import Path
from types import SimpleNamespace
from dotenv.main import dotenv_values # dotenv package needs to be installed.
def json_to_python(json_str):
return json.loads(json_str, object_hook=lambda d: SimpleNamespace(**d))
dotenv_path = Path(".") / ".env"
dotenv_vars_list = dotenv_values(dotenv_path)
dotenv_vars_as_json = json.dumps(dotenv_vars_list)
dotenv_vars = json_to_python(dotenv_vars_as_json)
print(dotenv_vars)
Which prints
namespace(EARTH_SYNONYM1='World', EARTH_SYNONYM2='Planet', EARTH_SYNONYM3='Globe')
Now I can do things like
print(f"Hello {dotenv_vars.EARTH_SYNONYM1}")
Which prints
Hello World
What I would love to accomplish is turning this into a class module (I think).
I'd like to
import dotenv_vars
And then type
dotenv_vars.
and be presented with a list of auto-complete options.
Continuing this example, each of the EARTH_SYNONYMx would show as auto-complete options.
How can I make the namespace object provide auto-complete?
I always thought dotenv is a pretty silly library and overcomplicating something that is so simple. Load your vars into a module namespace with Python's import system.
import imp
dotenv_vars = imp.load_source('dotenv_vars', '.env')
I want to use https://github.com/bear/python-twitter/ and check API requests https://github.com/kevin1024/vcrpy or https://github.com/agriffis/vcrpy-unittest.
From lines 30:
https://github.com/bear/python-twitter/blob/master/twitter/api.py#L30
30: import requests
and later on:
res = requests.post(url='https://api.twitter.com/oauth2/token',
data={'grant_type': 'client_credentials'},
headers=post_headers)
# ... etc ...
Yet when doing something like:
from vcr_unittest import VCRTestCase
import vcr
import twitter
from django.conf import settings
class TwitterRetrievalAndStorageTests(VCRTestCase):
#vcr.use_cassette()
def test_recorded_session(self):
api = twitter.Api(
consumer_key=settings.TWITTER_CONSUMER_KEY,
consumer_secret=settings.TWITTER_CONSUMER_SECRET,
access_token_key=settings.TWITTER_ACCESS_KEY,
access_token_secret=settings.TWITTER_ACCESS_SECRET)
statuses = api.GetUserTimeline(screen_name='nntaleb')
for s in statuses:
print(s)
Not a cassette file is being created. Is there a way to do this with python-twitter?
VCRTestCase is built on top of vcr. It doesn't make much sense to use both simultaneously. If you remove the line #vcr.use_cassette(), you should see a cassette named TwitterRetrievalAndStorageTests.test_recorded_session.yaml (or json) in your cwd. If instead, you don't inherit from VCRTestCase and use #vcr.use_cassette(), the cassette name should be test_recorded_session.yaml and it should be in the same folder as your class.
In general, if you use both, I have noticed that vcr takes precedence over vcrpy-unittest but that is not consistently the case.
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
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)