initializing yaml module in __init__.py - python

I'm using PyYAML, and would like to be able to use a string-concatenating constructor in my .yaml files.
This post shows how to add such constructors to PyYAML:
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
## register the tag handler
yaml.add_constructor('!join', join)
The above works when I enter it in a python terminal. However, I want to put the above in my_package's __init__.py file, so that I can do:
from my_package import yaml # my_package.__init__.py contains the above code
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")
However, this crashes with the message:
AttributeError Traceback (most recent call last)
<ipython-input-1-1107dafdb1d2> in <module>()
----> 1 import simplelearn.yaml
/home/mkg/projects/simplelearn/simplelearn/__init__.py in <module>()
----> 1 import yaml
2
3 def __join(loader, node):
4 '''
5 Concatenates a sequence of strings.
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc in <module>()
AttributeError: 'module' object has no attribute 'add_constructor'
What's going on? Why can't python find yaml.add_constructor?

Your loading the module yaml from the file:
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc
You either named one of your own files yaml.py, or you did have that file
before and renamed it, but forgot to remove the yaml.pyc. So you are not loading the PyYAML interpreter with import yaml.
The easiest way to verify is to include a temporary line after the import:
import yaml
print(yaml.__file__)
you should see something like .../site-packages/yaml/__init__.pyc.

Related

An idea of importing an user define python package

The structure needs for python 3.8+
That x.py contains x class with a 'display' method
concept one:
from p_abcd import a as A
''' call display '''
A.x.x().display()
Got an error
Traceback (most recent call last):
File "w.py", line 4, in
A.x.x().display()
AttributeError: module 'p_abcd.a' has no attribute 'x'
concept two:
import p_abcd.a as A
''' call display '''
A.x.x().display()
Got the same error
You can import only .py files. Not folders.
So you need something like
from p_abcd.a import x
x.display()

Python wont allow me to import .py files from same directory

So I'm just starting to learn Python, and I am learning classes and imports, but for some reason even when I follow the same code as my book say to do, I get a traceback error.
Traceback (most recent call last):
File "C:/Users/Programming/Desktop/Programs/EX40/main.py", line 1, in <module>
import objects.py
ModuleNotFoundError: No module named 'objects.py'; 'objects' is not a package
Here is both my Python files in which I'm trying to link:
main.py
import objects.py
print(MyStuff.tangerine)
objects.py
class MyStuff(object):
def __init__(self, arm):
self.tangerine = 'And now a thousand years between'
self.arm = arm
def apple(self):
print('I AM CLASSY APPLES!')
Try using
import objects
Because it takes py as a module in the objects file which does not exist
import objects.py is not a valid import
https://docs.python.org/3/reference/import.html
Try
from objects import MyStuff
Instantiating the class:
mystuff = MyStuff("arm value")
print(mystuff.tangerine)

Can't create instance of class from other file in Atom/Hydrogen

I am having problems with Hydrogen in Atom on MacOS when trying to create an instance of a class from another file/module. The code does work when run in the command-line, but not in Atom. I have already set the directory to start kernel in to "Current directory of the file", which enables me to create an object of that other file and use functions, but not classes.
Here is the code in the two respective files. Again, importing File2 is not the problem, neither is using functions from File2 in File1. It is only classes that don't work.
#File1
import File2
from File2 import MyClass
y=MyClass('test')
print(y.name)
#File2
class MyClass:
def __init__(self, x):
self.name=x
Running File1 gives me the error message, when run in Atom.
ImportError Traceback (most recent call last)
<ipython-input-92-444367378d7c> in <module>
----> 1 from File2 import MyClass
ImportError: cannot import name 'MyClass' from 'File2' (/Users/.../File2.py)

Error when importing python module from folders

I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.

How to add custom renames in six?

According to the documentation, six supports adding custom renames to six.moves:
six.add_move(item)
Add item to the six.moves mapping. item should be a MovedAttribute or
MovedModule instance.
And:
class six.MovedModule(name, old_mod, new_mod)
Create a mapping for six.moves called name that references different
modules in Python 2 and 3. old_mod is the name of the Python 2 module.
new_mod is the name of the Python 3 module.
However, this code yields an ImportError for me:
from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves.mock import MagicMock
When I run it on Python 3.4.2 using six 1.9.0 I get this error:
Traceback (most recent call last):
File "test_six_moves.py", line 2, in <module>
from six.moves.mock import MagicMock
ImportError: No module named 'six.moves.mock'
The builtin moves are working just fine. How do I get this to work?
You can't import the name from within the move. Use:
from __future__ import print_function
from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock
print(mock.MagicMock)
This will give you:
# Python 2
<class 'mock.MagicMock'>
# Python 3
<class 'unittest.mock.MagicMock'>
Note that importing from within a move works for the ones that ship with six. For example: from six.moves.configparser import ConfigParser works.
This piece of code (from six.py) is why:
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name)
In fact, if you ran the following (meddling with private attributes is of course not recommended), your import would work:
import six
mod = six.MovedModule('mock', 'mock', 'unittest.mock')
six.add_move(mod)
six._importer._add_module(mod, "moves." + mod.name)

Categories