Relative Imports - django

I'm reading Two Scoops Django Best Practices to make my coding style improve. I'm in relative imports and here is the sample code to make it reusable.
Old Way:
from cones.foo import bar
New way:
from .foo import bar
The code above is for cones app, what if I call the other model in other app? Do I have to put like this:
from .foo import bar
from .other import sample
OR
from .foo import bar
from test.other import sample
What is the correct way?

I usually use imports like this only for one reason
from .foo import bar
from .other import sample
The reason being
If Tomorrow, my module name changes from say 'test' to 'mytest' then the code does not require a refactoring. The code works without breaking.
Update
All imports starting with a '.' dot, only works within that package.
Cross package imports need require the whole path.

If test is another app,
from .other import sample
wont work.
Update:
You can only use relative imports when you're importing from the same app.
Inside test app
from .other import sample
will work. But you'll still need the complete form
from cones.foo import bar
if you import method defined in foo from test app.
So answering your question the second way is the correct way.

Related

Error when writing remix unit tests: URL not parseable: remix_accounts.sol

I'm writing unit test in remix-ide and I want to call functions from different addresses within a single test.
The remix-tests Github page says that you can use import "remix_accounts.sol";, but I get URL not parseable: remix_accounts.sol. How to fix that? Or maybe there's another way to call from various addresses?
Import files with relative paths, in your case, modify the following
import "remix_accounts.sol";
to
import "./remix_accounts.sol";
Also, notice that remix doesn't allow import from an ancestor directory, for example:
import "../remix_accounts.sol";

Calling a function from inside a sub-package the correct way in python

I have been trying to understand how to properly call a function from inside a subpackage in python. I wanted to be able to call the function the way I call, for example, function isfile from os package, with os.path.isfile(). I made a test package with a structure like this:
sandbox/
-- __init__.py
-- acid.py
-- pack1/
-- __init__.py
-- fly/
-- __init__.py
-- plane.py
-- by/
-- pack2/
There are only two modules there, acid.py and plane.py. Both of them contain just a function, e.g. plane.py is
"""plane module"""
def plane(x):
x=x+4
return x
To use the function in my test.py code, I put
import pack1
in sandbox/__init__.py
import fly
in sandbox/pack1/__init__.py, and
from plane import plane
in sandbox/pack1/fly/__init__.py
The test code was then:
import sandbox
print sandbox.pack1.fly.plane(3)
Is this the right way to import a function from a subpackage, or I'm misunderstanding things?
What you did certainly works, although there are several worthwhile changes to make.
First, a note about importing from packages: importing a module is semantically distinct from accessing something in a module, even though from xml import sax and from datetime import date are syntactically equivalent. It's impossible to import only part of a module, so that
import datetime
datetime.date.today() # OK: date is a class
is guaranteed to work. However, it is possible to import a package but not the modules it contains. This is a good thing for efficiency, but it does mean that
import xml
xml.sax.parse(...) # AttributeError: 'module' object has no attribute 'sax'
is an error. Unfortunately, such errors often go uncaught because some other code has already imported sax, making it available to any other code that imports xml. (The word "from" in from xml import sax is referring to the complete package on disk, not the module object xml — on which it stores the new module as an attribute!)
As an aside, note that your example of os.path is an abberation: writing
import os
os.path.isfile(...)
works, but only because os.path is not actually a module but an alias for one of posixpath, ntpath, etc. (It then gets installed in sys.modules to allow import os.path as if it were a normal module.)
As such, for a package there is a set of public modules that the user must be aware of (because they must be imported by name to be available); the rest are internal modules that the package loads itself when necessary. If a package contains no public modules, it is irrelevant to the user that it is a package (for example, importlib with its one public function is actually implemented as a package for forward compatibility with Python 3).
Now for the suggestions:
Implicit relative imports are deprecated: write from . import pack1 instead of just import pack1 in sandbox/__init__.py, for instance.
The from plane import plane (or from .plane import plane, following the above point) is problematic because it overwrites the reference to the module plane.py with a reference to the function. Instead:
Define the user-visible entry points (like plane()) directly in their package's __init__.py, importing internal functions from private modules as needed, or
Rename the module (to plane_module.py or so) to avoid the collision.
However, it's not generally a good idea to have a package automatically import its public modules anyway: it forces the client to pay for loading unused parts of the package, and it blurs the distinction between public modules and simple nested names. Instead, write client code like
import sandbox.pack1.fly
print sandbox.pack1.fly.plane(3) # the same line you had
or
from sandbox.pack1 import fly
print fly.plane(3)
if you want to avoid repeating sandbox.pack1.
It is often suggested that __init__.py be entirely empty, and in Python 3.3 it became possible to define packages without any __init__.py at all (which by necessity "makes it empty"). This policy does more than the "no automatic import" suggestion in that it precludes loading things from private modules (like plane).
There are sometimes good reasons to have a non-empty __init__.py; for example, it allows reorganzing an existing module into a package without breaking its clients. I personally see no reason to especially restrict its contents; for further discussion see What is __init__.py for?.
The init.py file makes a folder as a package so that you can import it to python prompt. If you just want to call the function "plane" from your file plane.py, add the absolute path of plane.py file to your PYTHONPATH and call the funtion as shown below.
>>> import sys
>>> sys.path.append("D:\\sandbox\\pack1\\fly")
>>> import plane
>>> print plane.__doc__
plane module
>>> print plane.plane(3)
7
If you want all the packages under "sandbox" folder to be used in your script just add the absolute path of "sandbox" folder to your PYTHONPATH and call the funtion as shown below.
>>> import sys
>>> sys.path.append("D:\\")
>>> from sandbox.pack1.fly import plane
>>> print plane.plane(3)
7
You can also import the "plane.py" module and call the function "plane" as shown below:
>>> import sys
>>> sys.path.append("D:\\")
>>> import sandbox.pack1.fly.plane
>>> print sandbox.pack1.fly.plane.plane(3)
7

Ember.js how to extend ember-cli-addon component

I'm using Stripe in my Ember app, and I've set it up following the instructions here :
https://github.com/sweettooth/ember-cli-stripe
so as my app stands right now, the ember-checkout component installed via this addon is in
myappname/node_modules/ember-cli-stripe/app/components/stripe-checkout
Now, I want to create a new component "my-stripe-checkout", and have it extend the default ember-cli-stripe component.
I have tried:
import StripeCheckoutComponent from '../node_modules/ember-cli-stripe/app/components/stripe-checkout';
import StripeCheckoutComponent from 'ember-cli-stripe/app/components/stripe-checkout';
import StripeCheckoutComponent from 'app/components/stripe-checkout';
in my my-stripe-checkout component that I generated via Ember g, but to no avail.
I always get an error of this pattern:
Could not find module `app/components/stripe-checkout` imported from `myappname/components/my-stripe-checkout`
And as per this question:
How to extend an ember-cli addon?
I tried doing
import StripeCheckoutComponent from 'ember-cli-stripe/components/stripe-checkout';
but same error.
I've also tried both :
export default Ember.StripeCheckoutComponent.extend({ })
and
export default StripeCheckoutComponent.extend({})
to each iteration of the imports, but nothing seems to work. How do I extend an ember-cli-addon component?
Well, you need to understand that the app directory of an addon is directly merged with your app structure. Its best practice to keep all code in the addon directory, however ember-cli-stripe hasn't done this. So from inside of your components directory you basically can do
import StripeCheckoutComponent from './stripe-checkout';
or
import StripeCheckoutComponent from 'YourAppName/components/stripe-checkout';
If the component would be in the addon directory of the addon the correct way would be:
import StripeCheckoutComponent from 'ember-cli-stripe/components/stripe-checkout';

Only in py.test file, usage of a nested(word?) imported variable/function fails with NameError

I have a python structure like this:
mymodule/
globalconfig.py # variables to set environment, etc
work.py # has: from mymodule.globalconfig import *
__init__.py
tests/
testspart1/
test_work.py # has: from mymodule.work import *
From inside work.py, all is well and I can access my global config variables and functions.
From inside test_work.py, I cannot access those variables, even if I add a second import,
from mymodule.globalconfig import *
Why is this? I wanted to use the same syntax as used in my modules.
thank you!
I am using py2.7 and, to get nice rspec-style outputs and verbose diffs,
pytest --spec -vv
Ref;
1.This answer reminded me I could use another format of import. If there are no other answers I will post my workaround. how to share a variable across modules for all tests in py.test
The import syntax that worked for me was directly importing the nested python file in addition to importing the file under test.
from mymodule.work import *
import mymodule.globalconfig as myconfigs
I assume it's a name clash or import circularity issue, but I could not figure out what the problem was. It took me a while so I wanted to be sure to post the solution for future me and others.

import java.util.regex fails

I get an error when attempting to import the java.util.regex (specifically added the line to figure out that the error is in the import as I previously only had import java.util.*).
find_glycopeps.java:5: cannot find symbol
symbol : class regex
location: package java.util
import java.util.regex; // Should be redundant...
<some more messages about not recognising Pattern and Matcher, which are classes of the regex package>
As far as I am aware, the regex is a 'core' library. I am assuming that since import java.io.* works that the native method of keeping track of where libraries are should be working so I am quite puzzled how this has occured.
PS: I have to note that I have tested some java compilers over the weekend to find 1 that I like and re-installed a 'clean' openjdk-6 this morning, this is probably where the problems originate from but not sure how to proceed.
Cheers
EDIT (SOLVED): .. I will definitely go hide in shame now, thank you all for pointing out the truly silly mistake
.
Your import is defined wrong.
You'll either need to provide explicit imports of each class, as so:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Or do
import java.util.regex.*;
You're trying to import a package, you need the * meta-character for that.
If you read the message the compiler gives you, it says it can't find Class regex.
You can't import a package. You import a class, or all classes in a package:
import java.util.regex.*;
Packages are organized in a tree, but import is not recursive. Importing java.util.* only imports classes in java.util, but not classes from sub-packages.
You need to write either:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
or else:
import java.util.regex.*;
You can't just import java.util.regex, without the asterisk, since that's a package; it would be like importing java.io.