title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 8,201,368 | <p>You could also enforce a class to be static using metaclass.</p>
<pre><code>class StaticClassError(Exception):
pass
class StaticClass:
__metaclass__ = abc.ABCMeta
def __new__(cls, *args, **kw):
raise StaticClassError("%s is a static class and cannot be initiated."
% cls)
class MyClass(StaticClass):
a = 1
b = 3
@staticmethod
def add(x, y):
return x+y
</code></pre>
<p>Then whenever by accident you try to initialize <strong>MyClass</strong> you'll get an StaticClassError.</p>
| 5 | 2011-11-20T12:06:23Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 9,613,563 | <p>One special thing to note about static properties & instance properties, shown in the example below:</p>
<pre><code>class my_cls:
my_prop = 0
#static property
print my_cls.my_prop #--> 0
#assign value to static property
my_cls.my_prop = 1
print my_cls.my_prop #--> 1
#access static property thru' instance
my_inst = my_cls()
print my_inst.my_prop #--> 1
#instance property is different from static property
#after being assigned a value
my_inst.my_prop = 2
print my_cls.my_prop #--> 1
print my_inst.my_prop #--> 2
</code></pre>
<p>This means before assigning the value to instance property, if we try to access the property thru' instance, the static value is used. <strong>Each property declared in python class always has a static slot in memory</strong>.</p>
| 6 | 2012-03-08T06:06:05Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 15,117,875 | <p>The best way I found is to use another class. You can create an object and then use it on other objects.</p>
<pre><code>class staticFlag:
def __init__(self):
self.__success = False
def isSuccess(self):
return self.__success
def succeed(self):
self.__success = True
class tryIt:
def __init__(self, staticFlag):
self.isSuccess = staticFlag.isSuccess
self.succeed = staticFlag.succeed
tryArr = []
flag = staticFlag()
for i in range(10):
tryArr.append(tryIt(flag))
if i == 5:
tryArr[i].succeed()
print tryArr[i].isSuccess()
</code></pre>
<p>With the example above, I made a class named <code>staticFlag</code>.</p>
<p>This class should present the static var <code>__success</code> (Private Static Var).</p>
<p><code>tryIt</code> class represented the regular class we need to use.</p>
<p>Now I made an object for one flag (<code>staticFlag</code>). This flag will be sent as reference to all the regular objects.</p>
<p>All these objects are being added to the list <code>tryArr</code>.</p>
<hr>
<p>This Script Results:</p>
<pre><code>False
False
False
False
False
True
True
True
True
True
</code></pre>
| 1 | 2013-02-27T17:00:43Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 15,644,143 | <p>When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed. </p>
<ul>
<li>CLASSNAME.var is static variable</li>
<li>INSTANCENAME.var is not static variable. </li>
<li>self.var inside class is not static variable. </li>
<li>var inside the class member function is not defined.</li>
</ul>
<p>For example:</p>
<pre><code>#!/usr/bin/python
class A:
var=1
def printvar(self):
print "self.var is %d" % self.var
print "A.var is %d" % A.var
a = A()
a.var = 2
a.printvar()
A.var = 3
a.printvar()
</code></pre>
<p>The results are</p>
<pre><code>self.var is 2
A.var is 1
self.var is 2
A.var is 3
</code></pre>
| 2 | 2013-03-26T17:56:19Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 24,553,443 | <p>In regards to this <a href="http://stackoverflow.com/a/68672/717357">answer</a>, for a <em>constant</em> static variable, you can use a descriptor. Here's an example:</p>
<pre><code>class ConstantAttribute(object):
'''You can initialize my value but not change it.'''
def __init__(self, value):
self.value = value
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, val):
pass
class Demo(object):
x = ConstantAttribute(10)
class SubDemo(Demo):
x = 10
demo = Demo()
subdemo = SubDemo()
# should not change
demo.x = 100
# should change
subdemo.x = 100
print "small demo", demo.x
print "small subdemo", subdemo.x
print "big demo", Demo.x
print "big subdemo", SubDemo.x
</code></pre>
<p>resulting in ...</p>
<pre><code>small demo 10
small subdemo 100
big demo 10
big subdemo 10
</code></pre>
<p>You can always raise an exception if quietly ignoring setting value (<code>pass</code> above) is not your thing. If you're looking for a C++, Java style static class variable:</p>
<pre><code>class StaticAttribute(object):
def __init__(self, value):
self.value = value
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, val):
self.value = val
</code></pre>
<p>Have a look at <a href="http://stackoverflow.com/a/102062/717357">this answer</a> and the official docs <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow">HOWTO</a> for more information about descriptors. </p>
| 1 | 2014-07-03T12:14:47Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 27,568,860 | <h2>Static and Class Methods</h2>
<p>As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:</p>
<pre><code>class Test(object):
#regular instance method:
def MyMethod(self):
pass
#class method:
@classmethod
def MyClassMethod(klass):
pass
#static method:
@staticmethod:
def MyStaticMethod():
pass
</code></pre>
<p>As usual, the first argument to <code>MyMethod()</code> is bound to the class instance object. In contrast, the first argument to <code>MyClassMethod()</code> is <em>bound to the class object itself</em> (e.g., in this case, <code>Test</code>). For <code>MyStaticMethod()</code>, none of the arguments are bound, and having arguments at all is optional. </p>
<h2>"Static Variables"</h2>
<p>However, implementing "static variables" (well, <em>mutable</em> static variables, anyway, if that's not a contradiction in terms...) is not as straight forward. As millerdev <a href="http://stackoverflow.com/a/69067/2437514">pointed out in his answer</a>, the problem is that Python's class attributes are not truly "static variables". Consider: </p>
<pre><code>class Test(object):
i = 3 #This is a class attribute
x = Test()
x.i = 12 #Attempt to change the value of the class attribute using x instance
assert x.i == Test.i #ERROR
assert Test.i == 3 #Test.i was not affected
assert x.i == 12 #x.i is a different object than Test.i
</code></pre>
<p>This is because the line <code>x.i = 12</code> has added a new instance attribute <code>i</code> to <code>x</code> instead of changing the value of the <code>Test</code> class <code>i</code> attribute. </p>
<p><em>Partial</em> expected static variable behavior, i.e., syncing of the attribute between multiple instances (but <strong>not</strong> with the class itself; see "gotcha" below), can be achieved by turning the class attribute into a property:</p>
<pre><code>class Test(object):
_i = 3
@property
def i(self):
return self._i
@i.setter
def i(self,val):
self._i = val
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting and setting i) ##
class Test(object):
_i = 3
def get_i(self):
return self._i
def set_i(self,val):
self._i = val
i = property(get_i, set_i)
</code></pre>
<p>Now you can do:</p>
<pre><code>x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # no error
assert x2.i == 50 # the property is synced
</code></pre>
<p>The static variable will now remain in sync <em>between all class instances</em>. </p>
<p>(NOTE: That is, unless a class instance decides to define its own version of <code>_i</code>! But if someone decides to do THAT, they deserve what they get, don't they???)</p>
<p>Note that technically speaking, <code>i</code> is still not a 'static variable' at all; it is a <code>property</code>, which is a special type of descriptor. However, the <code>property</code> behavior is now equivalent to a (mutable) static variable synced across all class instances. </p>
<h2>Immutable "Static Variables"</h2>
<p>For immutable static variable behavior, simply omit the <code>property</code> setter:</p>
<pre><code>class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
i = property(get_i)
</code></pre>
<p>Now attempting to set the instance <code>i</code> attribute will return an <code>AttributeError</code>: </p>
<pre><code>x = Test()
assert x.i == 3 #success
x.i = 12 #ERROR
</code></pre>
<h2>One Gotcha to be Aware of</h2>
<p>Note that the above methods only work with <em>instances</em> of your class - they will <strong>not</strong> work <em>when using the class itself</em>. So for example: </p>
<pre><code>x = Test()
assert x.i == Test.i # ERROR
# x.i and Test.i are two different objects:
type(Test.i) # class 'property'
type(x.i) # class 'int'
</code></pre>
<p>The line <code>assert Test.i == x.i</code> produces an error, because the <code>i</code> attribute of <code>Test</code> and <code>x</code> are two different objects. </p>
<p>Many people will find this surprising. However, it should not be. If we go back and inspect our <code>Test</code> class definition (the second version), we take note of this line: </p>
<pre><code> i = property(get_i)
</code></pre>
<p>Clearly, the member <code>i</code> of <code>Test</code> must be a <code>property</code> object, which is the type of object returned from the <code>property</code> function. </p>
<p>If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the <code>property</code> object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO). </p>
<p>I present a solution to the above 'gotcha' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why <code>assert Test.i = x.i</code> causes an error. </p>
<h2><em>REAL, ACTUAL</em> Static Variables - <code>Test.i == x.i</code></h2>
<p>I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works. </p>
<p><strong>Emulating static variable behavior of other languages using a metaclass</strong></p>
<p>A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the "new style" classes post Python 2.3 I believe) is <code>type</code>. For example: </p>
<pre><code>type(int) # class 'type'
type(str) # class 'type'
class Test(): pass
type(Test) # class 'type'
</code></pre>
<p>However, you can define your own metaclass like this: </p>
<pre><code>class MyMeta(type): pass
</code></pre>
<p>And apply it to your own class like this (Python 3 only):</p>
<pre><code>class MyClass(metaclass = MyMeta):
pass
type(MyClass) # class MyMeta
</code></pre>
<p>Below is a metaclass I have created which attempts to emulate "static variable" behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable". </p>
<p>A catalog of the "static variables" is stored in the <code>StaticVarMeta.statics</code> attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the "static resolution order", or "SRO". This is done by looking for the requested attribute in the set of "static variables" for a given class (or its parent classes). If the attribute does not appear in the "SRO", the class will fall back on the default attribute get/set/delete behavior (i.e., "MRO"). </p>
<pre><code>from functools import wraps
class StaticVarsMeta(type):
'''A metaclass for creating classes that emulate the "static variable" behavior
of other languages. I do not advise actually using this for anything!!!
Behavior is intended to be similar to classes that use __slots__. However, "normal"
attributes and __statics___ can coexist (unlike with __slots__).
Example usage:
class MyBaseClass(metaclass = StaticVarsMeta):
__statics__ = {'a','b','c'}
i = 0 # regular attribute
a = 1 # static var defined (optional)
class MyParentClass(MyBaseClass):
__statics__ = {'d','e','f'}
j = 2 # regular attribute
d, e, f = 3, 4, 5 # Static vars
a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)
class MyChildClass(MyParentClass):
__statics__ = {'a','b','c'}
j = 2 # regular attribute (redefines j from MyParentClass)
d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)
a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''
statics = {}
def __new__(mcls, name, bases, namespace):
# Get the class object
cls = super().__new__(mcls, name, bases, namespace)
# Establish the "statics resolution order"
cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))
# Replace class getter, setter, and deleter for instance attributes
cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
# Store the list of static variables for the class object
# This list is permanent and cannot be changed, similar to __slots__
try:
mcls.statics[cls] = getattr(cls,'__statics__')
except AttributeError:
mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
# Check and make sure the statics var names are strings
if any(not isinstance(static,str) for static in mcls.statics[cls]):
typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
# Move any previously existing, not overridden statics to the static var parent class(es)
if len(cls.__sro__) > 1:
for attr,value in namespace.items():
if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
for c in cls.__sro__[1:]:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
delattr(cls,attr)
return cls
def __inst_getattribute__(self, orig_getattribute):
'''Replaces the class __getattribute__'''
@wraps(orig_getattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
return StaticVarsMeta.__getstatic__(type(self),attr)
else:
return orig_getattribute(self, attr)
return wrapper
def __inst_setattr__(self, orig_setattribute):
'''Replaces the class __setattr__'''
@wraps(orig_setattribute)
def wrapper(self, attr, value):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__setstatic__(type(self),attr, value)
else:
orig_setattribute(self, attr, value)
return wrapper
def __inst_delattr__(self, orig_delattribute):
'''Replaces the class __delattr__'''
@wraps(orig_delattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__delstatic__(type(self),attr)
else:
orig_delattribute(self, attr)
return wrapper
def __getstatic__(cls,attr):
'''Static variable getter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
return getattr(c,attr)
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __setstatic__(cls,attr,value):
'''Static variable setter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
break
def __delstatic__(cls,attr):
'''Static variable deleter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
delattr(c,attr)
break
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __delattr__(cls,attr):
'''Prevent __sro__ attribute from deletion'''
if attr == '__sro__':
raise AttributeError('readonly attribute')
super().__delattr__(attr)
def is_static(cls,attr):
'''Returns True if an attribute is a static variable of any class in the __sro__'''
if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
return True
return False
</code></pre>
| 70 | 2014-12-19T15:16:36Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Static class variables in Python | 68,645 | <p>Is it possible to have static class variables or methods in python? What syntax is required to do this?</p>
| 1,015 | 2008-09-16T01:46:36Z | 36,216,964 | <p>It is possible to have <code>static</code> class variables, but probably not worth the effort.</p>
<p>Here's a proof-of-concept written in Python 3 -- if any of the exact details are wrong the code can be tweaked to match just about whatever you mean by a <code>static variable</code>:</p>
<hr>
<pre><code>class Static:
def __init__(self, value, doc=None):
self.deleted = False
self.value = value
self.__doc__ = doc
def __get__(self, inst, cls=None):
if self.deleted:
raise AttributeError('Attribute not set')
return self.value
def __set__(self, inst, value):
self.deleted = False
self.value = value
def __delete__(self, inst):
self.deleted = True
class StaticType(type):
def __delattr__(cls, name):
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__delete__(name)
else:
super(StaticType, cls).__delattr__(name)
def __getattribute__(cls, *args):
obj = super(StaticType, cls).__getattribute__(*args)
if isinstance(obj, Static):
obj = obj.__get__(cls, cls.__class__)
return obj
def __setattr__(cls, name, val):
# check if object already exists
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__set__(name, val)
else:
super(StaticType, cls).__setattr__(name, val)
</code></pre>
<p>and in use:</p>
<pre><code>class MyStatic(metaclass=StaticType):
"""
Testing static vars
"""
a = Static(9)
b = Static(12)
c = 3
class YourStatic(MyStatic):
d = Static('woo hoo')
e = Static('doo wop')
</code></pre>
<p>and some tests:</p>
<pre><code>ms1 = MyStatic()
ms2 = MyStatic()
ms3 = MyStatic()
assert ms1.a == ms2.a == ms3.a == MyStatic.a
assert ms1.b == ms2.b == ms3.b == MyStatic.b
assert ms1.c == ms2.c == ms3.c == MyStatic.c
ms1.a = 77
assert ms1.a == ms2.a == ms3.a == MyStatic.a
ms2.b = 99
assert ms1.b == ms2.b == ms3.b == MyStatic.b
MyStatic.a = 101
assert ms1.a == ms2.a == ms3.a == MyStatic.a
MyStatic.b = 139
assert ms1.b == ms2.b == ms3.b == MyStatic.b
del MyStatic.b
for inst in (ms1, ms2, ms3):
try:
getattr(inst, 'b')
except AttributeError:
pass
else:
print('AttributeError not raised on %r' % attr)
ms1.c = 13
ms2.c = 17
ms3.c = 19
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
MyStatic.c = 43
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
ys1 = YourStatic()
ys2 = YourStatic()
ys3 = YourStatic()
MyStatic.b = 'burgler'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
assert ys1.d == ys2.d == ys3.d == YourStatic.d
assert ys1.e == ys2.e == ys3.e == YourStatic.e
ys1.a = 'blah'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
ys2.b = 'kelp'
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
ys1.d = 'fee'
assert ys1.d == ys2.d == ys3.d == YourStatic.d
ys2.e = 'fie'
assert ys1.e == ys2.e == ys3.e == YourStatic.e
MyStatic.a = 'aargh'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
</code></pre>
| 1 | 2016-03-25T09:02:25Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] |
Best way to open a socket in Python | 68,774 | <p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
| 30 | 2008-09-16T02:06:11Z | 68,796 | <p>Opening sockets in python is pretty simple. You really just need something like this:</p>
<pre><code>import socket
sock = socket.socket()
sock.connect((address, port))
</code></pre>
<p>and then you can <code>send()</code> and <code>recv()</code> like any other socket</p>
| 55 | 2008-09-16T02:09:46Z | [
"python",
"networking",
"tcp"
] |
Best way to open a socket in Python | 68,774 | <p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
| 30 | 2008-09-16T02:06:11Z | 68,892 | <p>For developing portable network programs of any sort in Python, <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a> is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs.</p>
| 9 | 2008-09-16T02:28:38Z | [
"python",
"networking",
"tcp"
] |
Best way to open a socket in Python | 68,774 | <p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
| 30 | 2008-09-16T02:06:11Z | 68,911 | <p>OK, this code worked</p>
<pre><code>s = socket.socket()
s.connect((ip,port))
s.send("my request\r")
print s.recv(256)
s.close()
</code></pre>
<p>It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.</p>
| 13 | 2008-09-16T02:31:24Z | [
"python",
"networking",
"tcp"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 70,051 | <p>A short search turned up <a href="http://www.flagar.com/en/software/gtkshots" rel="nofollow">gtkShots</a> looks like it might help you, as it's a GPLed python screenshot program, so should have what you need in it.</p>
| 3 | 2008-09-16T07:24:13Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 70,237 | <pre><code>import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')
</code></pre>
<p>this requires Python Imaging Library</p>
| 7 | 2008-09-16T08:01:18Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 769,221 | <p>This one works on X11, and perhaps on Windows too (someone, please check). Needs <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro">PyQt4</a>:</p>
<pre><code>import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')
</code></pre>
| 17 | 2009-04-20T17:12:10Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 782,768 | <p>This works without having to use scrot or ImageMagick.</p>
<pre><code>import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
pb.save("screenshot.png","png")
print "Screenshot saved to screenshot.png."
else:
print "Unable to get the screenshot."
</code></pre>
<p>Borrowed from <a href="http://ubuntuforums.org/showpost.php?p=2681009&postcount=5">http://ubuntuforums.org/showpost.php?p=2681009&postcount=5</a></p>
| 53 | 2009-04-23T17:27:52Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 6,380,186 | <p>Cross platform solution using <a href="http://wxpython.org">wxPython</a>:</p>
<pre><code>import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
</code></pre>
| 7 | 2011-06-17T00:33:04Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 7,711,106 | <p>Compile all answers in one class.
Outputs PIL image.</p>
<pre><code>#!/usr/bin/env python
# encoding: utf-8
"""
screengrab.py
Created by Alex Snet on 2011-10-10.
Copyright (c) 2011 CodeTeam. All rights reserved.
"""
import sys
import os
import Image
class screengrab:
def __init__(self):
try:
import gtk
except ImportError:
pass
else:
self.screen = self.getScreenByGtk
try:
import PyQt4
except ImportError:
pass
else:
self.screen = self.getScreenByQt
try:
import wx
except ImportError:
pass
else:
self.screen = self.getScreenByWx
try:
import ImageGrab
except ImportError:
pass
else:
self.screen = self.getScreenByPIL
def getScreenByGtk(self):
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
return False
else:
width,height = pb.get_width(),pb.get_height()
return Image.fromstring("RGB",(width,height),pb.get_pixels() )
def getScreenByQt(self):
from PyQt4.QtGui import QPixmap, QApplication
from PyQt4.Qt import QBuffer, QIODevice
import StringIO
app = QApplication(sys.argv)
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
strio = StringIO.StringIO()
strio.write(buffer.data())
buffer.close()
del app
strio.seek(0)
return Image.open(strio)
def getScreenByPIL(self):
import ImageGrab
img = ImageGrab.grab()
return img
def getScreenByWx(self):
import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
#bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
myWxImage = wx.ImageFromBitmap( myBitmap )
PilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
PilImage.fromstring( myWxImage.GetData() )
return PilImage
if __name__ == '__main__':
s = screengrab()
screen = s.screen()
screen.show()
</code></pre>
| 35 | 2011-10-10T09:56:22Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 7,817,506 | <p>I have a wrapper project (<a href="https://github.com/ponty/pyscreenshot">pyscreenshot</a>) for scrot, imagemagick, pyqt, wx and pygtk.
If you have one of them, you can use it.
All solutions are included from this discussion.</p>
<p>Install:</p>
<pre><code>easy_install pyscreenshot
</code></pre>
<p>Example:</p>
<pre><code>import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
</code></pre>
| 11 | 2011-10-19T06:44:20Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 16,141,058 | <p>Just for completeness:
Xlib - But it's somewhat slow when capturing the whole screen:</p>
<pre><code>from Xlib import display, X
import Image #PIL
W,H = 200,200
dsp = display.Display()
root = dsp.screen().root
raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")
image.show()
</code></pre>
<p>One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.</p>
<hr>
<p><strong>Edit:</strong>
We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:</p>
<pre><code>#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c
void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data)
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
int x, y;
int ii = 0;
for (y = 0; y < H; y++) {
for (x = 0; x < W; x++) {
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = (pixel & blue_mask);
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
data[ii + 2] = blue;
data[ii + 1] = green;
data[ii + 0] = red;
ii += 3;
}
}
XDestroyImage(image);
XDestroyWindow(display, root);
XCloseDisplay(display);
}
</code></pre>
<p>And then the python-file:</p>
<pre><code>import ctypes
import os
from PIL import Image
LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)
def grab_screen(x1,y1,x2,y2):
w, h = x1+x2, y1+y2
size = w * h
objlength = size * 3
grab.getScreen.argtypes = []
result = (ctypes.c_ubyte*objlength)()
grab.getScreen(x1,y1, w, h, result)
return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
if __name__ == '__main__':
im = grab_screen(0,0,1440,900)
im.show()
</code></pre>
| 13 | 2013-04-22T06:52:08Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 20,219,666 | <p>Try it:</p>
<pre><code>#!/usr/bin/python
import gtk.gdk
import time
import random
import socket
import fcntl
import struct
import getpass
import os
import paramiko
while 1:
# generate a random time between 120 and 300 sec
random_time = random.randrange(20,25)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.asctime( time.localtime(time.time()) )
date = time.strftime("%d-%m-%Y")
timer = time.strftime("%I:%M:%S%p")
filename = timer
filename += ".png"
if (pb != None):
username = getpass.getuser() #Get username
newpath = r'screenshots/'+username+'/'+date #screenshot save path
if not os.path.exists(newpath): os.makedirs(newpath)
saveas = os.path.join(newpath,filename)
print saveas
pb.save(saveas,"png")
else:
print "Unable to get the screenshot."
</code></pre>
| -2 | 2013-11-26T14:23:22Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 23,609,424 | <p>There is a python package for this <a href="http://www.autopy.org/" rel="nofollow">Autopy</a></p>
<p>The bitmap module can to screen grabbing (bitmap.capture_screen)
It is multiplateform (Windows, Linux, Osx).</p>
| 1 | 2014-05-12T12:44:42Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 25,805,492 | <p>It's an old question. I would like to answer it using new tools.</p>
<p>Works with python 3 (should work with python 2, but I haven't test it) and PyQt5.</p>
<p>Minimal working example. Copy it to the python shell and get the result.</p>
<pre><code>from PyQt5.QtWidgets import QApplication
app = QApplication([])
screen = app.primaryScreen()
screenshot = screen.grabWindow(QApplication.desktop().winId())
screenshot.save('/tmp/screenshot.png')
</code></pre>
| 0 | 2014-09-12T09:51:53Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 29,136,548 | <p>From <a href="http://ubuntuforums.org/showthread.php?t=448160" rel="nofollow">this thread</a>:</p>
<pre><code> import os
os.system("import -window root temp.png")
</code></pre>
| 1 | 2015-03-19T03:05:42Z | [
"python",
"linux",
"screenshot"
] |
Take a screenshot via a python script. [Linux] | 69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| 54 | 2008-09-16T05:44:54Z | 30,503,686 | <p>bit late but nevermind easy one is</p>
<pre><code>import autopy
import time
time.sleep(2)
b = autopy.bitmap.capture_screen()
b.save("C:/Users/mak/Desktop/m.png")
</code></pre>
| 2 | 2015-05-28T10:17:58Z | [
"python",
"linux",
"screenshot"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 69,989 | <p>You could use HTTP Authentication, if supported.</p>
<p>You'd have to add SSL, as all methods, POST, GET and HTTP Auth (well, except Digest HHTP authentication) send plaintext.</p>
<p>GET is basically just like POST, it just has a limit on the amount of data you can send which is usually a lot smaller than POST and a semantic difference which makes GET not a good candidate from that point of view, even if technically they both can do it.</p>
<p>As for examples, what are you using? There are many choices in Python, like the cgi module or some framework like Django, CherryPy, and so on</p>
| 1 | 2008-09-16T07:10:04Z | [
"python",
"authentication",
"cgi"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 69,995 | <p>You can actually do it all with GET methods. However, you'll want to use a full challenge response protocol for the logins. (You can hash on the client side using javascript. You just need to send out a unique challenge each time.) You'll also want to use SSL to ensure that no one can see the strings as they go across.</p>
<p>In some senses there's no real security difference between GET and POST requests as they both go across in plaintext, in other senses and in practice... GET is are a hell of a lot easier to intercept and is all over most people's logs and your web browser's history. :)</p>
<p>(Or as suggested by the other posters, use a different method entirely like HTTP auth, digest auth or some higher level authentication scheme like AD, LDAP, kerberos or shib. However I kinda assumed that if you didn't have POST you wouldn't have these either.)</p>
| 5 | 2008-09-16T07:10:40Z | [
"python",
"authentication",
"cgi"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 70,003 | <p>With a bit of JavaScript, you could have the client hash the entered password and a server-generated nonce, and use that in an HTTP GET.</p>
| 0 | 2008-09-16T07:12:42Z | [
"python",
"authentication",
"cgi"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 70,025 | <p>Logging in securely is very subjective. Full 'security' is not easy to achieve (if at all possible...debatable). However, you can come close. </p>
<p>If POST is not an option, maybe you can use a directory security method such as .htaccess or windows authentication depending on what system you're on.</p>
<p>Both of the above will get you the pop-up window that allows for a username and password to be entered.</p>
<p>To use POST as the method to send the login credentials, you'd just use an HTML form with method="post" and retrieve the information from, say, a PHP or ASP page, using the $_POST['varname'] method in PHP or the request.form("varname") method in ASP. From the PHP or ASP page, as an example, you can do a lookup in a database of users, to see if that username/password combination exists, and if so, redirect them to the appropriate page.</p>
<p>As reference, use <a href="http://www.w3schools.com/ASP/showasp.asp?filename=demo_simpleform" rel="nofollow">http://www.w3schools.com/ASP/showasp.asp?filename=demo_simpleform</a> for the HTML/ASP portion</p>
| -1 | 2008-09-16T07:19:07Z | [
"python",
"authentication",
"cgi"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 70,145 | <p>A good choice: <a href="http://advosys.ca/viewpoints/2006/08/http-digest-authentication/" rel="nofollow">HTTP Digest authentication</a></p>
<p>Harder to pull off well, but an option: <a href="http://blog.paranoidferret.com/index.php/2007/07/22/secure-authentication-without-ssl-using-javascript/" rel="nofollow">Client-side hashing with Javascript</a></p>
| 0 | 2008-09-16T07:44:03Z | [
"python",
"authentication",
"cgi"
] |
Can I implement a web user authentication system in python without POST? | 69,979 | <p>My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?</p>
<p>If it's not, how would you do it with POST? Just out of curiosity.</p>
<p>Cheers!</p>
| 1 | 2008-09-16T07:07:42Z | 204,152 | <p>Javascript is the best option in this case.</p>
<p>Along with the request for the username and password, it sends a unique random string. You can then use a javascript md5 library to generate a hashed password, by combining the random string and the password [pwhash = md5(randomstring+password)]. The javascript then instantiates the call to <em><a href="http://SERVER/login.cgi?username=TheUsername&random=RANDOMSTRING&pwhash=0123456789abcdef0123456789abcdef" rel="nofollow">http://SERVER/login.cgi?username=TheUsername&random=RANDOMSTRING&pwhash=0123456789abcdef0123456789abcdef</a></em></p>
<p>The server must then do two things:
Check if the random string has EVER been used before, and it if has, deny the request. (<strong>very important</strong> for security)</p>
<p>Lookup the plaintext password for username, and do md5(randomstring+password). If that matches what the user supplied in the URL as a pwhash, then you know it's the user.</p>
<p>The reason you check if the random string has ever been used before is to stop a repeat attack. If somebody is able to see the network traffic or the browser history or logs, then they could simply log in again using the same URL, and it doesn't matter whether they know the original password or not.</p>
<p>I also recommend putting "Pragma: no-cache" and "Cache-Control: no-cache" at the top of the headers returned by the CGI script, just so that the authenticated session is not stored in the browser's or your ISPs web cache.</p>
<p>An even more secure solution would be using proper encryption and Challenge-Response. You tell the server your username, the server sends back a Challenge (some random string encrypted with your password), and you tell the server what the random string was. If you're able to tell the server, then obviously you have the password and are who you say you are! Kerberos does it this way, but quite a lot more carefully to prevent all sorts of attacks.</p>
| 0 | 2008-10-15T09:25:06Z | [
"python",
"authentication",
"cgi"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,555 | <p>From <a href="http://www.faqs.org/docs/diveintopython/fileinfo_private.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a></p>
<blockquote>
<p>Strictly speaking, private methods are
accessible outside their class, just
not easily accessible. Nothing in
Python is truly private; internally,
the names of private methods and
attributes are mangled and unmangled
on the fly to make them seem
inaccessible by their given names. You
can access the __parse method of the
MP3FileInfo class by the name
_MP3FileInfo__parse. Acknowledge that this is interesting, then promise to
never, ever do it in real code.
Private methods are private for a
reason, but like many other things in
Python, their privateness is
ultimately a matter of convention, not
force.</p>
</blockquote>
| 116 | 2008-09-16T09:03:45Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,562 | <p>It's not like you absolutly can't get around privateness of members in any language (pointer arithmetics in C++, Reflections in .NET/Java).</p>
<p>The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.</p>
<p>Edit: You don't try to secure your stuff by OO-encapsulation, do you?</p>
| 24 | 2008-09-16T09:04:57Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,567 | <p>The <code>class.__stuff</code> naming convention lets the programmer know he isn't meant to access <code>__stuff</code> from outside. The name mangling makes it unlikely anyone will do it by accident.</p>
<p>True, you still can work around this, it's even easier than in other languages (which BTW also let you do this), but no Python programmer would do this if he cares about encapsulation.</p>
| 9 | 2008-09-16T09:05:52Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,583 | <p>Its just one of those language design choices. On some level they are justified. They make it so you need to go pretty far out of your way to try and call the method, and if you really need it that badly, you must have a pretty good reason! Debugging hooks and testing come to mind as possible applications, used responsibly of course.</p>
| 10 | 2008-09-16T09:09:32Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,736 | <p>The phrase commonly used is "we're all consenting adults here". By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g. debuggers, code completion).</p>
<p>If you truly must have something that is private, then you can implement it in an extension (e.g. in C for CPython). In most cases, however, you simply learn the Pythonic way of doing things.</p>
| 66 | 2008-09-16T09:33:18Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 70,900 | <p>The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.</p>
<p>For example:</p>
<pre><code>>>> class Foo(object):
... def __init__(self):
... self.__baz = 42
... def foo(self):
... print self.__baz
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.__baz = 21
... def bar(self):
... print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}
</code></pre>
<p>Of course, it breaks down if two different classes have the same name.</p>
| 354 | 2008-09-16T10:06:07Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 80,000 | <p>Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).</p>
<p>Module attributes named as such will not be copied into an importing module when using the <code>from*</code> method, e.g.:</p>
<pre><code>from bar import *
</code></pre>
<p>However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.</p>
| 11 | 2008-09-17T04:29:45Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 1,949,874 | <p>When I first came from Java to Python i <strong>hated</strong> this. It scared me to death.</p>
<p>Today it might just be the one thing <strong>I love most</strong> about Python.</p>
<p>I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: "sure". If you think you understand the situation, perhaps you have even read it, then all we can say is "good luck!".</p>
<p>Remember, encapsulation is not even weakly related to "security", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.</p>
| 100 | 2009-12-22T23:25:42Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 3,147,548 | <h3>Example of private function</h3>
<pre><code>import re
import inspect
class MyClass :
def __init__(self) :
pass
def private_function ( self ) :
try :
function_call = inspect.stack()[1][4][0].strip()
# See if the function_call has "self." in the begining
matched = re.match( '^self\.', function_call )
if not matched :
print 'This is Private Function, Go Away'
return
except :
print 'This is Private Function, Go Away'
return
# This is the real Function, only accessible inside class #
print 'Hey, Welcome in to function'
def public_function ( self ) :
# i can call private function from inside the class
self.private_function()
### End ###
</code></pre>
| 185 | 2010-06-30T08:24:05Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Why are Python's 'private' methods not actually private? | 70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>What I did there is create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| 344 | 2008-09-16T08:59:32Z | 39,123,423 | <p>with python-3.4 this is the behaviour:</p>
<pre><code>>>> class Foo:
def __init__(self):
pass
def __privateMethod(self):
return 3
def invoke(self):
return self.__privateMethod()
>>> help(Foo)
Help on class Foo in module __main__:
class Foo(builtins.object)
| Methods defined here:
|
| __init__(self)
|
| invoke(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
>>> f = Foo()
>>> f.invoke()
3
>>> f.__privateMethod()
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
f.__privateMethod()
AttributeError: 'Foo' object has no attribute '__privateMethod'
</code></pre>
<p><a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow">https://docs.python.org/3/tutorial/classes.html#tut-private</a></p>
<blockquote>
<p>Note that the mangling rules are designed mostly to avoid accidents; <strong>it still is possible to access or modify a variable that is considered private.</strong> This can even be useful in special circumstances, such as in the debugger.</p>
</blockquote>
<p>Even if the question is old I hope my snippet could be helpful. </p>
| 0 | 2016-08-24T12:31:44Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 70,712 | <p>I think you should make your own authentication method as you can make it fit your application best but use a library for encryption, such as <a href="http://www.pycrypto.org" rel="nofollow">pycrypto</a> or some other more lightweight library.</p>
<p>btw, if you need windows binaries for pycrypto you can get them <a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="nofollow">here</a></p>
| 3 | 2008-09-16T09:27:28Z | [
"python",
"authentication",
"desktop"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 70,832 | <p>If you want simple, then use a dictionary where the keys are the usernames and the values are the passwords (encrypted with something like SHA256). <a href="http://docs.python.org/lib/module-pickle.html" rel="nofollow">Pickle</a> it to/from disk (as this is a desktop application, I'm assuming the overhead of keeping it in memory will be negligible).</p>
<p>For example:</p>
<pre><code>import pickle
import hashlib
# Load from disk
pwd_file = "mypasswords"
if os.path.exists(pwd_file):
pwds = pickle.load(open(pwd_file, "rb"))
else:
pwds = {}
# Save to disk
pickle.dump(pwds, open(pwd_file, "wb"))
# Add password
pwds[username] = hashlib.sha256(password).hexdigest()
# Check password
if pwds[username] = hashlib.sha256(password).hexdigest():
print "Good"
else:
print "No match"
</code></pre>
<p>Note that this stores the passwords as a <a href="http://docs.python.org/lib/module-hashlib.html" rel="nofollow">hash</a> - so they are essentially unrecoverable. If you lose your password, you'd get allocated a new one, not get the old one back.</p>
| 0 | 2008-09-16T09:50:34Z | [
"python",
"authentication",
"desktop"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 70,915 | <p>Treat the following as pseudo-code..</p>
<pre><code>try:
from hashlib import sha as hasher
except ImportError:
# You could probably exclude the try/except bit,
# but older Python distros dont have hashlib.
try:
import sha as hasher
except ImportError:
import md5 as hasher
def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
def load_auth_file(path):
"""Loads a comma-seperated file.
Important: make sure the username
doesn't contain any commas!
"""
# Open the file, or return an empty auth list.
try:
f = open(path)
except IOError:
print "Warning: auth file not found"
return {}
ret = {}
for line in f.readlines():
split_line = line.split(",")
if len(split_line) > 2:
print "Warning: Malformed line:"
print split_line
continue # skip it..
else:
username, password = split_line
ret[username] = password
#end if
#end for
return ret
def main():
auth_file = "/home/blah/.myauth.txt"
u = raw_input("Username:")
p = raw_input("Password:") # getpass is probably better..
if auth_file.has_key(u.strip()):
if auth_file[u] == hash_password(p):
# The hash matches the stored one
print "Welcome, sir!"
</code></pre>
<p>Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.</p>
<p>Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the <code>~/.myauth.txt</code> file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful.</p>
| 0 | 2008-09-16T10:08:57Z | [
"python",
"authentication",
"desktop"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 80,008 | <p>dbr said:</p>
<blockquote>
<pre><code>def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
</code></pre>
</blockquote>
<p>This is a really insecure way to hash passwords. You <em>don't</em> want to do this. If you want to know why read the <a href="http://www.openbsd.org/papers/bcrypt-paper.pdf">Bycrypt Paper</a> by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out <a href="http://www.securityfocus.com/columnists/388">this interview</a> with the author of Jack the Ripper (the popular unix password cracker).</p>
<p>Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times.</p>
<p>If that didn't make sense here is the code: </p>
<pre><code>#note I am using the Python Cryptography Toolkit
from Crypto.Hash import SHA256
HASH_REPS = 50000
def __saltedhash(string, salt):
sha256 = SHA256.new()
sha256.update(string)
sha256.update(salt)
for x in xrange(HASH_REPS):
sha256.update(sha256.digest())
if x % 10: sha256.update(salt)
return sha256
def saltedhash_bin(string, salt):
"""returns the hash in binary format"""
return __saltedhash(string, salt).digest()
def saltedhash_hex(string, salt):
"""returns the hash in hex format"""
return __saltedhash(string, salt).hexdigest()
</code></pre>
<p>For deploying a system like this the key thing to consider is the HASH_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file. </p>
<p>Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there.</p>
<p>hope this helps,
Tim</p>
| 9 | 2008-09-17T04:31:02Z | [
"python",
"authentication",
"desktop"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 1,992,484 | <pre><code>import hashlib
import random
def gen_salt():
salt_seed = str(random.getrandbits(128))
salt = hashlib.sha256(salt_seed).hexdigest()
return salt
def hash_password(password, salt):
h = hashlib.sha256()
h.update(salt)
h.update(password)
return h.hexdigest()
#in datastore
password_stored_hash = "41e2282a9c18a6c051a0636d369ad2d4727f8c70f7ddeebd11e6f49d9e6ba13c"
salt_stored = "fcc64c0c2bc30156f79c9bdcabfadcd71030775823cb993f11a4e6b01f9632c3"
password_supplied = 'password'
password_supplied_hash = hash_password(password_supplied, salt_stored)
authenticated = (password_supplied_hash == password_stored_hash)
print authenticated #True
</code></pre>
<p>see also <a href="http://stackoverflow.com/questions/1990722/gae-authenticate-to-a-3rd-party-site">gae-authenticate-to-a-3rd-party-site</a></p>
| 0 | 2010-01-02T19:05:18Z | [
"python",
"authentication",
"desktop"
] |
Python Authentication API | 70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| 5 | 2008-09-16T09:17:41Z | 10,495,626 | <p>Use " md5 " it's much better than base64</p>
<pre><code>>>> import md5
>>> hh = md5.new()
>>> hh.update('anoop')
>>> hh.digest
<built-in method digest of _hashlib.HASH object at 0x01FE1E40>
</code></pre>
| 0 | 2012-05-08T09:02:37Z | [
"python",
"authentication",
"desktop"
] |
Python Psycopg error and connection handling (v MySQLdb) | 70,681 | <p>Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:</p>
<pre><code>results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
try:
cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
print item, results[item]
# conn.commit()
except:
# conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
# cur=conn.cursor()
print 'choked on', item
continue
</code></pre>
<p>This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:</p>
<pre><code>agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina
</code></pre>
| 2 | 2008-09-16T09:22:36Z | 70,896 | <p>I think your code looks like this at the moment:</p>
<pre><code>l = "a very long ... text".split()
for e in l:
cursor.execute("INSERT INTO yourtable (yourcol) VALUES ('" + e + "')")
</code></pre>
<p>So try to change it into something like this:</p>
<pre><code>l = "a very long ... text".split()
for e in l:
cursor.execute("INSERT INTO yourtable (yourcol) VALUES (%s)", (e,))
</code></pre>
<p>so never forget to pass your parameters in the parameters list, then you don't have to care about your quotes and stuff, it is also more secure. You can read more about it at <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">http://www.python.org/dev/peps/pep-0249/</a></p>
<p>also have a look there at the method .executemany() which is specially designed to execute the same statement multiple times.</p>
| 2 | 2008-09-16T10:04:53Z | [
"python",
"mysql",
"psycopg2"
] |
Python Psycopg error and connection handling (v MySQLdb) | 70,681 | <p>Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:</p>
<pre><code>results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
try:
cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
print item, results[item]
# conn.commit()
except:
# conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
# cur=conn.cursor()
print 'choked on', item
continue
</code></pre>
<p>This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:</p>
<pre><code>agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina
</code></pre>
| 2 | 2008-09-16T09:22:36Z | 463,862 | <p>First of all you should let psycopg do the escaping for you by passing to the execute() method the parameters instead of doing the formatting yourself with '%'. That is:</p>
<pre><code>cur.execute("insert into resultstab values (%s, %s)", (item, results[item]))
</code></pre>
<p>Note how we use "%s" as a marker even for non-string values and avoid quotes in the query. psycopg will do all the quoting for us.</p>
<p>Then, if you want to ignore some errors, just rollback and continue.</p>
<pre><code>try:
cur.execute("SELECT this is an error")
except:
conn.rollback()
</code></pre>
<p>That's all. psycopg will rollback and start a new transaction on your next statement.</p>
| 2 | 2009-01-21T01:43:57Z | [
"python",
"mysql",
"psycopg2"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 70,814 | <pre><code>var = raw_input("Please enter something: ")
print "you entered", var
</code></pre>
| 296 | 2008-09-16T09:48:16Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 70,818 | <p>The best way to process command line arguments is the <a href="https://docs.python.org/library/argparse.html" rel="nofollow"><code>argparse</code> module.</a></p>
<p>Use <code>raw_input()</code> to get user input. If you import the <a href="https://docs.python.org/library/readline.html" rel="nofollow"><code>readline module</code></a> your users will have line editing and history.</p>
| 22 | 2008-09-16T09:48:40Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 70,833 | <p>To read user input you can try <a href="http://docs.python.org/2/library/cmd.html">the cmd module</a> for easily creating a mini-command line interpreter (with help texts and autocompletion) and <a href="http://docs.python.org/2/library/functions.html#raw_input">raw_input</a> for less fancy stuff (just reading a line of text from the user).</p>
<p>Command line inputs are in sys.argv. Try this in your script for Python 2:</p>
<pre><code>import sys
print sys.argv
</code></pre>
<p>For Python 3:</p>
<pre><code>import sys
print(sys.argv)
</code></pre>
<p>Since print has changed from a keyword in Python 2 into a function call in Python 3. </p>
<p>There are two modules for parsing command line options: <a href="http://docs.python.org/2/library/optparse.html">optparse</a> and <a href="http://docs.python.org/2/library/getopt.html">getopt</a>. If you just want to input files to your script, behold the power of <a href="http://docs.python.org/2/library/fileinput.html">fileinput</a>.</p>
<p>The <a href="http://docs.python.org/2/library/">Python library reference is your friend</a>.</p>
| 182 | 2008-09-16T09:50:40Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 70,841 | <p>Use 'raw_input' for input from a console/terminal.</p>
<p>if you just want a command line argument like a file name or something e.g. </p>
<pre><code>$ python my_prog.py file_name.txt
</code></pre>
<p>then you can use sys.argv...</p>
<pre><code>import sys
print sys.argv
</code></pre>
<p>sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"</p>
<p>If you want to have full on command line options use the optparse module.</p>
<p>Pev</p>
| 5 | 2008-09-16T09:52:24Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 70,869 | <p>Careful not to use the <code>input</code> function, unless you know what you're doing. Unlike <code>raw_input</code>, <code>input</code> will accept any python expression, so it's kinda like <code>eval</code></p>
| 10 | 2008-09-16T09:58:33Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 3,427,325 | <p>As of Python <del>3.2</del> 2.7, there is now <a href="http://docs.python.org/dev/library/argparse.html" rel="nofollow">argparse</a> for processing command line arguments.</p>
| 5 | 2010-08-06T20:00:22Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 8,334,188 | <p><code>raw_input</code> is no longer available in Python 3.x. But <code>raw_input</code> was renamed <code>input</code>, so the same functionality exists.</p>
<pre><code>input_var = input("Enter something: ")
print ("you entered " + input_var)
</code></pre>
<p><a href="http://docs.python.org/py3k/whatsnew/3.0.html#builtins">Documentation of the change</a></p>
| 127 | 2011-11-30T22:53:49Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 13,089,887 | <p>If you are running Python <2.7, you need <a href="http://docs.python.org/library/optparse.html">optparse</a>, which as the doc explains will create an interface to the command line arguments that are called when your application is run.</p>
<p>However, in Python â¥2.7, optparse has been deprecated, and was replaced with the <a href="http://docs.python.org/library/argparse.html">argparse</a> as shown above. A quick example from the docs...</p>
<blockquote>
<p>The following code is a Python program that takes a list of integers
and produces either the sum or the max:</p>
</blockquote>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
</code></pre>
| 6 | 2012-10-26T15:29:14Z | [
"python",
"input",
"command-line-arguments"
] |
Python: user input and commandline arguments | 70,797 | <p>How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?</p>
| 222 | 2008-09-16T09:44:59Z | 30,341,035 | <p>This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.</p>
<pre><code>import argparse
import sys
try:
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
#print the square of user input from cmd line.
print args.square**2
#print all the sys argument passed from cmd line including the program name.
print sys.argv
#print the second argument passed from cmd line; Note it starts from ZERO
print sys.argv[1]
except:
e = sys.exc_info()[0]
print e
</code></pre>
<p>1) To find the square root of 5</p>
<pre><code>C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5
</code></pre>
<p>2) Passing invalid argument other than number</p>
<pre><code>C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>
</code></pre>
| 5 | 2015-05-20T05:33:16Z | [
"python",
"input",
"command-line-arguments"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,161 | <p>Try:</p>
<pre><code>import HTMLParser
</code></pre>
<p>In Python 3.0, the HTMLParser module has been renamed to html.parser
you can check about this <a href="http://docs.python.org/library/htmlparser.html">here</a></p>
<p>Python 3.0</p>
<pre><code>import html.parser
</code></pre>
<p>Python 2.2 and above</p>
<pre><code>import HTMLParser
</code></pre>
| 12 | 2008-09-16T10:51:40Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,168 | <p>There's a link to an example on the bottom of (<a href="http://docs.python.org/2/library/htmlparser.html" rel="nofollow">http://docs.python.org/2/library/htmlparser.html</a>) , it just doesn't work with the original python or python3. It has to be python2 as it says on the top.</p>
| 1 | 2008-09-16T10:52:39Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,174 | <p>You probably really want <a href="http://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424">BeautifulSoup</a>, check the link for an example. </p>
<p>But in any case</p>
<pre><code>>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
>>> h.feed('<html></html>')
>>> h.get_starttag_text()
'<html>'
>>> h.close()
</code></pre>
| 22 | 2008-09-16T10:54:05Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,176 | <p>I would recommend using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> module instead and it has <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">good documentation</a>.</p>
| 4 | 2008-09-16T10:54:21Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,186 | <p>For real world HTML processing I'd recommend <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. It is great and takes away much of the pain. Installation is easy.</p>
| 1 | 2008-09-16T10:55:20Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 71,614 | <p>You should also look at <a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> for Python as it tries to parse HTML in a way that very much resembles what web browsers do, especially when dealing with invalid HTML (which is more than 90% of today's web).</p>
| 4 | 2008-09-16T12:14:04Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 72,100 | <p>I don't recommend BeautifulSoup if you want speed. lxml is much, much faster, and you can fall back in lxml's BS soupparser if the default parser doesn't work.</p>
| 3 | 2008-09-16T13:21:55Z | [
"python",
"import"
] |
HTML parser in Python | 71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| 7 | 2008-09-16T10:49:36Z | 82,117 | <p>You may be interested in <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. It is a separate package and has C components, but is the fastest. It has also very nice API, allowing you to easily list links in HTML documents, or list forms, sanitize HTML, and more. It also has capabilities to parse not well-formed HTML (it's configurable).</p>
| 4 | 2008-09-17T11:19:11Z | [
"python",
"import"
] |
Using the docstring from one method to automatically overwrite that of another method | 71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| 2 | 2008-09-16T12:46:28Z | 72,126 | <p>Well the doc-string is stored in <code>__doc__</code> so it wouldn't be too hard to re-assign it based on the doc-string of <code>_execute</code> after the fact.</p>
<p>Basically:</p>
<p><code></p>
<pre>
class MyClass(object):
def execute(self):
'''original doc-string'''
self._execute()
class SubClass(MyClass):
def _execute(self):
'''sub-class doc-string'''
pass
# re-assign doc-string of execute
def execute(self,*args,**kw):
return MyClass.execute(*args,**kw)
execute.__doc__=_execute.__doc__
</pre>
<p></code></p>
<p>Execute has to be re-declared to that the doc string gets attached to the version of execute for the <code>SubClass</code> and not for <code>MyClass</code> (which would otherwise interfere with other sub-classes).</p>
<p>That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result. You could then wrap this up in a meta-class to make it easier for people who are sub-classing.</p>
| 0 | 2008-09-16T13:25:12Z | [
"python",
"metaclass"
] |
Using the docstring from one method to automatically overwrite that of another method | 71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| 2 | 2008-09-16T12:46:28Z | 72,192 | <p>Is there a reason you can't override the base class's <code>execute</code> function directly?</p>
<pre><code>class Base(object):
def execute(self):
...
class Derived(Base):
def execute(self):
"""Docstring for derived class"""
Base.execute(self)
...stuff specific to Derived...
</code></pre>
<p>If you don't want to do the above:</p>
<p>Method objects don't support writing to the <code>__doc__</code> attribute, so you have to change <code>__doc__</code> in the actual function object. Since you don't want to override the one in the base class, you'd have to give each subclass its own copy of <code>execute</code>:</p>
<pre><code>class Derived(Base):
def execute(self):
return Base.execute(self)
class _execute(self):
"""Docstring for subclass"""
...
execute.__doc__= _execute.__doc__
</code></pre>
<p>but this is similar to a roundabout way of redefining <code>execute</code>...</p>
| 2 | 2008-09-16T13:31:44Z | [
"python",
"metaclass"
] |
Using the docstring from one method to automatically overwrite that of another method | 71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| 2 | 2008-09-16T12:46:28Z | 72,596 | <p>Well, if you don't mind copying the original method in the subclass, you can use the following technique.</p>
<pre><code>import new
def copyfunc(func):
return new.function(func.func_code, func.func_globals, func.func_name,
func.func_defaults, func.func_closure)
class Metaclass(type):
def __new__(meta, name, bases, attrs):
for key in attrs.keys():
if key[0] == '_':
skey = key[1:]
for base in bases:
original = getattr(base, skey, None)
if original is not None:
copy = copyfunc(original)
copy.__doc__ = attrs[key].__doc__
attrs[skey] = copy
break
return type.__new__(meta, name, bases, attrs)
class Class(object):
__metaclass__ = Metaclass
def execute(self):
'''original doc-string'''
return self._execute()
class Subclass(Class):
def _execute(self):
'''sub-class doc-string'''
pass
</code></pre>
| 4 | 2008-09-16T14:02:38Z | [
"python",
"metaclass"
] |
Using the docstring from one method to automatically overwrite that of another method | 71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| 2 | 2008-09-16T12:46:28Z | 72,785 | <p>I agree that the simplest, most Pythonic way of approaching this is to simply redefine execute in your subclasses and have it call the execute method of the base class:</p>
<pre><code>class Sub(Base):
def execute(self):
"""New docstring goes here"""
return Base.execute(self)
</code></pre>
<p>This is very little code to accomplish what you want; the only downside is that you must repeat this code in every subclass that extends Base. However, this is a small price to pay for the behavior you want.</p>
<p>If you want a sloppy and verbose way of making sure that the docstring for execute is dynamically generated, you can use the descriptor protocol, which would be significantly less code than the other proposals here. This is annoying because you can't just set a descriptor on an existing function, which means that execute must be written as a separate class with a <code>__call__</code> method.</p>
<p>Here's the code to do this, but keep in mind that my above example is much simpler and more Pythonic:</p>
<pre><code>class Executor(object):
__doc__ = property(lambda self: self.inst._execute.__doc__)
def __call__(self):
return self.inst._execute()
class Base(object):
execute = Executor()
class Sub(Base):
def __init__(self):
self.execute.inst = self
def _execute(self):
"""Actually does something!"""
return "Hello World!"
spam = Sub()
print spam.execute.__doc__ # prints "Actually does something!"
help(spam) # the execute method says "Actually does something!"
</code></pre>
| 0 | 2008-09-16T14:17:43Z | [
"python",
"metaclass"
] |
Using the docstring from one method to automatically overwrite that of another method | 71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| 2 | 2008-09-16T12:46:28Z | 73,473 | <p>Look at the functools.wraps() decorator; it does all of this, but I don't know offhand if you can get it to run in the right context</p>
| 1 | 2008-09-16T15:19:05Z | [
"python",
"metaclass"
] |
Python and "re" | 72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.</p>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| 6 | 2008-09-16T13:47:48Z | 72,449 | <p>Are you using the re.match() or re.search() method? My understanding is that re.match() assumes a "^" at the begining of your expression and will only search at the beginning of the text, while re.search() acts more like the Perl regular expressions and will only match the beginning of the text if you include a "^" at the beginning of your expression. Hope that helps.</p>
| 1 | 2008-09-16T13:52:02Z | [
"python",
"regex"
] |
Python and "re" | 72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.</p>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| 6 | 2008-09-16T13:47:48Z | 72,470 | <p>In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.</p>
<p><a href="http://docs.python.org/lib/module-re.html" rel="nofollow">Python regex docs</a><br />
<a href="http://docs.python.org/lib/matching-searching.html" rel="nofollow">Matching vs searching</a></p>
| 19 | 2008-09-16T13:53:03Z | [
"python",
"regex"
] |
Python and "re" | 72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.</p>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| 6 | 2008-09-16T13:47:48Z | 72,501 | <pre><code>>>> import re
>>> pattern = re.compile("url")
>>> string = " url"
>>> pattern.match(string)
>>> pattern.search(string)
<_sre.SRE_Match object at 0xb7f7a6e8>
</code></pre>
| 3 | 2008-09-16T13:54:56Z | [
"python",
"regex"
] |
Python and "re" | 72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.</p>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| 6 | 2008-09-16T13:47:48Z | 72,521 | <p>You are probably being tripped up by the different methods re.search and re.match.</p>
| 1 | 2008-09-16T13:56:13Z | [
"python",
"regex"
] |
Python and "re" | 72,393 | <p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.</p>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
| 6 | 2008-09-16T13:47:48Z | 78,072 | <pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(your_html)
for a in soup.findAll('a', href=True):
# do something with `a` w/ href attribute
print a['href']
</code></pre>
| 4 | 2008-09-16T22:44:42Z | [
"python",
"regex"
] |
Python's unittest logic | 72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| 3 | 2008-09-16T13:50:25Z | 72,498 | <p>If I recall correctly in that test framework the setUp method is run before each test</p>
| 0 | 2008-09-16T13:54:38Z | [
"python",
"unit-testing"
] |
Python's unittest logic | 72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| 3 | 2008-09-16T13:50:25Z | 72,504 | <p>From <a href="http://docs.python.org/lib/minimal-example.html">http://docs.python.org/lib/minimal-example.html</a> :</p>
<blockquote>
<p>When a setUp() method is defined, the
test runner will run that method prior
to each test.</p>
</blockquote>
<p>So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.</p>
| 11 | 2008-09-16T13:55:02Z | [
"python",
"unit-testing"
] |
Python's unittest logic | 72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| 3 | 2008-09-16T13:50:25Z | 72,702 | <p>The setUp method, as everyone else has said, runs before every test method you write. So, when testB runs, the value of i is 1, not 3.</p>
<p>You can also use a tearDown method which runs after every test method. However if one of your tests crashes, your tearDown method will never run.</p>
| -1 | 2008-09-16T14:12:08Z | [
"python",
"unit-testing"
] |
Python's unittest logic | 72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| 3 | 2008-09-16T13:50:25Z | 73,791 | <p>Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.</p>
<p>Additionally, as others have pointed out, setUp is called before each test.</p>
| 9 | 2008-09-16T15:47:30Z | [
"python",
"unit-testing"
] |
Python's unittest logic | 72,422 | <p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p>
<pre><code>>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self):
self.assertEqual(self.i, 3)
>>> unittest.main()
.F
======================================================================
FAIL: testB (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<pyshell#61>", line 8, in testB
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 0.016s
</code></pre>
| 3 | 2008-09-16T13:50:25Z | 215,576 | <p>From a methodological point of view, individual tests should be independent, otherwise it can produce more hard-to-find bugs. Imagine for instance that testA and testB would be called in a different order.</p>
| 0 | 2008-10-18T21:13:18Z | [
"python",
"unit-testing"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 72,904 | <p>Why you even need this? Why you just do not import it as</p>
<pre><code>from app.sub2 import mod2
</code></pre>
| -8 | 2008-09-16T14:27:57Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 73,009 | <p>I think that what you have to ask yourself is:</p>
<ul>
<li>Why i need to do this?</li>
<li>Is my package separation well done?</li>
</ul>
<p>I don't know the context why you want to do it this way. But for me a cleaner design would be to have the following packages structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub12/
__init__.py
mod2.py
</code></pre>
<p>Then you only have to do:</p>
<pre><code>from sub12 import mod2
</code></pre>
| -7 | 2008-09-16T14:36:25Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 73,060 | <p>Don't do relative imports. They'll only make your code more fragile. If you do an absolute import as Matej suggested, you'll be less vulnerable to changes in sys.path and changes in file locations.</p>
| -14 | 2008-09-16T14:40:26Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 73,149 | <p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>
<p>The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.</p>
<p>From <a href="http://www.python.org/dev/peps/pep-0328/">PEP 328</a>:</p>
<blockquote>
<p>Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>
</blockquote>
<p>In Python 2.6, they're adding the ability to reference modules relative to the main module. <a href="http://python.org/dev/peps/pep-0366/">PEP 366</a> describes the change.</p>
<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p>
| 189 | 2008-09-16T14:48:56Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 465,129 | <pre><code>main.py
setup.py
app/ ->
__init__.py
package_a/ ->
__init__.py
module_a.py
package_b/ ->
__init__.py
module_b.py
</code></pre>
<ol>
<li>You run <code>python main.py</code>.</li>
<li><code>main.py</code> does: <code>import app.package_a.module_a</code></li>
<li><code>module_a.py</code> does <code>import app.package_b.module_b</code></li>
</ol>
<p>Alternatively 2 or 3 could use: <code>from app.package_a import module_a</code></p>
<p>That will work as long as you have <code>app</code> in your PYTHONPATH. <code>main.py</code> could be anywhere then.</p>
<p>So you write a <code>setup.py</code> to copy (install) the whole app package and subpackages to the target system's python folders, and <code>main.py</code> to target system's script folders.</p>
| 82 | 2009-01-21T12:42:11Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 1,083,169 | <pre><code>def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[-1]
return module
</code></pre>
<p>I'm using this snippet to import modules from paths, hope that helps</p>
| 24 | 2009-07-04T23:27:50Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 5,204,410 | <p>Suppose you run at the top level, then in <code>mod1</code> use:</p>
<pre><code>import sub2.mod2
</code></pre>
<p>instead of</p>
<pre><code>from ..sub2 import mod2
</code></pre>
| -4 | 2011-03-05T14:31:21Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 6,524,846 | <p>From <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="nofollow">Python doc</a>,</p>
<blockquote>
<p>In Python 2.5, you can switch importâs behaviour to absolute imports using a <code>from __future__ import absolute_import</code> directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, <code>import string</code> will always find the standard libraryâs version. Itâs suggested that users should begin using absolute imports as much as possible, so itâs preferable to begin writing <code>from pkg import string</code> in your code</p>
</blockquote>
| 1 | 2011-06-29T17:33:27Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 7,541,369 | <p>Take a look at <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="nofollow">http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports</a>. You could do </p>
<pre><code>from .mod1 import stuff
</code></pre>
| 4 | 2011-09-24T19:31:57Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 8,195,271 | <p>"Guido views running scripts within a package as an anti-pattern" (rejected
<a href="http://www.python.org/dev/peps/pep-3122/">PEP-3122</a>)</p>
<p>I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.</p>
| 26 | 2011-11-19T16:05:29Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 9,541,554 | <p>This is unfortunately a sys.path hack, but it works quite well.</p>
<p>I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.</p>
<p>what I wanted to do was the following (the module I was working from was module3):</p>
<pre><code>mymodule\
__init__.py
mymodule1\
__init__.py
mymodule1_1
mymodule2\
__init__.py
mymodule2_1
import mymodule.mymodule1.mymodule1_1
</code></pre>
<p>Note that I have already installed mymodule, but in my installation I do not have "mymodule1"</p>
<p>and I would get an ImportError because it was trying to import from my installed modules.</p>
<p>I tried to do a sys.path.append, and that didn't work. What did work was a <strong>sys.path.insert</strong></p>
<pre><code>if __name__ == '__main__':
sys.path.insert(0, '../..')
</code></pre>
<p>So kind of a hack, but got it all to work!
So keep in mind, if you want your decision to <strong>override other paths</strong> then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)</p>
| 6 | 2012-03-02T22:58:47Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 9,748,770 | <p>I found it's more easy to set "PYTHONPATH" enviroment variable to the top folder:</p>
<pre><code>bash$ export PYTHONPATH=/PATH/TO/APP
</code></pre>
<p>then:</p>
<pre><code>import sub1.func1
#...more import
</code></pre>
<p>of course, PYTHONPATH is "global", but it didn't raise trouble for me yet.</p>
| -1 | 2012-03-17T09:20:09Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 12,365,065 | <p>On top of what John B said, it seems like setting the <code>__package__</code> variable should help, instead of changing <code>__main__</code> which could screw up other things. But as far as I could test, it doesn't completely work as it should.</p>
<p>I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in <code>sys.path</code>, as far as I could understand.</p>
<p>I should also mention that I did not find how to format the string that should go into those variables. Is it <code>"package_head.subfolder.module_name"</code> or what? </p>
| 0 | 2012-09-11T07:47:16Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 14,189,875 | <p>Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a <code>scripts</code> directory.</p>
<pre><code>import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
</code></pre>
| 5 | 2013-01-07T04:26:52Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 15,458,607 | <p>Here is the solution which works for me:</p>
<p>I do the relative imports as <code>from ..sub2 import mod2</code>
and then, if I want to run <code>mod1.py</code> then I go to the parent directory of <code>app</code> and run the module using the python -m switch as <code>python -m app.sub1.mod1</code>.</p>
<p>The real reason why this problem occurs with relative imports, is that relative imports works by taking the <code>__name__</code> property of the module. If the module is being directly run, then <code>__name__</code> is set to <code>__main__</code> and it doesn't contain any information about package structure. And, thats why python complains about the <code>relative import in non-package</code> error. </p>
<p>So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.</p>
<p>I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)</p>
<p>Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.</p>
| 67 | 2013-03-17T07:43:34Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 20,449,492 | <p>explanation of <code>nosklo's</code> answer with examples</p>
<p><em>note: all <code>__init__.py</code> files are empty.</em></p>
<pre><code>main.py
app/ ->
__init__.py
package_a/ ->
__init__.py
fun_a.py
package_b/ ->
__init__.py
fun_b.py
</code></pre>
<h3>app/package_a/fun_a.py</h3>
<pre><code>def print_a():
print 'This is a function in dir package_a'
</code></pre>
<h3>app/package_b/fun_b.py</h3>
<pre><code>from app.package_a.fun_a import print_a
def print_b():
print 'This is a function in dir package_b'
print 'going to call a function in dir package_a'
print '-'*30
print_a()
</code></pre>
<h3>main.py</h3>
<pre><code>from app.package_b import fun_b
fun_b.print_b()
</code></pre>
<p>if you run <code>$ python main.py</code> it returns:</p>
<pre><code>This is a function in dir package_b
going to call a function in dir package_a
------------------------------
This is a function in dir package_a
</code></pre>
<ul>
<li>main.py does: <code>from app.package_b import fun_b</code> </li>
<li>fun_b.py does <code>from app.package_a.fun_a import print_a</code></li>
</ul>
<p>so file in folder <code>package_b</code> used file in folder <code>package_a</code>, which is what you want. Right??</p>
| 8 | 2013-12-08T03:19:42Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 30,736,316 | <p>As @EvgeniSergeev says in the comments to the OP, you can import code from a <code>.py</code> file at an arbitrary location with:</p>
<pre><code>import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
</code></pre>
<p>This is taken from <a href="http://stackoverflow.com/a/67692/2071807">this SO answer</a>.</p>
| 3 | 2015-06-09T15:22:27Z | [
"python",
"python-import",
"python-module"
] |
How to do relative imports in Python? | 72,852 | <p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)</p>
| 309 | 2008-09-16T14:24:02Z | 35,338,828 | <p>This is solved 100%:</p>
<ul>
<li>app/
<ul>
<li>main.py</li>
</ul></li>
<li>settings/
<ul>
<li>local_setings.py</li>
</ul></li>
</ul>
<p>Import settings/local_setting.py in app/main.py:</p>
<p>main.py:</p>
<pre><code>import sys
sys.path.insert(0, ".settings")
try:
from settings.local_settings import *
except ImportError:
print('No Import')
</code></pre>
| 3 | 2016-02-11T12:01:50Z | [
"python",
"python-import",
"python-module"
] |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | <p>I got a list of dictionaries and want that to be sorted by a value of that dictionary.</p>
<p>This</p>
<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
</code></pre>
<p>sorted by name, should become</p>
<pre><code>[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
</code></pre>
| 822 | 2008-09-16T14:27:47Z | 72,950 | <p>You have to implement your own comparison function that will compare the dictionaries by values of name keys. See <a href="http://wiki.python.org/moin/HowTo/Sorting">Sorting Mini-HOW TO from PythonInfo Wiki</a></p>
| 7 | 2008-09-16T14:31:52Z | [
"python",
"list",
"sorting",
"dictionary"
] |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | <p>I got a list of dictionaries and want that to be sorted by a value of that dictionary.</p>
<p>This</p>
<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
</code></pre>
<p>sorted by name, should become</p>
<pre><code>[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
</code></pre>
| 822 | 2008-09-16T14:27:47Z | 73,019 | <p>I guess you've meant:</p>
<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
</code></pre>
<p>This would be sorted like this:</p>
<pre><code>sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
</code></pre>
| 7 | 2008-09-16T14:36:54Z | [
"python",
"list",
"sorting",
"dictionary"
] |
How do I sort a list of dictionaries by values of the dictionary in Python? | 72,899 | <p>I got a list of dictionaries and want that to be sorted by a value of that dictionary.</p>
<p>This</p>
<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
</code></pre>
<p>sorted by name, should become</p>
<pre><code>[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
</code></pre>
| 822 | 2008-09-16T14:27:47Z | 73,044 | <pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list.sort(lambda x,y : cmp(x['name'], y['name']))
</code></pre>
<p><code>my_list</code> will now be what you want.</p>
<p><strong>(3 years later) Edited to add:</strong></p>
<p>The new <code>key</code> argument is more efficient and neater. A better answer now looks like:</p>
<pre><code>my_list = sorted(my_list, key=lambda k: k['name'])
</code></pre>
<p>...the lambda is, IMO, easier to understand than <code>operator.itemgetter</code>, but YMMV.</p>
| 12 | 2008-09-16T14:39:11Z | [
"python",
"list",
"sorting",
"dictionary"
] |
Subsets and Splits