Why doesn't this Python work? Simple Oop - python

class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
I created a file "abc.py" and put above in it.
>>> import abc
>>> d = abc.UserDict()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'UserDict'

Most certainly you are importing the Python abc module for abstract base classes instead of your own abc.py. Better choose a different name for your module.
Edit: Of course it is possible to have your own module with the same name as a built-in module and to import it. You have to make sure that your module is in the interpreter's working directory or set the Python path correctly. But it is much easier to avoid the name clash -- in particular in this case, where you presumably don't care about the module's name anyway.

Related

how to modify python's built in modules

I want to add functions to python's built in module. As a example, there is no find function in list. I want to add it. There is some other functions I want to add. Can somebody please tell me how can I do that? Is their any way I can do that?
Adding functions to the builtins module is simple:
import builtins
builtins.find = my_find_function
But the built in classes are usually immutable, so they cannot be changed.
>>> list.hello = "hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'list'

python get module name that declared a variable

so classes in python can tell you where they were defined:
# module a.py
class Something:
pass
from a import SomeClass
print(f"name: {SomeClass.__name__}, module: {SomeClass.__module__}")
# name: SomeClass, module: a
I want to know if it is possible to get the module that declared a variable, rather than a class.
# module a.py
SOME_LIST = [1,2,3]
from a import SOME_LIST
# something like this:
print(SOME_LIST.__module__)
# Traceback (most recent call last):
# File "b.py", line 3, in <module>
# print(SOME_LIST.__module__)
# AttributeError: 'list' object has no attribute '__module__'
The use case is that I need to crawl a complicated structure of nested classes and lists across many files and I need to generate namespaces for classes and variables found in this structure.

Import __module__ python: why the underscores?

I am new to Python,
and have started working on code written by others.
In the source of packages downloaded from Pypi I have noticed the use of
import __module__
to use functions and classes defined in the src folder of packages.
Is this common practice? I actually can't really understand this kind of syntax,
could you explain it to me or send me to some reference?
It's a python convention for some builtin objects. From PEP8:
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
But in the end it is not a "kind of syntax" to understand or not, __module__ is just a name with underscores in it. It's different from and completely unrelated to module.
An example to show you it's just a name:
>>> __foo__ = 42
>>> print foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> print _foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_foo' is not defined
>>> print __foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__foo' is not defined
>>> print __foo__
42
>>> type(__foo__)
<type 'int'>
Nothing inherently special about it.
Without more info about where you saw this though, it's hard to say what the author's intention was. Either they are importing some python builtins (e.g. from __future__ import...) or they are ignoring PEP8 and just named some objects in this style because they think it looks cool or more important.

In python after I import a module is there a way of finding what physical file it was loaded from?

Something's acting up in my math package I think and I want to ensure I'm loading the correct module. How do I check the physical file location of loaded modules in python?
Use the __file__ attribute:
>>> import numpy
>>> numpy.__file__
'/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'
Note that built-in modules written in C and statically linked to the interpreter do not have this attribute:
>>> import math
>>> math.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
An other way to obtain the path to the file is using inspect.getfile. It raises TypeError if the object passed is a built.in module, class or function.
On a side note, you should avoid using names that conflict with language built-ins or standard library modules. So, I'd suggest you to rename your math package to something else, or, if it is part of a package like mypackage.math, to avoid importing it directly and use mypackage.math instead.
Check themodule.__file__.
import urllib
print urllib.__file__
>>> import math
>>> math.__file__
'/usr/lib/python2.7/lib-dynload/math.so'

NameError when using reload()

I've got file named recommend.py. It has a dict data named critics.
When I try to reload it in the interpreter it gives the following error:
>>> from recommend import critics
>>> reload(recommend.py)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'recommend' is not defined
>>>
I'm new to python. Please help me.
recommend.py is parsed as recommend . py which means that python looks for an object bound to the name recommend and then tries to get the py attribute from it. That doesn't work because you don't have an object named recommend in the current namespace and because even if you did have an object bound to that name, it probably wouldn't have an attribute py.
Of course, you'll need to give reload an actual module object. Something more like:
import recommend
reload(recommend)
reload() takes a module object, not a filename:
import recommend
reload(recommend)

Categories

Resources