Python, differentiating between an empty tuple and a completely empty variable -


i'm attempting use __getattr__ handle undefined method calls on object. want end result act autoload function in perl.

this can done following code.


test.py:

#!/usr/bin/python import object  # create object object = object.object()  # try , access "thing" attribute object.thing  # try , call "thing" method object.thing()  # call "thing" method arguments object.thing("arg1", "arg2") 

object.py:

class test(object): """class testing purposes!"""      def __getattr__(self, name):         """handle undefined method calls!"""          def __autoload(*args):             """hack simulate perl's autoload function."""              # args!             return self.f(name, *args)         return __autoload      # print args (as example)     def f(self, name, *args):     """do args!"""          print args         return 

output:

>test.py () ('arg1', 'arg2') 

the problem is, want work method calls. if attempts access attribute doesn't exist want script throw exception.

this means when try , access "thing" attribute want fail, should work in other 2 situations.


what think work:

if find way python differentiate empty tuple () , empty variable might doable. can see, object.thing call did not print because args variable did not contain anything.

is there way trap on in python , raise exception if args variable empty , not empty tuple?

as hacky autoload proxy, can like:

class thing(object):     def __init__(self, default):         self.default = default      def __getattr__(self, name):         try:             return getattr(self.default, name)         except attributeerror:             return self.default     

then use like:

first define default function:

>>> def auto(*args, **kwargs): >>>     print 'default', args, kwargs 

then:

>>> thing(auto).not_defined() default () {} >>> thing(auto).not_defined(123) default (123,) {} >>> thing(auto).not_defined(123, mu=345) default (123,) {'mu': 345} 

Comments