How can I clear all the attributes off an instance of Python's threading.local()?
You can clear it's underlying __dict__:
>>> l = threading.local()
>>> l
<thread._local object at 0x7fe8d5af5fb0>
>>> l.ok = "yes"
>>> l.__dict__
{'ok': 'yes'}
>>> l.__dict__.clear()
>>> l.__dict__
{}
>>> l.ok
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'thread._local' object has no attribute 'ok'
Accessing the __dict__ directly is specifically called out as a valid way to interact with the local object in the _threading_local module documentation:
Thread-local objects support the management of thread-local data.
If you have data that you want to be local to a thread, simply create
a thread-local object and use its attributes:
>>> mydata = local()
>>> mydata.number = 42
>>> mydata.number
42
You can also access the local-object's dictionary:
>>> mydata.__dict__
{'number': 42}
>>> mydata.__dict__.setdefault('widgets', [])
[]
>>> mydata.widgets
[]
Related
Here is a code I have written. I presumed both of them to return the same answer but they don't! How are they different?
from collections import deque
d = deque()
for _ in range(int(input())):
method, *n = input().split()
getattr(d, method)(*n)
print(*d)
and
from collections import deque
d = deque()
for _ in range(int(input())):
method, *n = input().split()
d.method(*n)
print(*d)
getattr(...) will get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
Where as d.method(*n) will try to lookup the method named method in deque object result in AttributeError: 'collections.deque' object has no attribute 'method'
>>> from collections import deque
>>> d = deque()
>>> dir(d) # removed dunder methods for readability
[
"append",
"appendleft",
"clear",
"copy",
"count",
"extend",
"extendleft",
"index",
"insert",
"maxlen",
"pop",
"popleft",
"remove",
"reverse",
"rotate",
]
>>> method = "insert"
>>> d.method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'collections.deque' object has no attribute 'method'
>>> insert_method = getattr(d, method)
>>> insert_method
<built-in method insert of collections.deque object at 0x000001E5638AC0>
>>> help(insert_method)
Help on built-in function insert:
insert(...) method of collections.deque instance
D.insert(index, object) -- insert object before index
>>> insert_method(0, 1)
>>> d
deque([1])
I am new to dse graph. I am getting an error
No such property: g for class: error
what could I be doing wrong?
>>> from dse.cluster import Cluster, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT, GraphExecutionProfile
>>> from dse.graph import GraphOptions
>>> from dse.auth import PlainTextAuthProvider
>>> Auth_provider = PlainTextAuthProvider(username=<<username>>,
password=<<password>>)
>>> ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name='idg'))
>>> cluster = Cluster(database_cluster, auth_provider=auth_provider,
execution_profiles={EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT: ep})
>>> dse_session.execute_graph('g.V()')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dse/cluster.py", line 2017, in dse.cluster.Session.execute_graph
File "dse/cluster.py", line 3962, in dse.cluster.ResponseFuture.result
dse.InvalidRequest: Error from server: code=2200 [Invalid query] message="No such property: g for class: Script184"
>>> print(vars(ep.graph_options))
{'_graph_options': {'graph-name': b'idg', 'graph-source': b'g', 'graph-language': b'gremlin-groovy', 'graph-results': b'graphson-1.0'}}
Instead of the EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT when defining execution profile you need to use EXEC_PROFILE_GRAPH_DEFAULT. The EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT is used to access to System API to manipulate graphs, etc.
You also need to connect to cluster via session = cluster.connect() (I don't see it in your code).
See driver docs for more examples.
Works now. After I used EXEC_PROFILE_GRAPH_DEFAULT for the execution profile
>>> from dse.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT, GraphExecutionProfile
>>> from dse.graph import GraphOptions,SimpleGraphStatement
>>> from dse.auth import PlainTextAuthProvider
>>> Auth_provider = PlainTextAuthProvider(<<username>>, <<password>>)
>>> ep = GraphExecutionProfile(graph_options=GraphOptions(graph_name='idg'))
>>> cluster = Cluster(database_cluster, auth_provider=auth_provider, execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep})
>>> dse_session = cluster.connect()
>>> dse_session.execute_graph('g.V()')
<dse.cluster.ResultSet object at 0x10f1fbef0>
I'm using python 2.7.3 and and Berkeley DB to store data. I didn't find much information about that module, only in python docks. I saw there some function described, but I didn't see instruction on how to delete a record from database. Help please, if you know how to delete a record and is that possible using bsddb ?
According to the documentation:
Once instantiated, hash, btree and record objects support the same methods as dictionaries.
So, you can use del db_object['key'] to delete specific record like a dictionary.
>>> import bsddb
>>> db = bsddb.hashopen('a.db', 'c')
>>> db['a'] = '1'
>>> db.keys()
['a']
>>> del db['a'] # <-----
>>> db.keys()
[]
db_object.pop('key') also works.
>>> db['b'] = '2'
>>> db.keys()
['b']
>>> db.pop('b')
'2'
del, .pop() with non-existing key will raise KeyError or similar exception. If you want ignore non-existing key, use .pop('key', None):
>>> db.pop('b') # This raises an exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_abcoll.py", line 497, in pop
value = self[key]
File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in __getitem__
return _DeadlockWrap(lambda: self.db[key]) # self.db[key]
File "/usr/lib/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
return function(*_args, **_kwargs)
File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in <lambda>
return _DeadlockWrap(lambda: self.db[key]) # self.db[key]
KeyError: 'b'
>>> db.pop('b', None) # This does not.
>>>
>>> FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
>>> FooChild().echobar()
Traceback (most recent call last):
File "<pyshell#214>", line 1, in <module>
FooChild().echobar()
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> FooChild().echobar
Traceback (most recent call last):
File "<pyshell#215>", line 1, in <module>
FooChild().echobar
AttributeError: 'FooChild' object has no attribute 'echobar'
>>> hasattr(FooChild, "echobar()")
True
>>> FooChild().echobar()()
Traceback (most recent call last):
File "<pyshell#217>", line 1, in <module>
FooChild().echobar()()
AttributeError: 'FooChild' object has no attribute 'echobar'
Remove those parentheses:
FooChild = type("FooChild", (Foo,), {"echobar":echo_bar})
The name of a function is without the parentheses. Appending them means to call the function. Without the parentheses you have a reference on the function itself (e. g. for passing a function to things like sort or map).
echobar() is an invalid identifier in python, so you can't access it directly i.e using the dot syntax:
>>> FooChild = type("FooChild", (Foo,), {"echobar()":10})
Use __dict__ or getattr:
>>> FooChild.__dict__['echobar()']
10
>>> getattr(FooChild, 'echobar()')
10
If you want to use it as an attribute then simply get rid of the parenthesis:
>>> FooChild = type("FooChild", (Foo,), {"echobar":10})
>>> FooChild.echobar
10
If you want to use it as a method, then:
>>> def echobar(self):return 10
>>> FooChild = type("FooChild", (Foo,), {'echobar':echobar})
>>> FooChild().echobar()
10
If you pretend to have fancy function with name echobar() in you class, only mean of accessing it is getattr:
class Foo(object):pass
echo_bar =lambda *a: 'bar'
FooChild = type("FooChild", (Foo,), {"echobar()":echo_bar})
print getattr(FooChild(), 'echobar()')()
# bar
Sorry if this question is too stupid to ask... I am a newbie on Python+Django+Bulbs+Neo4j.
I am attempting --without success-- to get an integer produced by g.gremlin.execute() while using Python+Django shell, as detailed below.
First, the query in Neo4j's Gremlin console:
gremlin> g.v(2).out
==> v[6]
==> v[4]
==> v[8]
==> v[7]
gremlin> g.v(2).out.count()
==> 4
What I intend to do it to get this result in Python+Django shell, passing it to a variable, as tried below:
>>> from bulbs.neo4jserver import Graph
>>> from bulbs.model import Node,Relationship
>>> g = Graph()
>>> sc = " g.v(vertex_id).out.count()"
>>> params = dict(vertex_id = 2)
>>> val = g.gremlin.execute(sc,params)
>>> val
<bulbs.neo4jserver.client.Neo4jResponse object at 0x243cfd0>
I can't get any further from now on.
>>> val.one()
<bulbs.neo4jserver.client.Neo4jResult object at 0x2446b90>
>>> val.one().data
>>> val.one().results
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Neo4jResult' object has no attribute 'results'
Could anyone please tell me what am I doing wrong?
Many thanks!
Raw result data is going to be in the Result object's raw attribute:
>>> from bulbs.neo4jserver import Graph
>>> from bulbs.model import Node,Relationship
>>> g = Graph()
>>> script = " g.v(vertex_id).out.count()"
>>> params = dict(vertex_id = 2)
>>> resp = g.gremlin.execute(script,params)
>>> result = resp.one()
>>> result.raw
NOTE: result.data returns an element's property data, so it will be empty unless you are returning a vertex or edge, i.e. a node or relationship in Neo4j parlance.
See...
https://github.com/espeed/bulbs/blob/master/bulbs/neo4jserver/client.py#L60
https://github.com/espeed/bulbs/blob/master/bulbs/neo4jserver/client.py#L88
https://github.com/espeed/bulbs/blob/master/bulbs/neo4jserver/client.py#L167
To see what Neo4j Server returned in the server response, you can output the Response headers and content:
>>> from bulbs.neo4jserver import Graph
>>> from bulbs.model import Node,Relationship
>>> g = Graph()
>>> script = "g.v(vertex_id).out.count()"
>>> params = dict(vertex_id = 2)
>>> resp = g.gremlin.execute(script,params)
>>> resp.headers
>>> resp.content
And if you set the loglevel to DEBUG in Config, you'll be able to see what's being sent to the server on each request. When DEBUG is enabled, Bulbs also sets the raw attribute on the Response object (not to be confused with the raw attribute that is always set on the Result object). Response.raw will contain the raw server response:
>>> from bulbs.neo4jserver import Graph, DEBUG
>>> from bulbs.model import Node,Relationship
>>> g = Graph()
>>> g.config.set_logger(DEBUG)
>>> script = " g.v(vertex_id).out.count()"
>>> params = dict(vertex_id = 2)
>>> resp = g.gremlin.execute(script,params)
>>> resp.raw
See...
https://github.com/espeed/bulbs/blob/master/bulbs/config.py#L70
https://github.com/espeed/bulbs/blob/master/bulbs/neo4jserver/client.py#L221
http://bulbflow.com/quickstart/#enable-debugging
To turn off DEBUG, set the loglevel back to ERROR:
>>> from bulbs.neo4jserver import ERROR
>>> g.config.set_logger(ERROR)
See...
http://bulbflow.com/quickstart/#disable-debugging