student
student

Reputation: 1646

Switch into object's namespace locally

Consider the following simple example:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
mytable["z"] = mytable.x + mytable.y
mytable["q"] = mytable.z**2
mytable

for example with cat test.dat:

x       y
1       5
2       6
3       7
4       8

If I use something like this for example from ipython3 I want to "factor out" the mytable keyword as in this pseudo code:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
cd mytable
   z = x + y
   q = z**2
mytable

Are there any possibilities to simplify syntax like this. It is ok, if the solutions uses additional ipython features.

Remark: I used a "cd" keyword following pgf/tikz syntax where something like this is possible.

Upvotes: 1

Views: 36

Answers (1)

Alfe
Alfe

Reputation: 59426

Python's design does not really allow for this as it would lead to ambiguities. See here for a detailed discussion on the topic.

Consider a code like this:

class X(object):
  def __init__(self, q):
    self.q = q

x = X(4)
q = 3

# del x.q

with x:
  print q

This should print 4, I assume.

Now, consider to enable the del statement. Should this then raise an error (because of the missing q in x?) or should it print 3 (because of the more global variable q)? Since this is hard to decide and different people could validly have different opinions, Python decided not to have this feature at all.

Upvotes: 1

Related Questions